Skip to content
Snippets Groups Projects
Commit 89b027d4 authored by jez04's avatar jez04
Browse files

feat: :tada: solution

parent 65c06be6
Branches
No related merge requests found
package lab;
@FunctionalInterface
public interface DeadListener {
void monsterDead();
}
...@@ -6,4 +6,5 @@ public interface DrawableSimulable { ...@@ -6,4 +6,5 @@ public interface DrawableSimulable {
void draw(GraphicsContext gc); void draw(GraphicsContext gc);
void simulate(double deltaT); void simulate(double deltaT);
int getZIndex();
} }
...@@ -16,52 +16,64 @@ public class GameController { ...@@ -16,52 +16,64 @@ public class GameController {
@FXML @FXML
private Slider angle; private Slider angle;
@FXML @FXML
private Canvas canvas; private Canvas canvas;
@FXML @FXML
private Slider speed; private Slider speed;
@FXML @FXML
private Label playerName; private Label playerName;
private int deadCount;
@FXML
void spawn(ActionEvent event) { @FXML
level.getPlayer().spawn(); void spawn(ActionEvent event) {
// level.getPlayer().spawn();
} Monster monster = new Monster(level);
monster.addDeadListener(new MujListener());
@FXML monster.addDeadListener(new Dead());
void initialize() { monster.addDeadListener(() -> System.out.println("another lambda dead"));
assert angle != null : "fx:id=\"angle\" was not injected: check your FXML file 'gameWindow.fxml'."; monster.addDeadListener(this::updateDeadLabel);
assert canvas != null : "fx:id=\"canvas\" was not injected: check your FXML file 'gameWindow.fxml'."; level.add(monster);
assert speed != null : "fx:id=\"speed\" was not injected: check your FXML file 'gameWindow.fxml'.";
angle.valueProperty().addListener(new ChangeListener<Number>() { }
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { private void updateDeadLabel() {
level.getPlayer().setAngle(newValue.doubleValue()); deadCount++;
} playerName.setText(String.format("Deads: %03d", deadCount));
}); }
speed.valueProperty().addListener(new ChangeListener<Number>() {
@Override @FXML
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { void initialize() {
level.getPlayer().setSpeed(newValue.doubleValue()); assert angle != null : "fx:id=\"angle\" was not injected: check your FXML file 'gameWindow.fxml'.";
} assert canvas != null : "fx:id=\"canvas\" was not injected: check your FXML file 'gameWindow.fxml'.";
}); assert speed != null : "fx:id=\"speed\" was not injected: check your FXML file 'gameWindow.fxml'.";
angle.valueProperty()
} .addListener((observable, oldValue, newValue) -> level.getPlayer().setAngle(newValue.doubleValue()));
speed.valueProperty()
public void startGame(String name, int numberOfMonsters) { .addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
playerName.setText(name); level.getPlayer().setSpeed(newValue.doubleValue());
level = new Level(canvas.getWidth(), canvas.getHeight(), numberOfMonsters); });
}
public void startGame(String name, int numberOfMonsters) {
playerName.setText(name);
level = new Level(canvas.getWidth(), canvas.getHeight(), numberOfMonsters);
timer = new DrawingThread(canvas, level); timer = new DrawingThread(canvas, level);
timer.start(); timer.start();
} }
public void stop() { public void stop() {
timer.stop(); timer.stop();
} }
private class Dead implements DeadListener {
@Override
public void monsterDead() {
System.out.println("Named dead");
}
}
} }
package lab; package lab;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javafx.geometry.Dimension2D; import javafx.geometry.Dimension2D;
import javafx.geometry.Point2D; import javafx.geometry.Point2D;
import javafx.scene.canvas.GraphicsContext; import javafx.scene.canvas.GraphicsContext;
...@@ -9,20 +13,22 @@ public class Level { ...@@ -9,20 +13,22 @@ public class Level {
private double width; private double width;
private double height; private double height;
private DrawableSimulable[] entities; private List<DrawableSimulable> entities;
private List<DrawableSimulable> entitiesToAdd = new ArrayList<>();
private List<DrawableSimulable> entitiesToRemove = new ArrayList<>();
private Player player; private Player player;
public Level(double width, double height, int monsterCount) { public Level(double width, double height, int monsterCount) {
this.width = width; this.width = width;
this.height = height; this.height = height;
player = new Player(this, new Point2D(20, 250), new Point2D(100, -20)); player = new Player(this, new Point2D(20, 250), new Point2D(100, -20));
entities = new DrawableSimulable[monsterCount+4]; entities = new ArrayList<>();
entities[0] = new NicerObstacle(this, new Point2D(20, 150)); entities.add(new NicerObstacle(this, new Point2D(20, 150)));
entities[1] = new Obstacle(this, new Point2D(300, 200), new Dimension2D(80, 40)); entities.add(new Obstacle(this, new Point2D(300, 200), new Dimension2D(80, 40)));
entities[2] = new Obstacle(this); entities.add(new Obstacle(this));
entities[3] = player; entities.add(player);
for (int i = 4; i < entities.length; i++) { for (int i = 0; i < monsterCount; i++) {
entities[i] = new Monster(this); entities.add(new Monster(this));
} }
} }
...@@ -38,10 +44,10 @@ public class Level { ...@@ -38,10 +44,10 @@ public class Level {
for (DrawableSimulable entity : entities) { for (DrawableSimulable entity : entities) {
entity.simulate(delay); entity.simulate(delay);
} }
for (int i = 0; i < entities.length; i++) { for (int i = 0; i < entities.size(); i++) {
if (entities[i] instanceof Collisionable c1) { if (entities.get(i) instanceof Collisionable c1) {
for (int j = i + 1; j < entities.length; j++) { for (int j = i + 1; j < entities.size(); j++) {
if (entities[j] instanceof Collisionable c2) { if (entities.get(j) instanceof Collisionable c2) {
if (c1.intersect(c2.getBoundingBox())) { if (c1.intersect(c2.getBoundingBox())) {
c1.hitBy(c2); c1.hitBy(c2);
c2.hitBy(c1); c2.hitBy(c1);
...@@ -50,6 +56,17 @@ public class Level { ...@@ -50,6 +56,17 @@ public class Level {
} }
} }
} }
entities.removeAll(entitiesToRemove);
entities.addAll(entitiesToAdd);
entitiesToAdd.clear();
entitiesToRemove.clear();
entities.sort(Comparator.comparing(DrawableSimulable::getZIndex));
// entities.sort(new Comparator<DrawableSimulable>() {
// @Override
// public int compare(DrawableSimulable o1, DrawableSimulable o2) {
// return Integer.compare(o1.getZIndex(), o2.getZIndex());
// }
// });
} }
public double getWidth() { public double getWidth() {
...@@ -63,5 +80,13 @@ public class Level { ...@@ -63,5 +80,13 @@ public class Level {
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public void add(DrawableSimulable entity) {
entitiesToAdd.add(entity);
}
public void remove(DrawableSimulable entity) {
entitiesToRemove.add(entity);
}
} }
package lab; package lab;
import java.util.ArrayList;
import java.util.List;
import java.util.Random; import java.util.Random;
import javafx.geometry.Dimension2D;
import javafx.geometry.Point2D; import javafx.geometry.Point2D;
import javafx.geometry.Rectangle2D; import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext; import javafx.scene.canvas.GraphicsContext;
...@@ -13,9 +16,10 @@ public class Monster extends WorldEntity implements Collisionable { ...@@ -13,9 +16,10 @@ public class Monster extends WorldEntity implements Collisionable {
private Image image; private Image image;
private Point2D speed; private Point2D speed;
private List<DeadListener> deadListeners = new ArrayList<>();
public Monster(Level level) { public Monster(Level level) {
super(level, new Point2D(0, 0)); super(level, new Point2D(0, 0), 100);
image = new Image(getClass().getResourceAsStream("red-monster.gif")); image = new Image(getClass().getResourceAsStream("red-monster.gif"));
position = new Point2D(level.getWidth() * 0.5 + RANDOM.nextDouble(level.getWidth() * 0.5 - image.getWidth()), position = new Point2D(level.getWidth() * 0.5 + RANDOM.nextDouble(level.getWidth() * 0.5 - image.getWidth()),
RANDOM.nextDouble(level.getHeight())); RANDOM.nextDouble(level.getHeight()));
...@@ -56,9 +60,24 @@ public class Monster extends WorldEntity implements Collisionable { ...@@ -56,9 +60,24 @@ public class Monster extends WorldEntity implements Collisionable {
@Override @Override
public void hitBy(Collisionable another) { public void hitBy(Collisionable another) {
if (another instanceof Player) { if (another instanceof Player) {
changeDirection(); level.remove(this);
level.add(new Obstacle(level, getPosition(), new Dimension2D(60, 30)));
fireMonsterDead();
} }
} }
public boolean addDeadListener(DeadListener e) {
return deadListeners.add(e);
}
public boolean removeDeadListener(DeadListener o) {
return deadListeners.remove(o);
}
public void fireMonsterDead() {
for (DeadListener deadListener : deadListeners) {
deadListener.monsterDead();
}
}
} }
package lab;
public class MujListener implements DeadListener {
@Override
public void monsterDead() {
System.out.println("AAAAhh!!!!");
}
}
...@@ -16,7 +16,7 @@ public class Player extends WorldEntity implements Collisionable { ...@@ -16,7 +16,7 @@ public class Player extends WorldEntity implements Collisionable {
private double angle; private double angle;
public Player(Level level, Point2D position, Point2D speed) { public Player(Level level, Point2D position, Point2D speed) {
super(level, position); super(level, position, 50);
this.speed = speed; this.speed = speed;
} }
......
...@@ -7,12 +7,19 @@ public abstract class WorldEntity implements DrawableSimulable{ ...@@ -7,12 +7,19 @@ public abstract class WorldEntity implements DrawableSimulable{
protected final Level level; protected final Level level;
protected Point2D position; protected Point2D position;
private int zIndex;
public WorldEntity(Level level, Point2D position) { public WorldEntity(Level level, Point2D position) {
this.level = level; this.level = level;
this.position = position; this.position = position;
zIndex = 0;
} }
public WorldEntity(Level level, Point2D position, int zIndex) {
this.level = level;
this.position = position;
this.zIndex = zIndex;
}
@Override @Override
public final void draw(GraphicsContext gc) { public final void draw(GraphicsContext gc) {
gc.save(); gc.save();
...@@ -26,5 +33,9 @@ public abstract class WorldEntity implements DrawableSimulable{ ...@@ -26,5 +33,9 @@ public abstract class WorldEntity implements DrawableSimulable{
return position; return position;
} }
public int getZIndex() {
return zIndex;
}
} }
...@@ -3,13 +3,23 @@ package jez04.structure.test; ...@@ -3,13 +3,23 @@ package jez04.structure.test;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
...@@ -24,197 +34,112 @@ import org.reflections.util.ConfigurationBuilder; ...@@ -24,197 +34,112 @@ import org.reflections.util.ConfigurationBuilder;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext;
class ClassStructureTest { class ClassStructureTest {
private static final String drawableSimulableName = "DrawableSimulable"; StructureHelper helper = new StructureHelper();
private static final String collisionableName = "Collisionable";
Set<String> allClasses = getNameOfAllClasses();
@Test @Test
void gameControllerExistenceTest() { void gameControllerExistenceTest() {
classExist("GameController"); helper.classExist("GameController");
Class<?> c = getClass("GameController");
hasPropertyWithAnnotation(c, ".*", FXML.class);
hasMethodRegexp(c, ".*", void.class, ActionEvent.class);
} }
@Test @Test
void gameControllerFxmlTest() { void gameControllerFxmlTest() {
classExist("GameController"); helper.classExist("GameController");
Class<?> c = getClass("GameController"); Class<?> c = helper.getClass("GameController");
hasPropertyWithAnnotation(c, ".*", FXML.class); helper.hasPropertyWithAnnotation(c, ".*", FXML.class);
}
@Test
void gameControllerActionEventTest() {
classExist("GameController");
Class<?> c = getClass("GameController");
hasMethodRegexp(c, ".*", void.class, ActionEvent.class);
} }
@Test @Test
void cannonExistenceTest() { void gameControllerActionMethodTest() {
classExist("Player"); helper.classExist("GameController");
} Class<?> c = helper.getClass("GameController");
@Test helper.hasMethodRegexp(c, ".*", void.class, ActionEvent.class);
void cannonExistenceSetAngleTest() {
classExist("Player");
Class<?> c = getClass("Player");
hasMethod(c, "setAngle");
} }
@Test
void cannonExistenceSetSpeedTest() {
classExist("Player");
Class<?> c = getClass("Player");
hasMethod(c, "setSpeed");
}
private void isInterface(Class<?> c) { @Test
assertTrue(c.isInterface(), c.getName() + " have to be interface."); void gameControllerLambdasTest() {
} helper.classExist("GameController");
Class<?> c = helper.getClass("GameController");
private void classExist(String name) { long lamdaCount = helper.countMethodRegexp(c, "lambda\\$.*");
assertTrue(allClasses.stream().anyMatch(c -> c.endsWith(name)), "Interface " + name + " not found"); long innerClasscount = helper.countClassesRegexp(".*GameController\\$.*");
assertTrue(lamdaCount + innerClasscount >= 3,
"At least 3 inner classes or lamdas required for GameController but only "
+ (lamdaCount + innerClasscount) + " found.");
} }
private Class<?> getClass(String name) { @Test
String className = allClasses.stream().filter(c -> c.endsWith(name)).findAny().orElse(null); void deadListenerExistenceTest() {
if (className == null) { helper.classExist("DeadListener");
Assertions.fail("Class " + name + " not found.");
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintStream ps = new PrintStream(baos, true)) {
e.printStackTrace(ps);
} catch (Exception e2) {
Assertions.fail(e2.getMessage());
}
String stackTrace = baos.toString();
Assertions.fail("Class " + name + " not found.\n" + stackTrace);
return null;
}
} }
private void hasProperty(Class<?> classDef, String propertyNameRegexp, Class<?> type, boolean array) { @Test
List<Field> fields = Arrays.asList(classDef.getDeclaredFields()); void deadListenerEventMethodTest() {
assertTrue(fields.stream().anyMatch(f -> { helper.classExist("DeadListener");
if (f.getName().matches(propertyNameRegexp)) { Class<?> c = helper.getClass("DeadListener");
if (array) { helper.hasMethod(c, "monsterDead");
return f.getType().isArray() && f.getType().getComponentType().equals(type);
} else {
return f.getType().equals(type);
}
}
return false;
}), "No field " + propertyNameRegexp + " of type " + type.getName() + " (is array " + array + ") in class "
+ classDef.getName());
} }
private void hasPropertyWithAnnotation(Class<?> classDef, String propertyNameRegexp, Class<?> annotation) { @Test
List<Field> fields = Arrays.asList(classDef.getDeclaredFields()); void sceneCollectionTest() {
assertTrue( helper.classExist("Level");
fields.stream().filter(f -> f.getName().matches(propertyNameRegexp)) Class<?> c = helper.getClass("Level");
.flatMap(f -> Arrays.asList( long collectionCount = Arrays.asList(c.getDeclaredFields()).stream()
f.getAnnotations()).stream()).map(a -> a.annotationType()).anyMatch(a -> .filter(f -> Collection.class.isAssignableFrom(f.getType())).count();
a.equals(annotation)), assertTrue(collectionCount >= 3, "lab.Scene require atleast 3 filed of type/subtype Collection, but only "
"No field " + propertyNameRegexp + " with annotation " + annotation.getName() + " in class " + collectionCount + " found.");
+ classDef.getName());
} }
private void hasMethod(Class<?> interfaceDef, String methodName, Class<?> returnType) { @Test
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods()); void sceneMethodAddTest() {
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName); helper.classExist("Level");
assertTrue( Class<?> c = helper.getClass("Level");
methods.stream().filter(m -> m.getName().contains(methodName)) helper.hasMethod(c, "add", void.class, helper.getClass("DrawableSimulable"));
.anyMatch(m -> m.getReturnType().equals(returnType)), ;
"Method " + methodName + " not return " + returnType.getName());
} }
private void hasMethod(Class<?> interfaceDef, String methodName, Class<?> returnType, Class<?>... params) { @Test
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods()); void levelMethodRemoveTest() {
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName); helper.classExist("Level");
assertTrue( Class<?> c = helper.getClass("Level");
methods.stream().filter(m -> m.getName().contains(methodName)) helper.hasMethod(c, "remove", void.class, helper.getClass("DrawableSimulable"));
.filter(m -> m.getReturnType().equals(returnType)) ;
.anyMatch(m -> Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodName + " has no all parrams:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
} }
private void hasMethodRegexp(Class<?> interfaceDef, String methodNameRegexp, Class<?> returnType, Class<?>... params) { @Test
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods()); void monsterMethodAddTest() {
assertTrue(methods.stream().anyMatch(m -> m.getName().matches(methodNameRegexp)), "No method " + methodNameRegexp); helper.classExist("Monster");
assertTrue( Class<?> c = helper.getClass("Monster");
methods.stream().filter(m -> m.getName().matches(methodNameRegexp)) helper.hasMethod(c, "addDeadListener");
.filter(m -> m.getReturnType().equals(returnType))
.anyMatch(m ->
Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodNameRegexp + " has no all parrams:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
}
private void hasMethod(Class<?> interfaceDef, boolean finalTag, boolean abstractTag, String methodName,
Class<?> returnType, Class<?>... params) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName);
assertTrue(
methods.stream().filter(m -> m.getName().contains(methodName))
.filter(m -> m.getReturnType().equals(returnType)
&& (Modifier.isAbstract(m.getModifiers()) == abstractTag)
&& (Modifier.isFinal(m.getModifiers()) == finalTag))
.anyMatch(m -> Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodName + " has no all params:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
} }
private void hasImplements(Class<?> clazz, String... interfaceNames) { @Test
List<Class<?>> interfaces = new ArrayList<>(); void monsterMethodRemoveTest() {
Arrays.asList(interfaceNames).stream().map(name -> getClass(name)).forEach(c -> interfaces.add(c)); helper.classExist("Monster");
assertTrue(Arrays.asList(clazz.getInterfaces()).containsAll(interfaces), "Class not implements all interfaces:" Class<?> c = helper.getClass("Monster");
+ interfaces.stream().map(Class::getName).collect(Collectors.joining(", "))); Class<?> l = helper.getClass("DeadListener");
helper.hasMethodRegexp(c, "remove.*", List.of(void.class, boolean.class), l);
} }
private void hasExtends(Class<?> clazz, String parentName) { @Test
Class<?> parent = getClass(parentName); void monsterMethodFireTest() {
assertTrue(clazz.getSuperclass().equals(parent), helper.classExist("Monster");
"Class " + clazz.getName() + " not extends class " + parentName); Class<?> c = helper.getClass("Monster");
assertTrue(helper.countMethodRegexp(c, "fire.*") > 0, "Method fire.* in LochNess not found.");
} }
private void hasMethod(Class<?> interfaceDef, String methodName) { @Test
List<Method> methods = Arrays.asList(interfaceDef.getMethods()); void zIndexMethodTest() {
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName); helper.classExist("DrawableSimulable");
Class<?> c = helper.getClass("DrawableSimulable");
helper.hasMethodRegexp(c, "get[zZ][iI]ndex", int.class, new Class[0]);
} }
private Set<String> getNameOfAllClasses() { @Test
List<String> initClassesName = Arrays.asList("lab.Routines", "lab.App", "lab.DrawingThread"); void zIndexFieldTest() {
for (String className : initClassesName) { helper.classExist("WorldEntity");
try { Class<?> c = helper.getClass("WorldEntity");
Class.forName(className); helper.hasProperty(c, "[zZ][iI]ndex", int.class, false);
} catch (ClassNotFoundException e) {
System.out.println(String.format("Class '%s' cannot be loaded: %s", className, e.getMessage()));
}
}
Set<String> allClasses = new HashSet<>();
for (Package p : Package.getPackages()) {
if (p.getName().startsWith("java.") || p.getName().startsWith("com.") || p.getName().startsWith("jdk.")
|| p.getName().startsWith("javafx.") || p.getName().startsWith("org.")
|| p.getName().startsWith("sun.") || p.getName().startsWith("javax.")
|| p.getName().startsWith("javassist")) {
continue;
}
System.out.println(p.getName());
Configuration conf = new ConfigurationBuilder().addScanners(Scanners.SubTypes.filterResultsBy(pc -> true))
.forPackages(p.getName());
Reflections reflections = new Reflections(conf);
allClasses.addAll(reflections.getAll(Scanners.SubTypes.filterResultsBy(c -> {
System.out.println(c);
return true;
})));
}
return allClasses;
} }
} }
package jez04.structure.test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.reflections.Configuration;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ConfigurationBuilder;
class StructureHelper {
Set<String> allClasses = getNameOfAllClasses();
public void isInterface(Class<?> c) {
assertTrue(c.isInterface(), c.getName() + " have to be interface.");
}
public void classExist(String name) {
assertTrue(allClasses.stream().anyMatch(c -> c.endsWith(name)), "Class/Interface " + name + " not found");
}
public Class<?> getClass(String name) {
String className = allClasses.stream().filter(c -> c.endsWith(name)).findAny().orElse(null);
if (className == null) {
Assertions.fail("Class " + name + " not found.");
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintStream ps = new PrintStream(baos, true)) {
e.printStackTrace(ps);
} catch (Exception e2) {
Assertions.fail(e2.getMessage());
}
String stackTrace = baos.toString();
Assertions.fail("Class " + name + " not found.\n" + stackTrace);
return null;
}
}
public void hasProperty(Class<?> classDef, String propertyNameRegexp, Class<?> type, boolean array) {
List<Field> fields = Arrays.asList(classDef.getDeclaredFields());
assertTrue(fields.stream().anyMatch(f -> {
if (f.getName().matches(propertyNameRegexp)) {
if (array) {
return f.getType().isArray() && f.getType().getComponentType().equals(type);
} else {
return f.getType().equals(type);
}
}
return false;
}), "No field " + propertyNameRegexp + " of type " + type.getName() + " (is array " + array + ") in class "
+ classDef.getName());
}
public void hasPropertyWithAnnotation(Class<?> classDef, String propertyNameRegexp, Class<?> annotation) {
List<Field> fields = Arrays.asList(classDef.getDeclaredFields());
assertTrue(
fields.stream().filter(f -> f.getName().matches(propertyNameRegexp))
.flatMap(f -> Arrays.asList(f.getAnnotations()).stream()).map(a -> a.annotationType())
.anyMatch(a -> a.equals(annotation)),
"No field " + propertyNameRegexp + " with annotation " + annotation.getName() + " in class "
+ classDef.getName());
}
public void hasMethod(Class<?> interfaceDef, String methodName, Class<?> returnType) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName);
assertTrue(
methods.stream().filter(m -> m.getName().contains(methodName))
.anyMatch(m -> m.getReturnType().equals(returnType)),
"Method " + methodName + " not return " + returnType.getName());
}
public void hasMethod(Class<?> interfaceDef, String methodName, Class<?> returnType, Class<?>... params) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName);
assertTrue(
methods.stream().filter(m -> m.getName().contains(methodName))
.filter(m -> m.getReturnType().equals(returnType))
.anyMatch(m -> Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodName + " has no all parrams:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
}
public long countMethodRegexp(Class<?> interfaceDef, String methodNameRegexp) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
return methods.stream().filter(m -> m.getName().matches(methodNameRegexp)).count();
}
public long countClassesRegexp(String classNameRegexp) {
return getNameOfAllClasses().stream().filter(className -> className.matches(classNameRegexp)).count();
}
public void hasMethodRegexp(Class<?> interfaceDef, String methodNameRegexp, Class<?> returnType,
Class<?>... params) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().matches(methodNameRegexp)),
"No method " + methodNameRegexp);
assertTrue(
methods.stream().filter(
m ->
m.getName().matches(methodNameRegexp))
.filter(
m ->
m.getReturnType().equals(returnType))
.anyMatch(m ->
Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodNameRegexp + " has no all parrams:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
}
public void hasMethodRegexp(Class<?> interfaceDef, String methodNameRegexp, Collection<Class<?>> returnTypeOnOf,
Class<?>... params) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().matches(methodNameRegexp)),
"No method " + methodNameRegexp);
assertTrue(
methods.stream().filter(
m ->
m.getName().matches(methodNameRegexp))
.filter(
m ->
returnTypeOnOf.contains(m.getReturnType()))
.anyMatch(m ->
Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodNameRegexp + " has no all parrams:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
}
public void hasMethod(Class<?> interfaceDef, boolean finalTag, boolean abstractTag, String methodName,
Class<?> returnType, Class<?>... params) {
List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName);
assertTrue(
methods.stream().filter(m -> m.getName().contains(methodName))
.filter(m -> m.getReturnType().equals(returnType)
&& (Modifier.isAbstract(m.getModifiers()) == abstractTag)
&& (Modifier.isFinal(m.getModifiers()) == finalTag))
.anyMatch(m -> Arrays.asList(m.getParameterTypes()).containsAll(Arrays.asList(params))),
"Method " + methodName + " has no all params:"
+ Arrays.asList(params).stream().map(Class::getName).collect(Collectors.joining(", ")));
}
public void hasImplements(Class<?> clazz, String... interfaceNames) {
List<Class<?>> interfaces = new ArrayList<>();
Arrays.asList(interfaceNames).stream().map(name -> getClass(name)).forEach(c -> interfaces.add(c));
assertTrue(Arrays.asList(clazz.getInterfaces()).containsAll(interfaces), "Class not implements all interfaces:"
+ interfaces.stream().map(Class::getName).collect(Collectors.joining(", ")));
}
public void hasExtends(Class<?> clazz, String parentName) {
Class<?> parent = getClass(parentName);
assertTrue(clazz.getSuperclass().equals(parent),
"Class " + clazz.getName() + " not extends class " + parentName);
}
public void hasMethod(Class<?> interfaceDef, String methodName) {
List<Method> methods = Arrays.asList(interfaceDef.getMethods());
assertTrue(methods.stream().anyMatch(m -> m.getName().contains(methodName)), "No method " + methodName);
}
public Set<String> getNameOfAllClasses() {
List<String> initClassesName = new ArrayList<>();
dynamicaliFoundSomeClass(initClassesName);
initClassesName.addAll(List.of("lab.Routines", "lab.App", "lab.DrawingThread"));
for (String className : initClassesName) {
try {
Class.forName(className);
break;
} catch (ClassNotFoundException e) {
System.out.println(String.format("Class '%s' cannot be loaded: %s", className, e.getMessage()));
}
}
Set<String> allClasses = new HashSet<>();
for (Package p : Package.getPackages()) {
if (p.getName().startsWith("java.") || p.getName().startsWith("com.") || p.getName().startsWith("jdk.")
|| p.getName().startsWith("javafx.") || p.getName().startsWith("org.")
|| p.getName().startsWith("sun.") || p.getName().startsWith("javax.")
|| p.getName().startsWith("javassist")) {
continue;
}
System.out.println(p.getName());
Configuration conf = new ConfigurationBuilder().addScanners(Scanners.SubTypes.filterResultsBy(pc -> true))
.forPackages(p.getName());
Reflections reflections = new Reflections(conf);
allClasses.addAll(reflections.getAll(Scanners.SubTypes.filterResultsBy(c -> {
System.out.println(c);
return true;
})));
}
for (String string : allClasses) {
System.out.println(string);
}
return allClasses;
}
public void dynamicaliFoundSomeClass(List<String> initClassesName) {
URL myClassUrl = StructureHelper.class.getResource("ClassStructureTest.class");
myClassUrl.getFile();
try {
Path classRoot = Paths.get(myClassUrl.toURI()).getParent().getParent().getParent().getParent();
if ("test-classes".equals(classRoot.getFileName().toString())) {
classRoot = classRoot.getParent().resolve("classes");
}
System.out.println("class root: " + classRoot);
final Path classRootFinal = classRoot;
Files.walkFileTree(classRoot, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (List.of("jez04", "META-INF").contains(dir.getFileName().toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("VISIT: " + file);
if ("module-info.class".equals(file.getFileName().toString())) {
return FileVisitResult.CONTINUE;
}
if (!file.getFileName().toString().endsWith(".class")) {
return FileVisitResult.CONTINUE;
}
String foundClassName = classRootFinal.relativize(file).toString();
foundClassName = foundClassName.substring(0, foundClassName.length() - 6)
.replace(File.separatorChar, '.');
initClassesName.add(foundClassName);
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment