From 08d53c801942f30202c3a17bbeccad1b5a1a5265 Mon Sep 17 00:00:00 2001 From: Dimitris Anyfadakis Date: Thu, 4 Jan 2024 18:46:11 +0100 Subject: [PATCH] Refactor parser --- README.md | 2 + src/main/java/controller/Controller.java | 2 +- .../java/controller/ControllerFactory.java | 9 +- src/main/java/controller/ControllerType.java | 2 + .../java/manager/ClassDiagramManager.java | 9 +- .../java/manager/DiagramManagerFactory.java | 2 +- src/main/java/manager/DiagramType.java | 3 + .../java/manager/PackageDiagramManager.java | 13 +- src/main/java/manager/SourceProject.java | 24 +- src/main/java/model/diagram/ClassDiagram.java | 4 +- .../diagram/GraphClassDiagramConverter.java | 12 +- .../diagram/GraphPackageDiagramConverter.java | 13 +- .../java/model/diagram/PackageDiagram.java | 6 +- .../java/model/diagram/ShadowCleaner.java | 25 +- .../ClassDiagramArrangementManager.java | 44 +- .../PackageDiagramArrangementManager.java | 35 +- .../AdvancedFruchtermanReingold.java | 6 +- .../algorithms/AdvancedSpring.java | 6 +- .../algorithms/FruchtermanReingold.java | 6 +- .../arrangement/algorithms/KamadaKawai.java | 10 +- .../algorithms/LayoutAlgorithm.java | 3 - .../algorithms/LayoutAlgorithmType.java | 1 + .../arrangement/algorithms/Spring.java | 6 +- .../arrangement/algorithms/Sugiyama.java | 9 +- .../arrangement/geometry/DiagramGeometry.java | 9 +- .../ClassifierVertexSerializer.java | 16 +- .../exportation/CoordinatesUpdater.java | 22 +- .../GraphMLClassDiagramExporter.java | 17 +- .../diagram/exportation/GraphMLFile.java | 26 +- .../GraphMLPackageDiagramExporter.java | 21 +- .../JavaFXClassDiagramExporter.java | 12 +- .../JavaFXPackageDiagramExporter.java | 11 +- .../exportation/PackageVertexSerializer.java | 54 +- .../PlantUMLClassDiagramImageExporter.java | 42 +- .../PlantUMLClassDiagramTextExporter.java | 25 +- .../PlantUMLPackageDiagramImageExporter.java | 54 +- .../PlantUMLPackageDiagramTextExporter.java | 31 +- .../graphml/GraphMLClassifierVertex.java | 47 +- .../graphml/GraphMLClassifierVertexArc.java | 17 +- .../diagram/graphml/GraphMLPackageVertex.java | 26 +- .../graphml/GraphMLPackageVertexArc.java | 12 +- .../model/diagram/graphml/GraphMLSyntax.java | 199 +++--- .../javafx/ClassifierVertexDeserializer.java | 71 +-- .../javafx/JavaFXClassDiagramLoader.java | 14 +- .../javafx/JavaFXClassVisualization.java | 17 +- .../javafx/JavaFXPackageDiagramLoader.java | 10 +- .../javafx/JavaFXPackageVisualization.java | 24 +- .../javafx/PackageVertexDeserializer.java | 46 +- .../plantuml/PlantUMLClassifierVertex.java | 2 +- .../plantuml/PlantUMLClassifierVertexArc.java | 2 +- .../plantuml/PlantUMLPackageVertex.java | 2 +- .../plantuml/PlantUMLPackageVertexArc.java | 3 +- src/main/java/model/graph/Arc.java | 2 +- src/main/java/model/graph/ArcType.java | 10 +- .../java/model/graph/ClassifierVertex.java | 58 +- src/main/java/model/graph/ModifierType.java | 12 +- src/main/java/model/graph/PackageVertex.java | 45 +- .../java/model/graph/VertexCoordinate.java | 18 + src/main/java/model/graph/VertexType.java | 2 + src/main/java/parser/FileVisitor.java | 338 +++++++++++ .../java/parser/IRelationshipIdentifier.java | 35 ++ src/main/java/parser/Interpreter.java | 183 +++--- src/main/java/parser/PackageNodeCleaner.java | 17 +- src/main/java/parser/ProjectParser.java | 70 +++ .../java/parser/RelationshipIdentifier.java | 209 +++++++ src/main/java/parser/factory/Parser.java | 27 +- .../parser/factory/ProjectParserFactory.java | 7 +- .../javaparser/JavaparserFileVisitor.java | 292 --------- .../parser/javaparser/JavaparserLeafNode.java | 88 --- .../javaparser/JavaparserProjectParser.java | 75 --- .../JavaparserRelationshipIdentifier.java | 98 --- src/main/java/parser/jdt/JDTFileVisitor.java | 176 ------ src/main/java/parser/jdt/JDTLeafNode.java | 43 -- .../java/parser/jdt/JDTProjectParser.java | 80 --- .../parser/jdt/JDTRelationshipIdentifier.java | 90 --- src/main/java/parser/tree/LeafNode.java | 126 +--- .../java/parser/tree/LeafNodeBuilder.java | 119 ++++ src/main/java/parser/tree/ModifierType.java | 2 + src/main/java/parser/tree/NodeType.java | 1 + src/main/java/parser/tree/PackageNode.java | 101 ++-- src/main/java/parser/tree/Relationship.java | 2 +- .../parser/tree/RelationshipIdentifier.java | 131 ---- .../java/parser/tree/RelationshipType.java | 1 + src/main/java/view/DiagramCreation.java | 2 +- src/main/java/view/DiagramVisualization.java | 6 +- .../view/DiagramVisualizationController.java | 7 +- .../java/view/FileAndDirectoryUtility.java | 2 +- src/main/java/view/ProjectTreeView.java | 2 +- .../java/manager/ClassDiagramManagerTest.java | 165 ++++- .../manager/PackageDiagramManagerTest.java | 31 +- .../model/GraphClassDiagramConverterTest.java | 24 +- .../GraphPackageDiagramConverterTest.java | 26 +- src/test/java/model/ShadowCleanerTest.java | 81 ++- .../GraphMLClassDiagramExporterTest.java | 38 +- .../JavaFXClassDiagramExporterTest.java | 169 +++--- .../JavaFXPackageDiagramExporterTest.java | 31 +- .../PlantUMLClassDiagramTextExporterTest.java | 61 +- .../graphml/GraphMLPackageVertexArcTest.java | 55 +- .../graphml/GraphMLPackageVertexTest.java | 55 +- .../GraphMLSinkPackageVertexArcTest.java | 54 +- .../graphml/GraphMLSinkPackageVertexTest.java | 90 +-- .../javafx/JavaFXClassDiagramLoaderTest.java | 60 +- .../JavaFXPackageDiagramLoaderTest.java | 80 ++- .../PlantUMLClassifierVertexArcTest.java | 4 +- .../PlantUMLClassifierVertexTest.java | 187 +++--- .../PlantUMLPackageVertexArcTest.java | 61 +- .../plantuml/PlantUMLPackageVertexTest.java | 58 +- src/test/java/parser/FileVisitorTest.java | 273 +++++++++ src/test/java/parser/InterpreterTest.java | 124 ++-- .../java/parser/PackageNodeCleanerTest.java | 119 +++- src/test/java/parser/ProjectParserTest.java | 567 ++++++++++++++++++ ...t.java => RelationshipIdentifierTest.java} | 210 +++++-- .../javaparser/JavaparserFileVisitorTest.java | 151 ----- .../JavaparserProjectParserTest.java | 220 ------- .../java/parser/jdt/JDTFileVisitorTest.java | 121 ---- .../java/parser/jdt/JDTProjectParserTest.java | 203 ------- .../jdt/JDTRelationshipIdentifierTest.java | 227 ------- .../src/bicycleBody/Bicycle.java | 2 +- .../resources/ParserTesting/EnumSample.java | 2 + .../resources/ParserTesting/EnumTest.java | 4 - .../ParserTesting/InnerClassSample.java | 9 + ...ionTest.java => ObjectCreationSample.java} | 9 +- 122 files changed, 3637 insertions(+), 3495 deletions(-) create mode 100644 src/main/java/model/graph/VertexCoordinate.java create mode 100644 src/main/java/parser/FileVisitor.java create mode 100644 src/main/java/parser/IRelationshipIdentifier.java create mode 100644 src/main/java/parser/ProjectParser.java create mode 100644 src/main/java/parser/RelationshipIdentifier.java delete mode 100644 src/main/java/parser/javaparser/JavaparserFileVisitor.java delete mode 100644 src/main/java/parser/javaparser/JavaparserLeafNode.java delete mode 100644 src/main/java/parser/javaparser/JavaparserProjectParser.java delete mode 100644 src/main/java/parser/javaparser/JavaparserRelationshipIdentifier.java delete mode 100644 src/main/java/parser/jdt/JDTFileVisitor.java delete mode 100644 src/main/java/parser/jdt/JDTLeafNode.java delete mode 100644 src/main/java/parser/jdt/JDTProjectParser.java delete mode 100644 src/main/java/parser/jdt/JDTRelationshipIdentifier.java create mode 100644 src/main/java/parser/tree/LeafNodeBuilder.java delete mode 100644 src/main/java/parser/tree/RelationshipIdentifier.java create mode 100644 src/test/java/parser/FileVisitorTest.java create mode 100644 src/test/java/parser/ProjectParserTest.java rename src/test/java/parser/{javaparser/JavaparserRelationshipIdentifierTest.java => RelationshipIdentifierTest.java} (50%) delete mode 100644 src/test/java/parser/javaparser/JavaparserFileVisitorTest.java delete mode 100644 src/test/java/parser/javaparser/JavaparserProjectParserTest.java delete mode 100644 src/test/java/parser/jdt/JDTFileVisitorTest.java delete mode 100644 src/test/java/parser/jdt/JDTProjectParserTest.java delete mode 100644 src/test/java/parser/jdt/JDTRelationshipIdentifierTest.java create mode 100644 src/test/resources/ParserTesting/EnumSample.java delete mode 100644 src/test/resources/ParserTesting/EnumTest.java create mode 100644 src/test/resources/ParserTesting/InnerClassSample.java rename src/test/resources/ParserTesting/{ObjectCreationTest.java => ObjectCreationSample.java} (80%) diff --git a/README.md b/README.md index 0da5389..f0fb96c 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ A tool for the reverse engineering of Java object-oriented source code into Unified Modeling Language (UML) diagrams

+![workflow][workflow-url] [![Contributors][contributors-shield]][contributors-url] [![Commits][commits-shield]][commits-url] [![Forks][forks-shield]][forks-url] @@ -152,6 +153,7 @@ See [License][license-url] for more information regarding the license ## Acknowledgments +[workflow-url]: https://github.com/DAINTINESS-Group/ObjectOrientedArchitectureDiagrammer/actions/workflows/maven.yml/badge.svg [contributors-shield]: https://img.shields.io/github/contributors/DAINTINESS-Group/ObjectOrientedArchitectureDiagrammer [contributors-url]: https://github.com/DAINTINESS-Group/ObjectOrientedArchitectureDiagrammer/graphs/contributors [commits-shield]: https://img.shields.io/github/last-commit/DAINTINESS-Group/ObjectOrientedArchitectureDiagrammer diff --git a/src/main/java/controller/Controller.java b/src/main/java/controller/Controller.java index bef78d6..87c9bc6 100644 --- a/src/main/java/controller/Controller.java +++ b/src/main/java/controller/Controller.java @@ -68,7 +68,7 @@ public interface Controller { SmartGraphPanel visualizeJavaFXGraph(); /** - * This method creates the Loaded Diagram's JavaFX graphView by calling the DiagramManager's visualizeLoadedJavaFXGraph method. + * This method creates the loaded Diagram's JavaFX graphView by calling the DiagramManager's visualizeLoadedJavaFXGraph method. * * @return the created graphView */ diff --git a/src/main/java/controller/ControllerFactory.java b/src/main/java/controller/ControllerFactory.java index 9a8510f..74f2e0b 100644 --- a/src/main/java/controller/ControllerFactory.java +++ b/src/main/java/controller/ControllerFactory.java @@ -3,10 +3,9 @@ public class ControllerFactory { public static Controller createController(String controllerType, String diagramType) { - if (ControllerType.get(controllerType) == ControllerType.UML) { - return new DiagramController(diagramType); - }else { - throw new RuntimeException(); - } + return switch (ControllerType.get(controllerType)) { + case UML -> new DiagramController(diagramType); + }; } + } diff --git a/src/main/java/controller/ControllerType.java b/src/main/java/controller/ControllerType.java index df9a9a8..af21026 100644 --- a/src/main/java/controller/ControllerType.java +++ b/src/main/java/controller/ControllerType.java @@ -21,7 +21,9 @@ public static ControllerType get(String controllerType) { return CONTROLLER_TYPE.get(controllerType.toLowerCase()); } + @Override public String toString() { return super.toString().toLowerCase(); } + } diff --git a/src/main/java/manager/ClassDiagramManager.java b/src/main/java/manager/ClassDiagramManager.java index 88b4407..ce840be 100644 --- a/src/main/java/manager/ClassDiagramManager.java +++ b/src/main/java/manager/ClassDiagramManager.java @@ -36,9 +36,8 @@ public ClassDiagramManager() { @Override public SourceProject createSourceProject(Path sourcePackagePath) { - SourceProject sourceProject = new SourceProject(classDiagram); - sourceProject.createGraph(sourcePackagePath); - sourceProject.setClassDiagramSinkVertices(); + SourceProject sourceProject = new SourceProject(); + sourceProject.createClassGraph(sourcePackagePath, classDiagram); return sourceProject; } @@ -119,9 +118,11 @@ public SmartGraphPanel applyLayout() { if (!nodesGeometry.containsKey(vertex.element())) { continue; } + Pair coordinates = nodesGeometry.getVertexGeometry(vertex.element()); graphView.setVertexPosition(vertex, coordinates.getValue0(), coordinates.getValue1()); } + return graphView; } @@ -131,9 +132,11 @@ public SmartGraphPanel applySpecificLayout(String choice){ if (!nodesGeometry.containsKey(vertex.element())) { continue; } + Pair coordinates = nodesGeometry.getVertexGeometry(vertex.element()); graphView.setVertexPosition(vertex, coordinates.getValue0(), coordinates.getValue1()); } + return graphView; } diff --git a/src/main/java/manager/DiagramManagerFactory.java b/src/main/java/manager/DiagramManagerFactory.java index fd6242d..cf7dd24 100644 --- a/src/main/java/manager/DiagramManagerFactory.java +++ b/src/main/java/manager/DiagramManagerFactory.java @@ -4,7 +4,7 @@ public class DiagramManagerFactory { public static DiagramManager createDiagramManager(String diagramType) { return switch (DiagramType.get(diagramType)) { - case CLASS -> new ClassDiagramManager(); + case CLASS -> new ClassDiagramManager(); case PACKAGE -> new PackageDiagramManager(); }; } diff --git a/src/main/java/manager/DiagramType.java b/src/main/java/manager/DiagramType.java index e0166b8..471e97b 100644 --- a/src/main/java/manager/DiagramType.java +++ b/src/main/java/manager/DiagramType.java @@ -15,6 +15,7 @@ public enum DiagramType { for (DiagramType diagramType: DiagramType.values()) { map.put(diagramType.toString().toLowerCase(), diagramType); } + DIAGRAM_TYPE = Collections.unmodifiableMap(map); } @@ -22,7 +23,9 @@ public static DiagramType get(String diagramType) { return DIAGRAM_TYPE.get(diagramType.toLowerCase().trim()); } + @Override public String toString() { return super.toString().toLowerCase(); } + } diff --git a/src/main/java/manager/PackageDiagramManager.java b/src/main/java/manager/PackageDiagramManager.java index be64d92..d44aed4 100644 --- a/src/main/java/manager/PackageDiagramManager.java +++ b/src/main/java/manager/PackageDiagramManager.java @@ -40,9 +40,8 @@ public PackageDiagramManager() { @Override public SourceProject createSourceProject(Path sourcePackagePath) { - SourceProject sourceProject = new SourceProject(packageDiagram); - sourceProject.createGraph(sourcePackagePath); - sourceProject.setPackageDiagramVertices(); + SourceProject sourceProject = new SourceProject(); + sourceProject.createPackageGraph(sourcePackagePath, packageDiagram); return sourceProject; } @@ -52,7 +51,7 @@ public void convertTreeToDiagram(List chosenFilesNames) { } @Override - public void arrangeDiagram(){ + public void arrangeDiagram() { packageDiagramArrangement = new PackageDiagramArrangementManager(packageDiagram); DiagramGeometry diagramGeometry = packageDiagramArrangement.arrangeDiagram(); packageDiagram.setDiagramGeometry(diagramGeometry); @@ -120,21 +119,25 @@ public SmartGraphPanel applyLayout() { logger.log(Level.INFO, vertex.element()); continue; } + Pair coordinates = nodesGeometry.getVertexGeometry(vertex.element()); graphView.setVertexPosition(vertex, coordinates.getValue0(), coordinates.getValue1()); } + return graphView; } public SmartGraphPanel applySpecificLayout(String choice){ DiagramGeometry nodesGeometry = packageDiagramArrangement.applyNewLayout(choice); for(Vertex vertex : vertexCollection) { - if(!nodesGeometry.containsKey(vertex.element())) { + if (!nodesGeometry.containsKey(vertex.element())) { continue; } + Pair coordinates = nodesGeometry.getVertexGeometry(vertex.element()); graphView.setVertexPosition(vertex, coordinates.getValue0(), coordinates.getValue1()); } + return graphView; } diff --git a/src/main/java/manager/SourceProject.java b/src/main/java/manager/SourceProject.java index c859ab8..e476a00 100644 --- a/src/main/java/manager/SourceProject.java +++ b/src/main/java/manager/SourceProject.java @@ -8,31 +8,17 @@ public class SourceProject { - private static Interpreter interpreter; - private static ClassDiagram classDiagram; - private static PackageDiagram packageDiagram; + private final Interpreter interpreter = new Interpreter(); - public SourceProject(ClassDiagram classDiagram) { - interpreter = new Interpreter(); - SourceProject.classDiagram = classDiagram; - } - - public SourceProject(PackageDiagram packageDiagram) { - interpreter = new Interpreter(); - SourceProject.packageDiagram = packageDiagram; - } - - - public void createGraph(Path sourcePackagePath) { + public void createClassGraph(Path sourcePackagePath, ClassDiagram classDiagram) { interpreter.parseProject(sourcePackagePath); interpreter.convertTreeToGraph(); - } - - public void setClassDiagramSinkVertices() { classDiagram.setSinkVertices(interpreter.getSinkVertices()); } - public void setPackageDiagramVertices() { + public void createPackageGraph(Path sourcePackagePath, PackageDiagram packageDiagram) { + interpreter.parseProject(sourcePackagePath); + interpreter.convertTreeToGraph(); packageDiagram.setVertices(interpreter.getVertices()); } diff --git a/src/main/java/model/diagram/ClassDiagram.java b/src/main/java/model/diagram/ClassDiagram.java index 2de35ef..c4c9226 100644 --- a/src/main/java/model/diagram/ClassDiagram.java +++ b/src/main/java/model/diagram/ClassDiagram.java @@ -27,7 +27,7 @@ public ClassDiagram() { public void createNewDiagram(List chosenFilesNames) { createGraphNodes(chosenFilesNames); - createDiagram(this.graphNodes.keySet()); + createDiagram(graphNodes.keySet()); } public void createDiagram(Set sinkVertices) { @@ -38,7 +38,7 @@ public void createDiagram(Set sinkVertices) { private void createGraphNodes(List chosenFileNames) { int nodeId = 0; for (ClassifierVertex classifierVertex : getChosenNodes(chosenFileNames)) { - this.graphNodes.put(classifierVertex, nodeId); + graphNodes.put(classifierVertex, nodeId); nodeId++; } } diff --git a/src/main/java/model/diagram/GraphClassDiagramConverter.java b/src/main/java/model/diagram/GraphClassDiagramConverter.java index 8095c29..9527311 100644 --- a/src/main/java/model/diagram/GraphClassDiagramConverter.java +++ b/src/main/java/model/diagram/GraphClassDiagramConverter.java @@ -15,20 +15,20 @@ public class GraphClassDiagramConverter { public GraphClassDiagramConverter(Set sinkVertices) { this.sinkVertices = sinkVertices; - this.adjacencyList = new HashMap<>(); + adjacencyList = new HashMap<>(); } public Map>> convertGraphToClassDiagram() { - for (ClassifierVertex classifierVertex : this.sinkVertices) { - this.adjacencyList.put(classifierVertex, new HashSet<>()); + for (ClassifierVertex classifierVertex : sinkVertices) { + adjacencyList.put(classifierVertex, new HashSet<>()); for (Arc arc: classifierVertex.getArcs()) { - if (!this.sinkVertices.contains(arc.targetVertex())) { + if (!sinkVertices.contains(arc.targetVertex())) { continue; } - this.adjacencyList.get(arc.sourceVertex()).add(arc); + adjacencyList.get(arc.sourceVertex()).add(arc); } } - return this.adjacencyList; + return adjacencyList; } } diff --git a/src/main/java/model/diagram/GraphPackageDiagramConverter.java b/src/main/java/model/diagram/GraphPackageDiagramConverter.java index a13f513..7479498 100644 --- a/src/main/java/model/diagram/GraphPackageDiagramConverter.java +++ b/src/main/java/model/diagram/GraphPackageDiagramConverter.java @@ -15,20 +15,21 @@ public class GraphPackageDiagramConverter { public GraphPackageDiagramConverter(Set vertices) { this.vertices = vertices; - this.adjacencyList = new HashMap<>(); + adjacencyList = new HashMap<>(); } public Map>> convertGraphToPackageDiagram() { - for (PackageVertex vertex: this.vertices) { - this.adjacencyList.put(vertex, new HashSet<>()); + for (PackageVertex vertex: vertices) { + adjacencyList.put(vertex, new HashSet<>()); for (Arc arc: vertex.getArcs()) { - if (!this.vertices.contains(arc.targetVertex())) { + if (!vertices.contains(arc.targetVertex())) { continue; } - this.adjacencyList.get(arc.sourceVertex()).add(arc); + adjacencyList.get(arc.sourceVertex()).add(arc); } } - return this.adjacencyList; + + return adjacencyList; } } diff --git a/src/main/java/model/diagram/PackageDiagram.java b/src/main/java/model/diagram/PackageDiagram.java index 3ee5f51..6f854dd 100644 --- a/src/main/java/model/diagram/PackageDiagram.java +++ b/src/main/java/model/diagram/PackageDiagram.java @@ -10,7 +10,7 @@ public class PackageDiagram { - private final Map graphNodes; + private final Map graphNodes; private static Map>> diagram; private static Map vertices; private static Map> diagramGeometryGraphML; @@ -22,7 +22,7 @@ public PackageDiagram() { public void createNewDiagram(List chosenFileNames) { createGraphNodes(chosenFileNames); - createDiagram(this.graphNodes.keySet()); + createDiagram(graphNodes.keySet()); } public void createDiagram(Set vertices) { @@ -33,7 +33,7 @@ public void createDiagram(Set vertices) { private void createGraphNodes(List chosenFileNames) { int nodeId = 0; for (PackageVertex vertex: getChosenNodes(chosenFileNames)) { - this.graphNodes.put(vertex, nodeId); + graphNodes.put(vertex, nodeId); nodeId++; } } diff --git a/src/main/java/model/diagram/ShadowCleaner.java b/src/main/java/model/diagram/ShadowCleaner.java index 923d3bf..cebd1f1 100644 --- a/src/main/java/model/diagram/ShadowCleaner.java +++ b/src/main/java/model/diagram/ShadowCleaner.java @@ -14,21 +14,22 @@ public class ShadowCleaner { ArcType.AGGREGATION, ArcType.ASSOCIATION); - private final ClassDiagram classDiagram; + private final ClassDiagram classDiagram; public ShadowCleaner(ClassDiagram diagram) { this.classDiagram = diagram; } public Map>> shadowWeakRelationships() { - for (Set> arcs: this.classDiagram.getDiagram().values()) { + for (Set> arcs: classDiagram.getDiagram().values()) { Map>> shadowedArcs = new HashMap<>(); for (Arc arc: arcs) { - shadowedArcs.computeIfAbsent(arc.targetVertex(), sinkVertex -> new ArrayList<>()).add(arc); + shadowedArcs.computeIfAbsent(arc.targetVertex(), + sinkVertex -> new ArrayList<>()).add(arc); } for (Map.Entry>> arc: shadowedArcs.entrySet()) { - if (!doWeakRelationshipsExist(arc)) { + if (!(arc.getValue().size() > 1)) { continue; } for (ArcType arcType: strongerToWeakerArcTypes) { @@ -40,14 +41,12 @@ public Map>> shadowWeakRelationships } } } - return this.classDiagram.getDiagram(); - } - private boolean doWeakRelationshipsExist(Map.Entry>> arc) { - return arc.getValue().size() > 1; + return classDiagram.getDiagram(); } - private boolean doesStrongerRelationshipExist(List> arc, ArcType arcType) { + private boolean doesStrongerRelationshipExist(List> arc, + ArcType arcType) { Optional> inheritanceArc = arc .stream() .filter(sinkVertexArc -> sinkVertexArc.arcType().equals(arcType)) @@ -55,7 +54,11 @@ private boolean doesStrongerRelationshipExist(List> arc, A return inheritanceArc.isPresent(); } - private void removeWeakerRelationships(Set> arcs, ClassifierVertex classifierVertex, ArcType arcType) { - arcs.removeIf(arc -> arc.targetVertex().equals(classifierVertex) && !arc.arcType().equals(arcType)); + private void removeWeakerRelationships(Set> arcs, + ClassifierVertex classifierVertex, + ArcType arcType) { + arcs.removeIf(arc -> + arc.targetVertex().equals(classifierVertex) && + !arc.arcType().equals(arcType)); } } diff --git a/src/main/java/model/diagram/arrangement/ClassDiagramArrangementManager.java b/src/main/java/model/diagram/arrangement/ClassDiagramArrangementManager.java index 6517965..dffd5c9 100644 --- a/src/main/java/model/diagram/arrangement/ClassDiagramArrangementManager.java +++ b/src/main/java/model/diagram/arrangement/ClassDiagramArrangementManager.java @@ -24,6 +24,8 @@ public class ClassDiagramArrangementManager implements DiagramArrangementManagerInterface{ public static final LayoutAlgorithmType LAYOUT_ALGORITHM_TYPE = LayoutAlgorithmType.SUGIYAMA; + public static final int WIDTH = 1500; + public static final int HEIGHT = 1000; private final ClassDiagram classDiagram; private final Graph graph; @@ -34,68 +36,70 @@ public ClassDiagramArrangementManager(ClassDiagram classDiagram) { @Override public Map> arrangeGraphMLDiagram() { - Map> nodesGeometryGraphML = new HashMap<>(); - Graph graph = createGraph(); - AbstractLayout layout = new SpringLayout<>(graph); - layout.setSize(new Dimension(1500, 1000)); - for (Integer i : this.classDiagram.getGraphNodes().values()) { + Map> nodesGeometryGraphML = new HashMap<>(); + Graph graph = createGraph(); + AbstractLayout layout = new SpringLayout<>(graph); + layout.setSize(new Dimension(WIDTH, HEIGHT)); + for (Integer i : classDiagram.getGraphNodes().values()) { nodesGeometryGraphML.put(i, new Pair<>(layout.getX(i), layout.getY(i))); } + return nodesGeometryGraphML; } @Override public DiagramGeometry arrangeDiagram() { LayoutAlgorithm layoutAlgorithm = LayoutAlgorithmFactory.createLayoutAlgorithm(LAYOUT_ALGORITHM_TYPE); - layoutAlgorithm.setGraph(this.graph); + layoutAlgorithm.setGraph(graph); return layoutAlgorithm.arrangeDiagram(); } @Override public DiagramGeometry applyNewLayout(String algorithmType){ LayoutAlgorithmType algorithmEnumType = LayoutAlgorithmType.valueOf(algorithmType.toUpperCase()); - LayoutAlgorithm layout = LayoutAlgorithmFactory.createLayoutAlgorithm(algorithmEnumType); - layout.setGraph(this.graph); + LayoutAlgorithm layout = LayoutAlgorithmFactory.createLayoutAlgorithm(algorithmEnumType); + layout.setGraph(graph); return layout.arrangeDiagram(); } private Graph createGraph(){ Graph graph = new SparseGraph<>(); - for (Integer nodeId: this.classDiagram.getGraphNodes().values()) { + for (Integer nodeId: classDiagram.getGraphNodes().values()) { graph.addVertex(nodeId); } List> arcs = new ArrayList<>(); - for (Set> arcSet: this.classDiagram.getDiagram().values()) { + for (Set> arcSet: classDiagram.getDiagram().values()) { arcs.addAll(arcSet); } for (Arc arc: arcs) { - graph.addEdge( - this.classDiagram.getGraphNodes().get(arc.sourceVertex()) + " " + this.classDiagram.getGraphNodes().get(arc.targetVertex()), - this.classDiagram.getGraphNodes().get(arc.sourceVertex()), - this.classDiagram.getGraphNodes().get(arc.targetVertex()), EdgeType.DIRECTED); + graph.addEdge(classDiagram.getGraphNodes().get(arc.sourceVertex()) + " " + classDiagram.getGraphNodes().get(arc.targetVertex()), + classDiagram.getGraphNodes().get(arc.sourceVertex()), + classDiagram.getGraphNodes().get(arc.targetVertex()), + EdgeType.DIRECTED); } + return graph; } private Graph createGraphWithStrings(){ Graph graph = new SparseGraph<>(); - for (ClassifierVertex vertex: this.classDiagram.getGraphNodes().keySet()) { + for (ClassifierVertex vertex: classDiagram.getGraphNodes().keySet()) { graph.addVertex(vertex.getName()); } List> arcs = new ArrayList<>(); - for (Set> arcSet: this.classDiagram.getDiagram().values()) { + for (Set> arcSet: classDiagram.getDiagram().values()) { arcs.addAll(arcSet); } for (Arc arc: arcs) { - graph.addEdge( - arc.sourceVertex().getName() + " " + arc.targetVertex().getName(), - arc.sourceVertex().getName(), - arc.targetVertex().getName(), EdgeType.DIRECTED); + graph.addEdge(arc.sourceVertex().getName() + " " + arc.targetVertex().getName(), + arc.sourceVertex().getName(), + arc.targetVertex().getName(), EdgeType.DIRECTED); } + return graph; } diff --git a/src/main/java/model/diagram/arrangement/PackageDiagramArrangementManager.java b/src/main/java/model/diagram/arrangement/PackageDiagramArrangementManager.java index 559ae3b..fb0ab66 100644 --- a/src/main/java/model/diagram/arrangement/PackageDiagramArrangementManager.java +++ b/src/main/java/model/diagram/arrangement/PackageDiagramArrangementManager.java @@ -24,6 +24,8 @@ public class PackageDiagramArrangementManager implements DiagramArrangementManagerInterface { public static final LayoutAlgorithmType LAYOUT_ALGORITHM_TYPE = LayoutAlgorithmType.SUGIYAMA; + public static final int WIDTH = 1500; + public static final int HEIGHT = 1000; private final Graph graph; private final PackageDiagram packageDiagram; @@ -37,17 +39,18 @@ public Map> arrangeGraphMLDiagram() { Map> nodesGeometryGraphML = new HashMap<>(); Graph graph = populatePackageGraph(); AbstractLayout layout = new SpringLayout<>(graph); - layout.setSize(new Dimension(1500, 1000)); - for (Integer i : this.packageDiagram.getGraphNodes().values()) { + layout.setSize(new Dimension(WIDTH, HEIGHT)); + for (Integer i : packageDiagram.getGraphNodes().values()) { nodesGeometryGraphML.put(i, new Pair<>(layout.getX(i), layout.getY(i))); } + return nodesGeometryGraphML; } @Override public DiagramGeometry arrangeDiagram() { LayoutAlgorithm layoutAlgorithm = LayoutAlgorithmFactory.createLayoutAlgorithm(LAYOUT_ALGORITHM_TYPE); - layoutAlgorithm.setGraph(this.graph); + layoutAlgorithm.setGraph(graph); return layoutAlgorithm.arrangeDiagram(); } @@ -55,26 +58,25 @@ public DiagramGeometry arrangeDiagram() { public DiagramGeometry applyNewLayout(String algorithmType){ LayoutAlgorithmType algorithmEnumType = LayoutAlgorithmType.valueOf(algorithmType.toUpperCase()); LayoutAlgorithm layout = LayoutAlgorithmFactory.createLayoutAlgorithm(algorithmEnumType); - layout.setGraph(this.graph); + layout.setGraph(graph); return layout.arrangeDiagram(); } private Graph populatePackageGraph() { Graph graph = new SparseGraph<>(); - for (Integer i : this.packageDiagram.getGraphNodes().values()) { + for (Integer i : packageDiagram.getGraphNodes().values()) { graph.addVertex(i); } List> arcs = new ArrayList<>(); - for (Set> arcSet: this.packageDiagram.getDiagram().values()) { + for (Set> arcSet: packageDiagram.getDiagram().values()) { arcs.addAll(arcSet); } for (Arc arc: arcs) { - graph.addEdge( - this.packageDiagram.getGraphNodes().get(arc.sourceVertex()) + " " + this.packageDiagram.getGraphNodes().get(arc.targetVertex()), - this.packageDiagram.getGraphNodes().get(arc.sourceVertex()), - this.packageDiagram.getGraphNodes().get(arc.targetVertex()), EdgeType.DIRECTED); + graph.addEdge(packageDiagram.getGraphNodes().get(arc.sourceVertex()) + " " + packageDiagram.getGraphNodes().get(arc.targetVertex()), + packageDiagram.getGraphNodes().get(arc.sourceVertex()), + packageDiagram.getGraphNodes().get(arc.targetVertex()), EdgeType.DIRECTED); } return graph; @@ -82,20 +84,21 @@ private Graph populatePackageGraph() { private Graph populatePackageGraphWithStrings(){ Graph graph = new SparseGraph<>(); - for (PackageVertex vertex: this.packageDiagram.getGraphNodes().keySet()) { + for (PackageVertex vertex: packageDiagram.getGraphNodes().keySet()) { graph.addVertex(vertex.getName()); } List> arcs = new ArrayList<>(); - for (Set> arcSet: this.packageDiagram.getDiagram().values()) { + for (Set> arcSet: packageDiagram.getDiagram().values()) { arcs.addAll(arcSet); } for (Arc arc: arcs) { - graph.addEdge( - String.join(" ", arc.sourceVertex().getName(), arc.targetVertex().getName()), - arc.sourceVertex().getName(), - arc.targetVertex().getName(), EdgeType.DIRECTED); + graph.addEdge(String.join(" ", + arc.sourceVertex().getName(), + arc.targetVertex().getName()), + arc.sourceVertex().getName(), + arc.targetVertex().getName(), EdgeType.DIRECTED); } return graph; diff --git a/src/main/java/model/diagram/arrangement/algorithms/AdvancedFruchtermanReingold.java b/src/main/java/model/diagram/arrangement/algorithms/AdvancedFruchtermanReingold.java index b5ae758..b6184ea 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/AdvancedFruchtermanReingold.java +++ b/src/main/java/model/diagram/arrangement/algorithms/AdvancedFruchtermanReingold.java @@ -8,6 +8,8 @@ import model.diagram.arrangement.geometry.GeometryNode; public class AdvancedFruchtermanReingold implements LayoutAlgorithm{ + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private Graph graph; @@ -31,13 +33,13 @@ public DiagramGeometry arrangeDiagram() { double y = layout.getY(vertex); if (x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/algorithms/AdvancedSpring.java b/src/main/java/model/diagram/arrangement/algorithms/AdvancedSpring.java index 1380458..99fe725 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/AdvancedSpring.java +++ b/src/main/java/model/diagram/arrangement/algorithms/AdvancedSpring.java @@ -7,6 +7,8 @@ import model.diagram.arrangement.geometry.GeometryNode; public class AdvancedSpring implements LayoutAlgorithm{ + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private Graph graph; @@ -32,13 +34,13 @@ public DiagramGeometry arrangeDiagram() { double y = layout.getY(vertex); if (x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/algorithms/FruchtermanReingold.java b/src/main/java/model/diagram/arrangement/algorithms/FruchtermanReingold.java index c93898c..2dc93be 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/FruchtermanReingold.java +++ b/src/main/java/model/diagram/arrangement/algorithms/FruchtermanReingold.java @@ -8,6 +8,8 @@ import model.diagram.arrangement.geometry.GeometryNode; public class FruchtermanReingold implements LayoutAlgorithm{ + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private Graph graph; @@ -31,13 +33,13 @@ public DiagramGeometry arrangeDiagram() { double y = layout.getY(vertex); if (x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/algorithms/KamadaKawai.java b/src/main/java/model/diagram/arrangement/algorithms/KamadaKawai.java index fb96610..36311ab 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/KamadaKawai.java +++ b/src/main/java/model/diagram/arrangement/algorithms/KamadaKawai.java @@ -10,8 +10,10 @@ public class KamadaKawai implements LayoutAlgorithm{ - private final static int GRAPH_X_SIZE = 1200; - private final static int GRAPH_Y_SIZE = 725; + private final static int GRAPH_X_SIZE = 1200; + private final static int GRAPH_Y_SIZE = 725; + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private Graph graph; @@ -37,13 +39,13 @@ public DiagramGeometry arrangeDiagram() { double y = layout.getY(vertex); if (x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithm.java b/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithm.java index 09d3081..fe0edb3 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithm.java +++ b/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithm.java @@ -4,9 +4,6 @@ import model.diagram.arrangement.geometry.DiagramGeometry; public interface LayoutAlgorithm { - int MIN_X_WINDOW_VALUE = 25; - int MIN_Y_WINDOW_VALUE = 25; - // TODO Update JavaDoc /** * This method is responsible for the arrangement of the graph by creating a graph of the Jung library diff --git a/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithmType.java b/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithmType.java index fb117f2..6cc8853 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithmType.java +++ b/src/main/java/model/diagram/arrangement/algorithms/LayoutAlgorithmType.java @@ -25,4 +25,5 @@ public enum LayoutAlgorithmType { public static LayoutAlgorithmType get(String algorithmType) { return ALGORITHM_TYPE_MAP.get(algorithmType.toLowerCase()); } + } diff --git a/src/main/java/model/diagram/arrangement/algorithms/Spring.java b/src/main/java/model/diagram/arrangement/algorithms/Spring.java index ce2baa1..fbf9a9b 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/Spring.java +++ b/src/main/java/model/diagram/arrangement/algorithms/Spring.java @@ -8,6 +8,8 @@ public class Spring implements LayoutAlgorithm{ + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private Graph graph; @@ -33,13 +35,13 @@ public DiagramGeometry arrangeDiagram() { double y = layout.getY(vertex); if (x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/algorithms/Sugiyama.java b/src/main/java/model/diagram/arrangement/algorithms/Sugiyama.java index 01b9d87..a09ab20 100644 --- a/src/main/java/model/diagram/arrangement/algorithms/Sugiyama.java +++ b/src/main/java/model/diagram/arrangement/algorithms/Sugiyama.java @@ -16,7 +16,8 @@ import model.diagram.arrangement.geometry.GeometryNode; public class Sugiyama implements LayoutAlgorithm{ - + private final static int MIN_X_WINDOW_VALUE = 25; + private final static int MIN_Y_WINDOW_VALUE = 25; private final static int VERTEX_X_SIZE = 20; private final static int VERTEX_Y_SIZE = 20; private final static int HORIZONTAL_SPACING = 125; @@ -50,20 +51,20 @@ public DiagramGeometry arrangeDiagram() { DigrpahLayoutBuilder builder = new SugiyamaBuilder<>(HORIZONTAL_SPACING, VERTICAL_SPACING); DigraphLayout layout = builder.build(digraph, dimensionProvider); for (DigraphLayoutNode vertex : layout.getLayoutGraph().vertices()) { - for (Map.Entry entryVertex : this.verticesMap.entrySet()) { + for (Map.Entry entryVertex : verticesMap.entrySet()) { if (entryVertex.getValue().equals(vertex.getVertex())) { double x = vertex.getPoint().x; double y = vertex.getPoint().y; GeometryNode geometryNode = new GeometryNode(entryVertex.getKey()); if (vertex.getPoint().x < MIN_X_WINDOW_VALUE) { double difference = MIN_X_WINDOW_VALUE - x; - if(difference > maxXdistance) { + if (difference > maxXdistance) { maxXdistance = difference; } } if (vertex.getPoint().y < MIN_Y_WINDOW_VALUE) { double difference = MIN_Y_WINDOW_VALUE - y; - if(difference > maxYdistance) { + if (difference > maxYdistance) { maxYdistance = difference; } } diff --git a/src/main/java/model/diagram/arrangement/geometry/DiagramGeometry.java b/src/main/java/model/diagram/arrangement/geometry/DiagramGeometry.java index 1bce16e..47f9991 100644 --- a/src/main/java/model/diagram/arrangement/geometry/DiagramGeometry.java +++ b/src/main/java/model/diagram/arrangement/geometry/DiagramGeometry.java @@ -20,18 +20,17 @@ public void addGeometry(GeometryNode key, double x, double y) { geometryMap.put(key.nodeName(), new Pair<>(x, y)); } - public Pair getVertexGeometry(String stringKey){ return geometryMap.get(stringKey); } - public boolean containsKey(String stringKey) { return geometryMap.containsKey(stringKey); } public void correctPositions(double x, double y) { - // We store minX and minY coordinates of the system, in order to bring the graph to match the left side and upper side of the window. + // We store minX and minY coordinates of the system, in order to bring the graph to match the left side + // and upper side of the window. double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double xDifference; @@ -40,10 +39,10 @@ public void correctPositions(double x, double y) { double newX = entry.getValue().getValue0() + x; double newY = entry.getValue().getValue1() + y; geometryMap.put(entry.getKey(), new Pair<>(entry.getValue().getValue0() + x, entry.getValue().getValue1() + y)); - if( newX < minX) { + if (newX < minX) { minX = newX; } - if( newY < minY) { + if (newY < minY) { minY = newY; } } diff --git a/src/main/java/model/diagram/exportation/ClassifierVertexSerializer.java b/src/main/java/model/diagram/exportation/ClassifierVertexSerializer.java index e90ee09..9b712f8 100644 --- a/src/main/java/model/diagram/exportation/ClassifierVertexSerializer.java +++ b/src/main/java/model/diagram/exportation/ClassifierVertexSerializer.java @@ -17,18 +17,18 @@ public class ClassifierVertexSerializer implements JsonSerializer { @Override - public JsonElement serialize(ClassifierVertex classifierVertex, - Type type, - JsonSerializationContext jsonSerializationContext) { + public JsonElement serialize(ClassifierVertex classifierVertex, + Type type, + JsonSerializationContext jsonSerializationContext) { JsonObject jsonObject = new JsonObject(); - String name = classifierVertex.getName(); - Path path = classifierVertex.getPath(); - String vertexType = classifierVertex.getVertexType().toString(); + String name = classifierVertex.getName(); + Path path = classifierVertex.getPath(); + String vertexType = classifierVertex.getVertexType().toString(); jsonObject.addProperty("name", name); jsonObject.addProperty("path", path.toString()); jsonObject.addProperty("vertexType", vertexType); - jsonObject.addProperty("coordinate_x", classifierVertex.getCoordinates().getValue0()); - jsonObject.addProperty("coordinate_y", classifierVertex.getCoordinates().getValue1()); + jsonObject.addProperty("coordinate_x", classifierVertex.getCoordinate().getX()); + jsonObject.addProperty("coordinate_y", classifierVertex.getCoordinate().getY()); jsonObject.add("methods", serializeMethods(classifierVertex)); jsonObject.add("fields", serializeFields(classifierVertex)); jsonObject.add("arcs", serializeArcs(classifierVertex)); diff --git a/src/main/java/model/diagram/exportation/CoordinatesUpdater.java b/src/main/java/model/diagram/exportation/CoordinatesUpdater.java index 7376ece..eca0e96 100644 --- a/src/main/java/model/diagram/exportation/CoordinatesUpdater.java +++ b/src/main/java/model/diagram/exportation/CoordinatesUpdater.java @@ -12,10 +12,10 @@ import java.util.logging.Logger; public class CoordinatesUpdater { - private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); - private PackageDiagram packageDiagram; - private ClassDiagram classDiagram; + private PackageDiagram packageDiagram; + private ClassDiagram classDiagram; public CoordinatesUpdater(PackageDiagram packageDiagram) { this.packageDiagram = packageDiagram; @@ -28,18 +28,19 @@ public CoordinatesUpdater(ClassDiagram classDiagram) { public void updatePackageCoordinates(Collection> vertexCollection, SmartGraphPanel graphView) { if (vertexCollection == null) { - logger.log(Level.INFO, "Vertex Collection is null"); + logger.log(Level.WARNING, "Vertex Collection is null"); return; } for(Vertex vertex : vertexCollection) { double x = graphView.getVertexPositionX(vertex); double y = graphView.getVertexPositionY(vertex); - for(PackageVertex packageVertex : this.packageDiagram.getGraphNodes().keySet()) { - if(!packageVertex.getName().equals(vertex.element())) { + for (PackageVertex packageVertex : packageDiagram.getGraphNodes().keySet()) { + if (!packageVertex.getName().equals(vertex.element())) { continue; } - packageVertex.setCoordinates(x, y); + + packageVertex.createCoordinate(x, y); } } } @@ -47,18 +48,19 @@ public void updatePackageCoordinates(Collection> vertexCollecti public void updateClassCoordinates(Collection> vertexCollection, SmartGraphPanel graphView) { if (vertexCollection == null) { - logger.log(Level.INFO, "Vertex Collection is null"); + logger.log(Level.WARNING, "Vertex Collection is null"); return; } for(Vertex vertex : vertexCollection) { double x = graphView.getVertexPositionX(vertex); double y = graphView.getVertexPositionY(vertex); - for(ClassifierVertex classifierVertex : this.classDiagram.getGraphNodes().keySet()) { + for (ClassifierVertex classifierVertex : classDiagram.getGraphNodes().keySet()) { if (!classifierVertex.getName().equals(vertex.element())) { continue; } - classifierVertex.setCoordinates(x, y); + + classifierVertex.updateCoordinate(x, y); } } } diff --git a/src/main/java/model/diagram/exportation/GraphMLClassDiagramExporter.java b/src/main/java/model/diagram/exportation/GraphMLClassDiagramExporter.java index 881c558..9c3c483 100644 --- a/src/main/java/model/diagram/exportation/GraphMLClassDiagramExporter.java +++ b/src/main/java/model/diagram/exportation/GraphMLClassDiagramExporter.java @@ -15,19 +15,20 @@ public class GraphMLClassDiagramExporter implements DiagramExporter { public GraphMLClassDiagramExporter(ClassDiagram classDiagram) { GraphMLClassifierVertex graphMLClassifierVertex = new GraphMLClassifierVertex(classDiagram); - this.graphMLNodeBuffer = graphMLClassifierVertex.convertSinkVertex(); GraphMLClassifierVertexArc graphMLClassifierVertexArc = new GraphMLClassifierVertexArc(classDiagram); - this.graphMLEdgeBuffer = graphMLClassifierVertexArc.convertSinkVertexArc(); - this.graphMLFile = new GraphMLFile(); + + graphMLNodeBuffer = graphMLClassifierVertex.convertSinkVertex(); + graphMLEdgeBuffer = graphMLClassifierVertexArc.convertSinkVertexArc(); + graphMLFile = new GraphMLFile(); } @Override public File exportDiagram(Path exportPath) { - this.graphMLFile.createGraphMLFile(exportPath); - this.graphMLFile.writeToBuffer(this.graphMLNodeBuffer); - this.graphMLFile.writeToBuffer(this.graphMLEdgeBuffer); - this.graphMLFile.closeGraphMLFile(); - return this.graphMLFile.getGraphMLFile(); + graphMLFile.createGraphMLFile(exportPath); + graphMLFile.writeToBuffer(graphMLNodeBuffer); + graphMLFile.writeToBuffer(graphMLEdgeBuffer); + graphMLFile.closeGraphMLFile(); + return graphMLFile.getGraphMLFile(); } } diff --git a/src/main/java/model/diagram/exportation/GraphMLFile.java b/src/main/java/model/diagram/exportation/GraphMLFile.java index 89c2852..003b060 100644 --- a/src/main/java/model/diagram/exportation/GraphMLFile.java +++ b/src/main/java/model/diagram/exportation/GraphMLFile.java @@ -15,34 +15,34 @@ public class GraphMLFile { public void createGraphMLFile(Path graphMLSavePath) { try { - this.graphMLFile = graphMLSavePath.toFile(); - this.graphMLWriter = new FileWriter(this.graphMLFile); - this.graphMLBuffer = new StringBuilder(); - this.graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLPrefix()); - } - catch (IOException e) { + graphMLFile = graphMLSavePath.toFile(); + graphMLWriter = new FileWriter(graphMLFile); + graphMLBuffer = new StringBuilder(); + graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLPrefix()); + } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } public void closeGraphMLFile() { try { - this.graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLSuffix()); - this.graphMLWriter.write(this.graphMLBuffer.toString()); - this.graphMLWriter.close(); - } - catch (IOException e) { + graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLSuffix()); + graphMLWriter.write(graphMLBuffer.toString()); + graphMLWriter.close(); + } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } public void writeToBuffer(StringBuilder buffer) { - this.graphMLBuffer.append(buffer); + graphMLBuffer.append(buffer); } public File getGraphMLFile() { - return this.graphMLFile; + return graphMLFile; } } diff --git a/src/main/java/model/diagram/exportation/GraphMLPackageDiagramExporter.java b/src/main/java/model/diagram/exportation/GraphMLPackageDiagramExporter.java index a1eecf1..084dc25 100644 --- a/src/main/java/model/diagram/exportation/GraphMLPackageDiagramExporter.java +++ b/src/main/java/model/diagram/exportation/GraphMLPackageDiagramExporter.java @@ -14,24 +14,25 @@ public class GraphMLPackageDiagramExporter implements DiagramExporter { private final StringBuilder graphMLEdgeBuffer; public GraphMLPackageDiagramExporter(PackageDiagram packageDiagram) { - GraphMLPackageVertex graphMLPackageVertex = new GraphMLPackageVertex(packageDiagram); - this.graphMLNodeBuffer = graphMLPackageVertex.convertVertex(); + GraphMLPackageVertex graphMLPackageVertex = new GraphMLPackageVertex(packageDiagram); GraphMLPackageVertexArc graphMLPackageVertexArc = new GraphMLPackageVertexArc(packageDiagram); - this.graphMLEdgeBuffer = graphMLPackageVertexArc.convertVertexArc(); - this.graphMLFile = new GraphMLFile(); + + graphMLNodeBuffer = graphMLPackageVertex.convertVertex(); + graphMLEdgeBuffer = graphMLPackageVertexArc.convertVertexArc(); + graphMLFile = new GraphMLFile(); } @Override public File exportDiagram(Path exportPath) { - this.graphMLFile.createGraphMLFile(exportPath); - generateGraphMLGraph(this.graphMLNodeBuffer, this.graphMLEdgeBuffer); - this.graphMLFile.closeGraphMLFile(); - return this.graphMLFile.getGraphMLFile(); + graphMLFile.createGraphMLFile(exportPath); + generateGraphMLGraph(graphMLNodeBuffer, graphMLEdgeBuffer); + graphMLFile.closeGraphMLFile(); + return graphMLFile.getGraphMLFile(); } private void generateGraphMLGraph(StringBuilder nodeBuffer, StringBuilder edgeBuffer) { - this.graphMLFile.writeToBuffer(nodeBuffer); - this.graphMLFile.writeToBuffer(edgeBuffer); + graphMLFile.writeToBuffer(nodeBuffer); + graphMLFile.writeToBuffer(edgeBuffer); } } diff --git a/src/main/java/model/diagram/exportation/JavaFXClassDiagramExporter.java b/src/main/java/model/diagram/exportation/JavaFXClassDiagramExporter.java index 6372bc0..f7806ef 100644 --- a/src/main/java/model/diagram/exportation/JavaFXClassDiagramExporter.java +++ b/src/main/java/model/diagram/exportation/JavaFXClassDiagramExporter.java @@ -22,14 +22,18 @@ public JavaFXClassDiagramExporter(ClassDiagram diagram) { public File exportDiagram(Path exportPath) { File graphSaveFile = exportPath.toFile(); try (FileWriter fileWriter = new FileWriter(graphSaveFile)) { - Gson gson = new GsonBuilder().registerTypeAdapter(ClassifierVertex.class, - new ClassifierVertexSerializer()) - .create(); - String json = gson.toJson(this.classDiagram.getDiagram().keySet()); + Gson gson = new GsonBuilder() + .registerTypeAdapter(ClassifierVertex.class, + new ClassifierVertexSerializer()) + .create(); + + String json = gson.toJson(classDiagram.getDiagram().keySet()); fileWriter.write(json); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } + return graphSaveFile; } diff --git a/src/main/java/model/diagram/exportation/JavaFXPackageDiagramExporter.java b/src/main/java/model/diagram/exportation/JavaFXPackageDiagramExporter.java index 311add9..f6baf95 100644 --- a/src/main/java/model/diagram/exportation/JavaFXPackageDiagramExporter.java +++ b/src/main/java/model/diagram/exportation/JavaFXPackageDiagramExporter.java @@ -22,14 +22,17 @@ public JavaFXPackageDiagramExporter(PackageDiagram packageDiagram) { public File exportDiagram(Path exportPath) { File graphSaveFile = exportPath.toFile(); try (FileWriter fileWriter = new FileWriter(graphSaveFile)) { - Gson gson = new GsonBuilder().registerTypeAdapter(PackageVertex.class, - new PackageVertexSerializer()) - .create(); - String json = gson.toJson(this.packageDiagram.getDiagram().keySet()); + Gson gson = new GsonBuilder() + .registerTypeAdapter(PackageVertex.class, + new PackageVertexSerializer()) + .create(); + String json = gson.toJson(packageDiagram.getDiagram().keySet()); fileWriter.write(json); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } + return graphSaveFile; } diff --git a/src/main/java/model/diagram/exportation/PackageVertexSerializer.java b/src/main/java/model/diagram/exportation/PackageVertexSerializer.java index c90be57..ec7b13f 100644 --- a/src/main/java/model/diagram/exportation/PackageVertexSerializer.java +++ b/src/main/java/model/diagram/exportation/PackageVertexSerializer.java @@ -22,15 +22,15 @@ public JsonElement serialize(PackageVertex packageVertex, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject jsonObject = new JsonObject(); - String name = packageVertex.getName(); - Path path = packageVertex.getPath(); - String vertexType = packageVertex.getVertexType().toString(); + String name = packageVertex.getName(); + Path path = packageVertex.getPath(); + String vertexType = packageVertex.getVertexType().toString(); jsonObject.addProperty("name", name); jsonObject.addProperty("path", path.toString()); jsonObject.addProperty("vertexType", vertexType); - jsonObject.addProperty("coordinate_x", packageVertex.getCoordinates().getValue0()); - jsonObject.addProperty("coordinate_y", packageVertex.getCoordinates().getValue1()); + jsonObject.addProperty("coordinate_x", packageVertex.getCoordinate().getX()); + jsonObject.addProperty("coordinate_y", packageVertex.getCoordinate().getY()); jsonObject.add("sinkVertices", serializeSinkVertices(packageVertex)); jsonObject.add("parent", serializeParentVertex(packageVertex)); jsonObject.add("neighbours", serializeNeighbourVertices(packageVertex)); @@ -40,24 +40,24 @@ public JsonElement serialize(PackageVertex packageVertex, } private JsonArray serializeSinkVertices(PackageVertex packageVertex) { - List sinkVertices = packageVertex.getSinkVertices(); - JsonArray sinkVerticesArray = new JsonArray(sinkVertices.size()); + List sinkVertices = packageVertex.getSinkVertices(); + JsonArray sinkVerticesArray = new JsonArray(sinkVertices.size()); for (ClassifierVertex classifierVertex : sinkVertices) { - Gson gson = new GsonBuilder().registerTypeAdapter(ClassifierVertex.class, - new ClassifierVertexSerializer()) - .create(); - String json = gson.toJson(classifierVertex); - sinkVerticesArray.add(json); + Gson gson = new GsonBuilder().registerTypeAdapter(ClassifierVertex.class, + new ClassifierVertexSerializer()) + .create(); + String json = gson.toJson(classifierVertex); + sinkVerticesArray.add(json); } return sinkVerticesArray; } private JsonObject serializeParentVertex(PackageVertex packageVertex) { PackageVertex parentPackageVertex = packageVertex.getParentVertex(); - JsonObject parentObject = new JsonObject(); - String name = parentPackageVertex.getName(); - String path = parentPackageVertex.getPath().toString(); - String type = parentPackageVertex.getModifierType().toString(); + JsonObject parentObject = new JsonObject(); + String name = parentPackageVertex.getName(); + String path = parentPackageVertex.getPath().toString(); + String type = parentPackageVertex.getModifierType().toString(); parentObject.addProperty("name", name); parentObject.addProperty("path", path); @@ -71,11 +71,11 @@ private JsonArray serializeNeighbourVertices(PackageVertex packageVertex) { JsonArray neighbourVerticesArray = new JsonArray(neighbourVertices.size()); for (PackageVertex v: neighbourVertices) { - JsonObject neighbourVertexObject = new JsonObject(); - String name = v.getName(); - String path = v.getPath().toString(); - String vertexType = v.getVertexType().toString(); - String parentName = v.getParentVertex().getName(); + JsonObject neighbourVertexObject = new JsonObject(); + String name = v.getName(); + String path = v.getPath().toString(); + String vertexType = v.getVertexType().toString(); + String parentName = v.getParentVertex().getName(); neighbourVertexObject.addProperty("name", name); neighbourVertexObject.addProperty("path", path); @@ -87,14 +87,14 @@ private JsonArray serializeNeighbourVertices(PackageVertex packageVertex) { } private JsonArray serializeArcs(PackageVertex packageVertex) { - List> arcs = packageVertex.getArcs(); - JsonArray arcsArray = new JsonArray(arcs.size()); + List> arcs = packageVertex.getArcs(); + JsonArray arcsArray = new JsonArray(arcs.size()); for (Arc vertexArc : arcs) { - JsonObject arcObject = new JsonObject(); - String source = vertexArc.sourceVertex().getName(); - String target = vertexArc.targetVertex().getName(); - String arcType = vertexArc.arcType().toString(); + JsonObject arcObject = new JsonObject(); + String source = vertexArc.sourceVertex().getName(); + String target = vertexArc.targetVertex().getName(); + String arcType = vertexArc.arcType().toString(); arcObject.addProperty("source", source); arcObject.addProperty("target", target); diff --git a/src/main/java/model/diagram/exportation/PlantUMLClassDiagramImageExporter.java b/src/main/java/model/diagram/exportation/PlantUMLClassDiagramImageExporter.java index e5c9773..ca795dd 100644 --- a/src/main/java/model/diagram/exportation/PlantUMLClassDiagramImageExporter.java +++ b/src/main/java/model/diagram/exportation/PlantUMLClassDiagramImageExporter.java @@ -19,20 +19,21 @@ public class PlantUMLClassDiagramImageExporter implements DiagramExporter { private final StringBuilder bufferBody; public PlantUMLClassDiagramImageExporter(ClassDiagram diagram) { - PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(diagram); - StringBuilder plantUMLNodeBuffer = plantUMLClassifierVertex.convertSinkVertex(); - PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(diagram); - StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertSinkVertexArc(); - this.bufferBody = plantUMLNodeBuffer.append("\n\n") - .append(plantUMLEdgeBuffer) - .append("\n @enduml"); + PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(diagram); + StringBuilder plantUMLNodeBuffer = plantUMLClassifierVertex.convertSinkVertex(); + PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(diagram); + StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertSinkVertexArc(); + bufferBody = plantUMLNodeBuffer + .append("\n\n") + .append(plantUMLEdgeBuffer) + .append("\n @enduml"); } @Override public File exportDiagram(Path exportPath) { - File plantUMLFile = exportPath.toFile(); + File plantUMLFile = exportPath.toFile(); String plantUMLCode = getClassText(); - plantUMLCode += this.bufferBody; + plantUMLCode += bufferBody; exportImage(plantUMLFile, plantUMLCode); return plantUMLFile; } @@ -41,11 +42,12 @@ private void exportImage(File plantUMLFile, String plantCode) { try (ByteArrayOutputStream png = new ByteArrayOutputStream()) { SourceStringReader reader = new SourceStringReader(plantCode); reader.outputImage(png).getDescription(); - byte [] data = png.toByteArray(); - InputStream in = new ByteArrayInputStream(data); - BufferedImage convImg = ImageIO.read(in); - int width = convImg.getWidth(); - int wrapWidth = 150; + + byte[] data = png.toByteArray(); + InputStream in = new ByteArrayInputStream(data); + BufferedImage convImg = ImageIO.read(in); + int width = convImg.getWidth(); + int wrapWidth = 150; if (width == 4096) { try (ByteArrayOutputStream newPng = new ByteArrayOutputStream()) { @@ -60,16 +62,17 @@ private void exportImage(File plantUMLFile, String plantCode) { ImageIO.write(convImg, "png", plantUMLFile); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } private String wrapWidthChanger(String plantCode, int wrapWidth){ String updatedString; //if (counter == 0) { - int indexOfNewLine = plantCode.indexOf("\n"); - String firstPart = plantCode.substring(0, indexOfNewLine + 1); - String secondPart = plantCode.substring(indexOfNewLine + 1); - updatedString = firstPart + "skinparam wrapWidth " + wrapWidth + "\n" + secondPart; + int indexOfNewLine = plantCode.indexOf("\n"); + String firstPart = plantCode.substring(0, indexOfNewLine + 1); + String secondPart = plantCode.substring(indexOfNewLine + 1); + updatedString = firstPart + "skinparam wrapWidth " + wrapWidth + "\n" + secondPart; // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // KEEP REDUCING THE WRAPWIDTH PARAMETER IN ORDER TO FIT PROPERLY THE IMAGE // // DOESNT WORK PROPERLY, COMMENTED JUST TO KEEP THE IDEA. // @@ -86,8 +89,7 @@ private String wrapWidthChanger(String plantCode, int wrapWidth){ } private String getClassText() { - return - """ + return """ @startuml skinparam class { BackgroundColor lightyellow diff --git a/src/main/java/model/diagram/exportation/PlantUMLClassDiagramTextExporter.java b/src/main/java/model/diagram/exportation/PlantUMLClassDiagramTextExporter.java index e84e6a9..b687fac 100644 --- a/src/main/java/model/diagram/exportation/PlantUMLClassDiagramTextExporter.java +++ b/src/main/java/model/diagram/exportation/PlantUMLClassDiagramTextExporter.java @@ -15,20 +15,21 @@ public class PlantUMLClassDiagramTextExporter implements DiagramExporter { private final StringBuilder bufferBody; public PlantUMLClassDiagramTextExporter(ClassDiagram diagram) { - PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(diagram); - StringBuilder plantUMLNodeBuffer = plantUMLClassifierVertex.convertSinkVertex(); - PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(diagram); - StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertSinkVertexArc(); - this.bufferBody = plantUMLNodeBuffer.append("\n\n") - .append(plantUMLEdgeBuffer) - .append("\n @enduml"); + PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(diagram); + StringBuilder plantUMLNodeBuffer = plantUMLClassifierVertex.convertSinkVertex(); + PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(diagram); + StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertSinkVertexArc(); + bufferBody = plantUMLNodeBuffer + .append("\n\n") + .append(plantUMLEdgeBuffer) + .append("\n @enduml"); } @Override public File exportDiagram(Path exportPath) { - File plantUMLFile = exportPath.toFile(); - String plantUMLCode = getClassText(); - plantUMLCode += this.bufferBody; + File plantUMLFile = exportPath.toFile(); + String plantUMLCode = getClassText(); + plantUMLCode += bufferBody; writeFile(plantUMLFile, plantUMLCode); return plantUMLFile; } @@ -38,12 +39,12 @@ private void writeFile(File plantUMLFile, String plantCode) { writer.write(plantCode); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } private String getClassText() { - return - """ + return """ @startuml skinparam class { BackgroundColor lightyellow diff --git a/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramImageExporter.java b/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramImageExporter.java index bc598d5..04bd202 100644 --- a/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramImageExporter.java +++ b/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramImageExporter.java @@ -19,34 +19,36 @@ public class PlantUMLPackageDiagramImageExporter implements DiagramExporter { private final StringBuilder bufferBody; public PlantUMLPackageDiagramImageExporter(PackageDiagram diagram) { - PlantUMLPackageVertex plantUMLPackageVertex = new PlantUMLPackageVertex(diagram); - StringBuilder plantUMLNodeBuffer = plantUMLPackageVertex.convertVertex(); - PlantUMLPackageVertexArc plantUMLEdge = new PlantUMLPackageVertexArc(diagram); - StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertVertexArc(); - this.bufferBody = plantUMLNodeBuffer.append("\n\n") - .append(plantUMLEdgeBuffer) - .append("\n @enduml"); + PlantUMLPackageVertex plantUMLPackageVertex = new PlantUMLPackageVertex(diagram); + StringBuilder plantUMLNodeBuffer = plantUMLPackageVertex.convertVertex(); + PlantUMLPackageVertexArc plantUMLEdge = new PlantUMLPackageVertexArc(diagram); + StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertVertexArc(); + bufferBody = plantUMLNodeBuffer + .append("\n\n") + .append(plantUMLEdgeBuffer) + .append("\n @enduml"); } @Override public File exportDiagram(Path exportPath) { - File plantUMLFile = exportPath.toFile(); - String plantUMLCode = getPackageText(); - plantUMLCode += this.bufferBody; - plantUMLCode = dotChanger(plantUMLCode); + File plantUMLFile = exportPath.toFile(); + String plantUMLCode = getPackageText(); + plantUMLCode += bufferBody; + plantUMLCode = dotChanger(plantUMLCode); exportImage(plantUMLFile, plantUMLCode); return plantUMLFile; } private void exportImage(File plantUMLFile, String plantCode) { - try (ByteArrayOutputStream png = new ByteArrayOutputStream()) { - SourceStringReader reader = new SourceStringReader(plantCode); + try (ByteArrayOutputStream png = new ByteArrayOutputStream()) { + SourceStringReader reader = new SourceStringReader(plantCode); reader.outputImage(png).getDescription(); - byte [] data = png.toByteArray(); - InputStream in = new ByteArrayInputStream(data); - BufferedImage convImg = ImageIO.read(in); - int width = convImg.getWidth(); - int wrapWidth = 150; + + byte[] data = png.toByteArray(); + InputStream in = new ByteArrayInputStream(data); + BufferedImage convImg = ImageIO.read(in); + int width = convImg.getWidth(); + int wrapWidth = 150; //int stringChangerCounter = 0; if (width == 4096) { try (ByteArrayOutputStream newPng = new ByteArrayOutputStream()) @@ -63,15 +65,16 @@ private void exportImage(File plantUMLFile, String plantCode) { ImageIO.write(convImg, "png", plantUMLFile); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } private String wrapWidthChanger(String plantCode, int wrapWidth){ String updatedString; - int indexOfNewLine = plantCode.indexOf("\n"); - String firstPart = plantCode.substring(0, indexOfNewLine + 1); - String secondPart = plantCode.substring(indexOfNewLine + 1); - updatedString = firstPart + "skinparam wrapWidth " + wrapWidth + "\n" + secondPart; + int indexOfNewLine = plantCode.indexOf("\n"); + String firstPart = plantCode.substring(0, indexOfNewLine + 1); + String secondPart = plantCode.substring(indexOfNewLine + 1); + updatedString = firstPart + "skinparam wrapWidth " + wrapWidth + "\n" + secondPart; // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // KEEP REDUCING THE WRAPWIDTH PARAMETER IN ORDER TO FIT PROPERLY THE IMAGE // // DOESNT WORK PROPERLY, COMMENTED JUST TO KEEP THE IDEA. // @@ -89,12 +92,12 @@ private String wrapWidthChanger(String plantCode, int wrapWidth){ private String dotChanger(String plantUMLCode) { StringBuilder newString = new StringBuilder(); - String[] lines = plantUMLCode.split("\n"); + String[] lines = plantUMLCode.split("\n"); for (String line: lines) { String[] splittedLine = line.split(" "); for (String word: splittedLine) { String newWord = word; - if(word.contains(".") && !word.contains("..")) { + if (word.contains(".") && !word.contains("..")) { newWord = word.replace(".", "_"); newWord = newWord.replace("-", "_"); } @@ -106,8 +109,7 @@ private String dotChanger(String plantUMLCode) { } private String getPackageText() { - return - """ + return """ @startuml skinparam package { BackgroundColor lightyellow diff --git a/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramTextExporter.java b/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramTextExporter.java index af55915..8fe5c42 100644 --- a/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramTextExporter.java +++ b/src/main/java/model/diagram/exportation/PlantUMLPackageDiagramTextExporter.java @@ -15,21 +15,22 @@ public class PlantUMLPackageDiagramTextExporter implements DiagramExporter { private final StringBuilder bufferBody; public PlantUMLPackageDiagramTextExporter(PackageDiagram diagram) { - PlantUMLPackageVertex plantUMLPackageVertex = new PlantUMLPackageVertex(diagram); - StringBuilder plantUMLNodeBuffer = plantUMLPackageVertex.convertVertex(); - PlantUMLPackageVertexArc plantUMLEdge = new PlantUMLPackageVertexArc(diagram); - StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertVertexArc(); - this.bufferBody = plantUMLNodeBuffer.append("\n\n") - .append(plantUMLEdgeBuffer) - .append("\n @enduml"); + PlantUMLPackageVertex plantUMLPackageVertex = new PlantUMLPackageVertex(diagram); + StringBuilder plantUMLNodeBuffer = plantUMLPackageVertex.convertVertex(); + PlantUMLPackageVertexArc plantUMLEdge = new PlantUMLPackageVertexArc(diagram); + StringBuilder plantUMLEdgeBuffer = plantUMLEdge.convertVertexArc(); + bufferBody = plantUMLNodeBuffer + .append("\n\n") + .append(plantUMLEdgeBuffer) + .append("\n @enduml"); } @Override public File exportDiagram(Path exportPath) { - File plantUMLFile = exportPath.toFile(); - String plantUMLCode = getPackageText(); - plantUMLCode += this.bufferBody; - plantUMLCode = dotChanger(plantUMLCode); + File plantUMLFile = exportPath.toFile(); + String plantUMLCode = getPackageText(); + plantUMLCode += bufferBody; + plantUMLCode = dotChanger(plantUMLCode); writeFile(plantUMLFile, plantUMLCode); return plantUMLFile; } @@ -39,17 +40,18 @@ private void writeFile(File plantUMLFile, String plantCode) { writer.write(plantCode); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } } private String dotChanger(String plantUMLCode) { StringBuilder newString = new StringBuilder(); - String[] lines = plantUMLCode.split("\n"); + String[] lines = plantUMLCode.split("\n"); for (String line: lines) { String[] splittedLine = line.split(" "); for (String word: splittedLine) { String newWord = word; - if(word.contains(".") && !word.contains("..")) { + if (word.contains(".") && !word.contains("..")) { newWord = word.replace(".", "_"); newWord = newWord.replace("-", "_"); } @@ -61,8 +63,7 @@ private String dotChanger(String plantUMLCode) { } private String getPackageText() { - return - """ + return """ @startuml skinparam package { BackgroundColor lightyellow diff --git a/src/main/java/model/diagram/graphml/GraphMLClassifierVertex.java b/src/main/java/model/diagram/graphml/GraphMLClassifierVertex.java index 493178c..85043f8 100644 --- a/src/main/java/model/diagram/graphml/GraphMLClassifierVertex.java +++ b/src/main/java/model/diagram/graphml/GraphMLClassifierVertex.java @@ -20,44 +20,51 @@ public class GraphMLClassifierVertex { public GraphMLClassifierVertex(ClassDiagram classDiagram) { this.classDiagram = classDiagram; - this.graphMLBuffer = new StringBuilder(); + graphMLBuffer = new StringBuilder(); } public StringBuilder convertSinkVertex() { - for (Map.Entry sinkVertex: this.classDiagram.getGraphNodes().entrySet()) { - this.graphMLBuffer.append(GraphMLSyntax.getInstance() - .getGraphMLSinkVertexSyntax(getSinkVertexDescription(sinkVertex.getKey(), - sinkVertex.getValue(), - this.classDiagram.getGraphMLDiagramGeometry().get(sinkVertex.getValue())))); + for (Map.Entry sinkVertex: classDiagram.getGraphNodes().entrySet()) { + graphMLBuffer.append(GraphMLSyntax.getInstance() + .getGraphMLSinkVertexSyntax(getSinkVertexDescription(sinkVertex.getKey(), + sinkVertex.getValue(), + classDiagram.getGraphMLDiagramGeometry().get(sinkVertex.getValue())))); } - return this.graphMLBuffer; + return graphMLBuffer; } - private List getSinkVertexDescription(ClassifierVertex classifierVertex, int nodeId, Pair nodeGeometry) { - return Arrays.asList(String.valueOf(nodeId), getSinkVertexColor(classifierVertex), classifierVertex.getName(), getSinkVertexFields(classifierVertex), - getSinkVertexMethods(classifierVertex), String.valueOf(nodeGeometry.getValue0()), String.valueOf(nodeGeometry.getValue1())); + private List getSinkVertexDescription(ClassifierVertex classifierVertex, + int nodeId, + Pair nodeGeometry) { + return Arrays.asList(String.valueOf(nodeId), + getSinkVertexColor(classifierVertex), + classifierVertex.getName(), + getSinkVertexFields(classifierVertex), + getSinkVertexMethods(classifierVertex), + String.valueOf(nodeGeometry.getValue0()), + String.valueOf(nodeGeometry.getValue1())); } private String getSinkVertexMethods(ClassifierVertex classifierVertex) { if (classifierVertex.getMethods().isEmpty()) { return ""; } - return - classifierVertex.getMethods() - .stream() - .map(method -> method.returnType() + " " + method.name()) - .collect(Collectors.joining("\n")); + return classifierVertex.getMethods() + .stream() + .map(method -> method.returnType() + " " + method.name()) + .collect(Collectors.joining("\n")); } private String getSinkVertexFields(ClassifierVertex classifierVertex) { if (classifierVertex.getFields().isEmpty()) { return ""; } - return - classifierVertex.getFields() - .stream() - .map(field -> String.join(" ", field.type(), field.name())) - .collect(Collectors.joining("\n")); + return classifierVertex.getFields() + .stream() + .map(field -> String.join(" ", + field.type(), + field.name())) + .collect(Collectors.joining("\n")); } private String getSinkVertexColor(ClassifierVertex leafNode) { diff --git a/src/main/java/model/diagram/graphml/GraphMLClassifierVertexArc.java b/src/main/java/model/diagram/graphml/GraphMLClassifierVertexArc.java index 8e63767..500ef6d 100644 --- a/src/main/java/model/diagram/graphml/GraphMLClassifierVertexArc.java +++ b/src/main/java/model/diagram/graphml/GraphMLClassifierVertexArc.java @@ -19,29 +19,28 @@ public class GraphMLClassifierVertexArc { private final ClassDiagram classDiagram; public GraphMLClassifierVertexArc(ClassDiagram classDiagram) { - this.classDiagram = classDiagram; - this.graphMLBuffer = new StringBuilder(); + this.classDiagram = classDiagram; + graphMLBuffer = new StringBuilder(); } public StringBuilder convertSinkVertexArc() { List> arcs = new ArrayList<>(); - for (Set> arcSet: this.classDiagram.getDiagram().values()) { + for (Set> arcSet: classDiagram.getDiagram().values()) { arcs.addAll(arcSet); } int edgeId = 0; for (Arc arc: arcs) { - this.graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLSinkVertexArcSyntax(getEdgesProperties(arc, edgeId))); + graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLSinkVertexArcSyntax(getEdgesProperties(arc, edgeId))); edgeId++; } - return this.graphMLBuffer; + return graphMLBuffer; } private List getEdgesProperties(Arc relationship, Integer edgeId) { - return - Arrays.asList(String.valueOf(edgeId), String.valueOf(this.classDiagram.getGraphNodes().get(relationship.sourceVertex())), - String.valueOf(this.classDiagram.getGraphNodes().get(relationship.targetVertex())), identifyEdgeType(relationship).get(EDGE_TYPE), - identifyEdgeType(relationship).get(EDGES_SOURCE_TYPE), identifyEdgeType(relationship).get(EDGES_TARGET_TYPE)); + return Arrays.asList(String.valueOf(edgeId), String.valueOf(classDiagram.getGraphNodes().get(relationship.sourceVertex())), + String.valueOf(classDiagram.getGraphNodes().get(relationship.targetVertex())), identifyEdgeType(relationship).get(EDGE_TYPE), + identifyEdgeType(relationship).get(EDGES_SOURCE_TYPE), identifyEdgeType(relationship).get(EDGES_TARGET_TYPE)); } private List identifyEdgeType(Arc relationship){ diff --git a/src/main/java/model/diagram/graphml/GraphMLPackageVertex.java b/src/main/java/model/diagram/graphml/GraphMLPackageVertex.java index fd2d618..de65706 100644 --- a/src/main/java/model/diagram/graphml/GraphMLPackageVertex.java +++ b/src/main/java/model/diagram/graphml/GraphMLPackageVertex.java @@ -15,25 +15,25 @@ public class GraphMLPackageVertex { public GraphMLPackageVertex(PackageDiagram packageDiagram) { this.packageDiagram = packageDiagram; - this.graphMLBuffer = new StringBuilder(); + graphMLBuffer = new StringBuilder(); } public StringBuilder convertVertex() { - for (Map.Entry entry: this.packageDiagram.getGraphNodes().entrySet()) { - this.graphMLBuffer.append(GraphMLSyntax.getInstance() - .getGraphMLVertexSyntax(getVertexDescription(entry.getKey(), - entry.getValue(), - this.packageDiagram.getGraphMLDiagramGeometry().get(entry.getValue())))); + for (Map.Entry entry: packageDiagram.getGraphNodes().entrySet()) { + graphMLBuffer.append(GraphMLSyntax.getInstance() + .getGraphMLVertexSyntax(getVertexDescription(entry.getKey(), + entry.getValue(), + packageDiagram.getGraphMLDiagramGeometry().get(entry.getValue())))); } - return this.graphMLBuffer; + return graphMLBuffer; } - private List getVertexDescription(PackageVertex packageNode, int nodeId, Pair nodeGeometry) { - return Arrays.asList( - String.valueOf(nodeId), packageNode.getName(), - String.valueOf(nodeGeometry.getValue0()), - String.valueOf(nodeGeometry.getValue1()) - ); + private List getVertexDescription(PackageVertex packageNode, + int nodeId, + Pair nodeGeometry) { + return Arrays.asList(String.valueOf(nodeId), packageNode.getName(), + String.valueOf(nodeGeometry.getValue0()), + String.valueOf(nodeGeometry.getValue1())); } } diff --git a/src/main/java/model/diagram/graphml/GraphMLPackageVertexArc.java b/src/main/java/model/diagram/graphml/GraphMLPackageVertexArc.java index 83ef893..ccece9a 100644 --- a/src/main/java/model/diagram/graphml/GraphMLPackageVertexArc.java +++ b/src/main/java/model/diagram/graphml/GraphMLPackageVertexArc.java @@ -15,27 +15,27 @@ public class GraphMLPackageVertexArc { public GraphMLPackageVertexArc(PackageDiagram packageDiagram) { this.packageDiagram = packageDiagram; - this.graphMLBuffer = new StringBuilder(); + graphMLBuffer = new StringBuilder(); } public StringBuilder convertVertexArc() { List> arcs = new ArrayList<>(); - for (Set> arcSet: this.packageDiagram.getDiagram().values()) { + for (Set> arcSet: packageDiagram.getDiagram().values()) { arcs.addAll(arcSet); } int edgeId = 0; for (Arc arc: arcs) { - this.graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLVertexArcSyntax(getVertexArcProperties(arc, edgeId))); + graphMLBuffer.append(GraphMLSyntax.getInstance().getGraphMLVertexArcSyntax(getVertexArcProperties(arc, edgeId))); edgeId++; } - return this.graphMLBuffer; + return graphMLBuffer; } private List getVertexArcProperties(Arc relationship, Integer edgeId) { return Arrays.asList(String.valueOf(edgeId), - String.valueOf(this.packageDiagram.getGraphNodes().get(relationship.sourceVertex())), - String.valueOf(this.packageDiagram.getGraphNodes().get(relationship.targetVertex()))); + String.valueOf(packageDiagram.getGraphNodes().get(relationship.sourceVertex())), + String.valueOf(packageDiagram.getGraphNodes().get(relationship.targetVertex()))); } } diff --git a/src/main/java/model/diagram/graphml/GraphMLSyntax.java b/src/main/java/model/diagram/graphml/GraphMLSyntax.java index 5c14846..151dac6 100644 --- a/src/main/java/model/diagram/graphml/GraphMLSyntax.java +++ b/src/main/java/model/diagram/graphml/GraphMLSyntax.java @@ -9,119 +9,122 @@ public class GraphMLSyntax { private GraphMLSyntax() {} public String getGraphMLPrefix(){ - return - """ - - - - - - - - - - - - - - - - - """; + return """ + + + + + + + + + + + + + + + + + """; } public String getGraphMLSuffix() { - return - """ - - - - - - """; + return """ + + + + + + """; } public String getGraphMLSinkVertexSyntax(List sinkVertexDescription) { - return String.format( - """ - - - - - - - - - %s - - %s - %s - - - - - """, - sinkVertexDescription.get(GraphMLSyntaxIds.NODE_ID.getId()), sinkVertexDescription.get(GraphMLSyntaxIds.NODE_X_COORDINATE.getId()), - sinkVertexDescription.get(GraphMLSyntaxIds.NODE_Y_COORDINATE.getId()), sinkVertexDescription.get(GraphMLSyntaxIds.NODE_COLOR.getId()), - sinkVertexDescription.get(GraphMLSyntaxIds.NODE_NAME.getId()), sinkVertexDescription.get(GraphMLSyntaxIds.NODE_FIELDS.getId()), - sinkVertexDescription.get(GraphMLSyntaxIds.NODE_METHODS.getId())); + return String.format(""" + + + + + + + + + %s + + %s + %s + + + + + """, + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_ID.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_X_COORDINATE.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_Y_COORDINATE.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_COLOR.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_NAME.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_FIELDS.getId()), + sinkVertexDescription.get(GraphMLSyntaxIds.NODE_METHODS.getId())); } public String getGraphMLVertexSyntax(List vertexDescription) { - return String.format( - """ - - - - - - - - %s - - - - """, - vertexDescription.get(GraphMLSyntaxIds.NODE_ID.getId()), vertexDescription.get(GraphMLSyntaxIds.PACKAGE_X_COORDINATE.getId()), - vertexDescription.get(GraphMLSyntaxIds.PACKAGE_Y_COORDINATE.getId()), vertexDescription.get(GraphMLSyntaxIds.PACKAGE_NAME.getId())); + return String.format(""" + + + + + + + + %s + + + + """, + vertexDescription.get(GraphMLSyntaxIds.NODE_ID.getId()), + vertexDescription.get(GraphMLSyntaxIds.PACKAGE_X_COORDINATE.getId()), + vertexDescription.get(GraphMLSyntaxIds.PACKAGE_Y_COORDINATE.getId()), + vertexDescription.get(GraphMLSyntaxIds.PACKAGE_NAME.getId())); } public String getGraphMLSinkVertexArcSyntax(List sinkVertexArcDescription) { - return String.format( - """ - - - - - - - - - - - """, - sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_ID.getId()), sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_SOURCE.getId()), - sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_TARGET.getId()), sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_TYPE.getId()), - sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGES_SOURCE_TYPE.getId()), sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGES_TARGET_TYPE.getId())); + return String.format(""" + + + + + + + + + + + """, + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_ID.getId()), + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_SOURCE.getId()), + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_TARGET.getId()), + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGE_TYPE.getId()), + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGES_SOURCE_TYPE.getId()), + sinkVertexArcDescription.get(GraphMLSyntaxIds.EDGES_TARGET_TYPE.getId())); } public String getGraphMLVertexArcSyntax(List vertexArcDescription) { - return String.format( - """ - - - - - - - - - - - \ - """, - vertexArcDescription.get(GraphMLSyntaxIds.EDGE_ID.getId()), vertexArcDescription.get(GraphMLSyntaxIds.EDGE_SOURCE.getId()), - vertexArcDescription.get(GraphMLSyntaxIds.EDGE_TARGET.getId())); + return String.format(""" + + + + + + + + + + + \ + """, + vertexArcDescription.get(GraphMLSyntaxIds.EDGE_ID.getId()), + vertexArcDescription.get(GraphMLSyntaxIds.EDGE_SOURCE.getId()), + vertexArcDescription.get(GraphMLSyntaxIds.EDGE_TARGET.getId())); } public static GraphMLSyntax getInstance(){ diff --git a/src/main/java/model/diagram/javafx/ClassifierVertexDeserializer.java b/src/main/java/model/diagram/javafx/ClassifierVertexDeserializer.java index 78234d2..3a97b72 100644 --- a/src/main/java/model/diagram/javafx/ClassifierVertexDeserializer.java +++ b/src/main/java/model/diagram/javafx/ClassifierVertexDeserializer.java @@ -17,7 +17,6 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class ClassifierVertexDeserializer implements JsonDeserializer { private ClassifierVertex classifierVertex; @@ -26,40 +25,40 @@ public class ClassifierVertexDeserializer implements JsonDeserializer() {}.getType()) + JsonObject method = methods.get(i).getAsJsonObject(); + String methodName = method.get("name").getAsString(); + String returnType = method.get("returnType").getAsString(); + String modifier = method.get("modifier").getAsString(); + String parameters = method.get("parameters").getAsString(); + classifierVertex.addMethod(methodName, + returnType, + ModifierType.get(modifier), + gson.fromJson(parameters, + new TypeToken<>() {}.getType()) ); } } @@ -67,28 +66,30 @@ private void deserializeMethods(JsonObject jsonObject) { private void deserializeFields(JsonObject jsonObject) { JsonArray fields = jsonObject.get("fields").getAsJsonArray(); for (int i = 0; i < fields.size(); i++) { - JsonObject fieldObject = fields.get(i).getAsJsonObject(); - String fieldName = fieldObject.get("name").getAsString(); - String returnType = fieldObject.get("returnType").getAsString(); - String modifierType = fieldObject.get("modifier").getAsString(); - this.classifierVertex.addField(fieldName, - returnType, - ModifierType.get(modifierType) + JsonObject fieldObject = fields.get(i).getAsJsonObject(); + String fieldName = fieldObject.get("name").getAsString(); + String returnType = fieldObject.get("returnType").getAsString(); + String modifierType = fieldObject.get("modifier").getAsString(); + classifierVertex.addField(fieldName, + returnType, + ModifierType.get(modifierType) ); } } private void deserializeArcs(JsonObject jsonObject) { - List> arcs = new ArrayList<>(); - JsonArray arcsArray = jsonObject.get("arcs").getAsJsonArray(); + List> arcs = new ArrayList<>(); + JsonArray arcsArray = jsonObject.get("arcs").getAsJsonArray(); for (int i = 0; i < arcsArray.size(); i++) { - JsonObject arcObject = arcsArray.get(i).getAsJsonObject(); - String sourceVertex = arcObject.get("source").getAsString(); - String targetVertex = arcObject.get("target").getAsString(); - String arcType = arcObject.get("arcType").getAsString(); - arcs.add(new Triplet<>(sourceVertex, targetVertex, arcType)); + JsonObject arcObject = arcsArray.get(i).getAsJsonObject(); + String sourceVertex = arcObject.get("source").getAsString(); + String targetVertex = arcObject.get("target").getAsString(); + String arcType = arcObject.get("arcType").getAsString(); + arcs.add(new Triplet<>(sourceVertex, + targetVertex, + arcType)); } - this.classifierVertex.setDeserializedArcs(arcs); + classifierVertex.setDeserializedArcs(arcs); } } diff --git a/src/main/java/model/diagram/javafx/JavaFXClassDiagramLoader.java b/src/main/java/model/diagram/javafx/JavaFXClassDiagramLoader.java index 4f66d3a..dfa104c 100644 --- a/src/main/java/model/diagram/javafx/JavaFXClassDiagramLoader.java +++ b/src/main/java/model/diagram/javafx/JavaFXClassDiagramLoader.java @@ -26,18 +26,20 @@ public JavaFXClassDiagramLoader(Path graphSavePath) { } public Set loadDiagram() throws JsonParseException { - Set sinkVertices = new HashSet<>(); + Set sinkVertices = new HashSet<>(); try { - byte[] encodedBytes = Files.readAllBytes(this.graphSavePath); - String json = new String(encodedBytes, StandardCharsets.ISO_8859_1); - Gson gson = new GsonBuilder().registerTypeAdapter(ClassifierVertex.class, - new ClassifierVertexDeserializer()) - .create(); + byte[] encodedBytes = Files.readAllBytes(graphSavePath); + String json = new String(encodedBytes, StandardCharsets.ISO_8859_1); + Gson gson = new GsonBuilder().registerTypeAdapter(ClassifierVertex.class, + new ClassifierVertexDeserializer()) + .create(); + ClassifierVertex[] sinkVerticesArray = gson.fromJson(json, ClassifierVertex[].class); Collections.addAll(sinkVertices, sinkVerticesArray); deserializeArcs(sinkVertices); } catch (IOException e) { e.printStackTrace(); + throw new RuntimeException(e); } return sinkVertices; } diff --git a/src/main/java/model/diagram/javafx/JavaFXClassVisualization.java b/src/main/java/model/diagram/javafx/JavaFXClassVisualization.java index 5217551..e7c9c2d 100644 --- a/src/main/java/model/diagram/javafx/JavaFXClassVisualization.java +++ b/src/main/java/model/diagram/javafx/JavaFXClassVisualization.java @@ -42,7 +42,7 @@ public Collection> getVertexCollection(){ private Graph createGraph() { Digraph directedGraph = new DigraphEdgeList<>(); - for (ClassifierVertex classifierVertex : this.classDiagram.getDiagram().keySet()) { + for (ClassifierVertex classifierVertex : classDiagram.getDiagram().keySet()) { directedGraph.insertVertex(classifierVertex.getName()); } insertSinkVertexArcs(directedGraph); @@ -50,13 +50,13 @@ private Graph createGraph() { } private void insertSinkVertexArcs(Digraph directedGraph){ - for (Set> arcs : this.classDiagram.getDiagram().values()) { + for (Set> arcs : classDiagram.getDiagram().values()) { for (Arc arc: arcs) { if (arc.arcType().equals(ArcType.AGGREGATION)) { directedGraph.insertEdge(arc.targetVertex().getName(), arc.sourceVertex().getName(), arc.targetVertex().getName() + "_" + arc.sourceVertex().getName() + "_" + arc.arcType()); - }else { + } else { directedGraph.insertEdge(arc.sourceVertex().getName(), arc.targetVertex().getName(), arc.sourceVertex().getName() + "_" + arc.targetVertex().getName() + "_" + arc.arcType()); @@ -66,10 +66,10 @@ private void insertSinkVertexArcs(Digraph directedGraph){ } private void setSinkVertexCustomStyle() { - for (ClassifierVertex classifierVertex : this.classDiagram.getDiagram().keySet()){ + for (ClassifierVertex classifierVertex : classDiagram.getDiagram().keySet()){ if (classifierVertex.getVertexType().equals(VertexType.INTERFACE)) { graphView.getStylableVertex(classifierVertex.getName()).setStyleClass("vertexInterface"); - }else { + } else { graphView.getStylableVertex(classifierVertex.getName()).setStyleClass("vertexPackage"); } } @@ -78,16 +78,17 @@ private void setSinkVertexCustomStyle() { @Override public SmartGraphPanel getLoadedGraph() { for (Vertex vertex : vertexCollection) { - for (ClassifierVertex classifierVertex: this.classDiagram.getDiagram().keySet()){ + for (ClassifierVertex classifierVertex: classDiagram.getDiagram().keySet()){ if (!classifierVertex.getName().equals(vertex.element())) { continue; } graphView.setVertexPosition(vertex, - classifierVertex.getCoordinates().getValue0(), - classifierVertex.getCoordinates().getValue1()); + classifierVertex.getCoordinate().getX(), + classifierVertex.getCoordinate().getY()); break; } } + return graphView; } diff --git a/src/main/java/model/diagram/javafx/JavaFXPackageDiagramLoader.java b/src/main/java/model/diagram/javafx/JavaFXPackageDiagramLoader.java index d677bc1..390f287 100644 --- a/src/main/java/model/diagram/javafx/JavaFXPackageDiagramLoader.java +++ b/src/main/java/model/diagram/javafx/JavaFXPackageDiagramLoader.java @@ -28,11 +28,11 @@ public JavaFXPackageDiagramLoader(Path graphSavePath) { public Set loadDiagram() throws JsonParseException { Set vertices = new HashSet<>(); try { - byte[] encodedBytes = Files.readAllBytes(this.graphSavePath); - String json = new String(encodedBytes, StandardCharsets.ISO_8859_1); - Gson gson = new GsonBuilder().registerTypeAdapter(PackageVertex.class, - new PackageVertexDeserializer()) - .create(); + byte[] encodedBytes = Files.readAllBytes(graphSavePath); + String json = new String(encodedBytes, StandardCharsets.ISO_8859_1); + Gson gson = new GsonBuilder().registerTypeAdapter(PackageVertex.class, + new PackageVertexDeserializer()) + .create(); PackageVertex[] verticesArray = gson.fromJson(json, PackageVertex[].class); Collections.addAll(vertices, verticesArray); deserializeArcs(vertices); diff --git a/src/main/java/model/diagram/javafx/JavaFXPackageVisualization.java b/src/main/java/model/diagram/javafx/JavaFXPackageVisualization.java index e480442..a5388aa 100644 --- a/src/main/java/model/diagram/javafx/JavaFXPackageVisualization.java +++ b/src/main/java/model/diagram/javafx/JavaFXPackageVisualization.java @@ -18,8 +18,8 @@ public class JavaFXPackageVisualization implements JavaFXVisualization { private final PackageDiagram packageDiagram; - private static SmartGraphPanel graphView; - private static Collection> vertexCollection; + private SmartGraphPanel graphView; + private Collection> vertexCollection; public JavaFXPackageVisualization(PackageDiagram diagram) { this.packageDiagram = diagram; @@ -42,7 +42,7 @@ public Collection> getVertexCollection(){ private Graph createGraph() { Digraph directedGraph = new DigraphEdgeList<>(); - for (PackageVertex vertex: this.packageDiagram.getDiagram().keySet()) { + for (PackageVertex vertex: packageDiagram.getDiagram().keySet()) { if (vertex.getSinkVertices().isEmpty()) { continue; } @@ -53,13 +53,13 @@ private Graph createGraph() { } private void insertVertexArcs(Digraph directedGraph){ - for (Set> arcs : this.packageDiagram.getDiagram().values()) { + for (Set> arcs : packageDiagram.getDiagram().values()) { for (Arc arc: arcs) { if (arc.arcType().equals(ArcType.AGGREGATION)) { directedGraph.insertEdge(arc.targetVertex().getName(), arc.sourceVertex().getName(), arc.targetVertex().getName() + "_" + arc.sourceVertex().getName() + "_" + arc.arcType()); - }else { + } else { directedGraph.insertEdge(arc.sourceVertex().getName(), arc.targetVertex().getName(), arc.sourceVertex().getName() + "_" +arc.targetVertex().getName() + "_" + arc.arcType()); @@ -69,11 +69,11 @@ private void insertVertexArcs(Digraph directedGraph){ } private void setVertexCustomStyle() { - for (PackageVertex vertex: this.packageDiagram.getDiagram().keySet()){ + for (PackageVertex vertex: packageDiagram.getDiagram().keySet()){ if (vertex.getVertexType().equals(VertexType.INTERFACE)) { graphView.getStylableVertex(vertex.getName()).setStyleClass("vertexInterface"); - }else { - if(vertex.getSinkVertices().isEmpty()) { + } else { + if (vertex.getSinkVertices().isEmpty()) { continue; } graphView.getStylableVertex(vertex.getName()).setStyleClass("vertexPackage"); @@ -84,13 +84,13 @@ private void setVertexCustomStyle() { @Override public SmartGraphPanel getLoadedGraph() { for (Vertex vertex : vertexCollection) { - for (PackageVertex packageVertex: this.packageDiagram.getDiagram().keySet()){ - if(!packageVertex.getName().equals(vertex.element())) { + for (PackageVertex packageVertex: packageDiagram.getDiagram().keySet()){ + if (!packageVertex.getName().equals(vertex.element())) { continue; } graphView.setVertexPosition(vertex, - packageVertex.getCoordinates().getValue0(), - packageVertex.getCoordinates().getValue1()); + packageVertex.getCoordinate().getX(), + packageVertex.getCoordinate().getY()); break; } } diff --git a/src/main/java/model/diagram/javafx/PackageVertexDeserializer.java b/src/main/java/model/diagram/javafx/PackageVertexDeserializer.java index 8da9f5f..a5d64d7 100644 --- a/src/main/java/model/diagram/javafx/PackageVertexDeserializer.java +++ b/src/main/java/model/diagram/javafx/PackageVertexDeserializer.java @@ -26,39 +26,39 @@ public class PackageVertexDeserializer implements JsonDeserializer> arcs = new ArrayList<>(); + JsonArray arcsArray = jsonObject.get("arcs").getAsJsonArray(); + List> arcs = new ArrayList<>(); for (int i = 0; i < arcsArray.size(); i++) { JsonObject arcObject = arcsArray.get(i).getAsJsonObject(); String sourceVertex = arcObject.get("source").getAsString(); @@ -85,7 +85,7 @@ private void deserializeArcs(JsonObject jsonObject) { String arcType = arcObject.get("arcType").getAsString(); arcs.add(new Triplet<>(sourceVertex, targetVertex, arcType)); } - this.packageVertex.setDeserializedArcs(arcs); + packageVertex.setDeserializedArcs(arcs); } } diff --git a/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertex.java b/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertex.java index 66176ad..e6f4701 100644 --- a/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertex.java +++ b/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertex.java @@ -18,7 +18,7 @@ public PlantUMLClassifierVertex(ClassDiagram diagram) { public StringBuilder convertSinkVertex() { return new StringBuilder( - this.classDiagram.getDiagram().keySet() + classDiagram.getDiagram().keySet() .stream() .map(sinkVertex -> sinkVertex.getVertexType() + " " + sinkVertex.getName() + " {\n" + diff --git a/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertexArc.java b/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertexArc.java index b0cee52..f59b6af 100644 --- a/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertexArc.java +++ b/src/main/java/model/diagram/plantuml/PlantUMLClassifierVertexArc.java @@ -19,7 +19,7 @@ public PlantUMLClassifierVertexArc(ClassDiagram diagram) { } public StringBuilder convertSinkVertexArc() { - return new StringBuilder(this.classDiagram.getDiagram().values() + return new StringBuilder(classDiagram.getDiagram().values() .stream().flatMap(sinkVertexStream -> sinkVertexStream .stream() .map(sinkVertexArc -> String.join(" ", diff --git a/src/main/java/model/diagram/plantuml/PlantUMLPackageVertex.java b/src/main/java/model/diagram/plantuml/PlantUMLPackageVertex.java index b48cf47..a2cae18 100644 --- a/src/main/java/model/diagram/plantuml/PlantUMLPackageVertex.java +++ b/src/main/java/model/diagram/plantuml/PlantUMLPackageVertex.java @@ -13,7 +13,7 @@ public PlantUMLPackageVertex(PackageDiagram diagram) { } public StringBuilder convertVertex() { - return new StringBuilder(this.packageDiagram.getDiagram().keySet() + return new StringBuilder(packageDiagram.getDiagram().keySet() .stream() .map(vertex -> vertex.getVertexType() + " " + vertex.getName() + " {\n" + "}\n") .collect(Collectors.joining("\n"))); diff --git a/src/main/java/model/diagram/plantuml/PlantUMLPackageVertexArc.java b/src/main/java/model/diagram/plantuml/PlantUMLPackageVertexArc.java index c50c969..a0dc037 100644 --- a/src/main/java/model/diagram/plantuml/PlantUMLPackageVertexArc.java +++ b/src/main/java/model/diagram/plantuml/PlantUMLPackageVertexArc.java @@ -19,8 +19,7 @@ public PlantUMLPackageVertexArc(PackageDiagram diagram) { } public StringBuilder convertVertexArc() { - - return new StringBuilder(this.packageDiagram.getDiagram().values() + return new StringBuilder(packageDiagram.getDiagram().values() .stream() .flatMap(vertexArcStream -> vertexArcStream .stream() diff --git a/src/main/java/model/graph/Arc.java b/src/main/java/model/graph/Arc.java index a7d77f6..1ae3f11 100644 --- a/src/main/java/model/graph/Arc.java +++ b/src/main/java/model/graph/Arc.java @@ -2,4 +2,4 @@ public record Arc (T sourceVertex, T targetVertex, - ArcType arcType) { } \ No newline at end of file + ArcType arcType) {} \ No newline at end of file diff --git a/src/main/java/model/graph/ArcType.java b/src/main/java/model/graph/ArcType.java index 9ecbcd2..1c79de3 100644 --- a/src/main/java/model/graph/ArcType.java +++ b/src/main/java/model/graph/ArcType.java @@ -7,11 +7,11 @@ public enum ArcType implements Comparator { - DEPENDENCY(0), - EXTENSION(1), + DEPENDENCY (0), + EXTENSION (1), IMPLEMENTATION(2), - AGGREGATION(3), - ASSOCIATION(4); + AGGREGATION (3), + ASSOCIATION (4); private static final Map DEGREE_MAP; @@ -33,10 +33,12 @@ public static ArcType get(String arcTypeName) { return DEGREE_MAP.get(arcTypeName.toLowerCase().trim()); } + @Override public String toString() { return super.toString().toLowerCase(); } + @Override public int compare(ArcType o1, ArcType o2) { return Integer.compare(o1.degree, o2.degree); diff --git a/src/main/java/model/graph/ClassifierVertex.java b/src/main/java/model/graph/ClassifierVertex.java index 51e4a4d..f943047 100644 --- a/src/main/java/model/graph/ClassifierVertex.java +++ b/src/main/java/model/graph/ClassifierVertex.java @@ -1,6 +1,5 @@ package model.graph; -import org.javatuples.Pair; import org.javatuples.Triplet; import java.nio.file.Path; @@ -16,9 +15,8 @@ public class ClassifierVertex { private final VertexType vertexType; private final Path path; private final String name; + private final VertexCoordinate coordinate; private List> deserializedArcs; - private double x; - private double y; public ClassifierVertex(Path path, String name, @@ -26,21 +24,28 @@ public ClassifierVertex(Path path, this.vertexType = vertexType; this.path = path; this.name = name; - this.arcs = new ArrayList<>(); - this.methods = new ArrayList<>(); - this.fields = new ArrayList<>(); + arcs = new ArrayList<>(); + methods = new ArrayList<>(); + fields = new ArrayList<>(); + coordinate = new VertexCoordinate(); + } + + + public void updateCoordinate(double x, double y) { + coordinate.x = x; + coordinate.y = y; } public void addArc(ClassifierVertex sourceVertex, ClassifierVertex targetVertex, ArcType arcType) { - this.arcs.add(new Arc<>(sourceVertex, targetVertex, arcType)); + arcs.add(new Arc<>(sourceVertex, targetVertex, arcType)); } public void addMethod(String name, String returnType, ModifierType modifier, Map parameters) { - this.methods.add(new Method(name, returnType, modifier, parameters)); + methods.add(new Method(name, returnType, modifier, parameters)); } public void addField(String name, String type, ModifierType modifier) { - this.fields.add(new Field(name, type, modifier)); + fields.add(new Field(name, type, modifier)); } public void setDeserializedArcs(List> deserializedArcs) { @@ -48,48 +53,45 @@ public void setDeserializedArcs(List> deserializ } public List> getDeserializedArcs() { - return this.deserializedArcs; + return deserializedArcs; } public VertexType getVertexType() { - return this.vertexType; + return vertexType; } public List> getArcs() { - return this.arcs; + return arcs; } public Path getPath() { - return this.path; + return path; } public String getName() { - return this.name; + return name; } public List getMethods() { - return this.methods; + return methods; } public List getFields() { - return this.fields; + return fields; } - public void setCoordinates(double x, double y) { - this.x = x; - this.y = y; + public VertexCoordinate getCoordinate() { + return coordinate; } - public Pair getCoordinates() { - return new Pair<>(x, y); - } - public record Method (String name, - String returnType, - ModifierType modifier, - Map parameters) {} + public record Method(String name, + String returnType, + ModifierType modifier, + Map parameters) {} - public record Field(String name, - String type, + public record Field(String name, + String type, ModifierType modifier) {} + } diff --git a/src/main/java/model/graph/ModifierType.java b/src/main/java/model/graph/ModifierType.java index 4adc75e..02c3545 100644 --- a/src/main/java/model/graph/ModifierType.java +++ b/src/main/java/model/graph/ModifierType.java @@ -5,10 +5,10 @@ import java.util.Map; public enum ModifierType { - PRIVATE(), - PUBLIC(), - PROTECTED(), - PACKAGE_PRIVATE(); + PRIVATE, + PUBLIC, + PROTECTED, + PACKAGE_PRIVATE; private static final Map MODIFIER_TYPE; @@ -19,12 +19,14 @@ public enum ModifierType { } MODIFIER_TYPE = Collections.unmodifiableMap(temp); } + public static ModifierType get(String modifier) { return MODIFIER_TYPE.get(modifier.toLowerCase().trim()); } - + @Override public String toString() { return super.toString().toLowerCase(); } + } diff --git a/src/main/java/model/graph/PackageVertex.java b/src/main/java/model/graph/PackageVertex.java index f661e5d..31c6e0c 100644 --- a/src/main/java/model/graph/PackageVertex.java +++ b/src/main/java/model/graph/PackageVertex.java @@ -1,6 +1,5 @@ package model.graph; -import org.javatuples.Pair; import org.javatuples.Triplet; import java.nio.file.Path; @@ -17,10 +16,9 @@ public class PackageVertex { private final VertexType vertexType; private final Path path; private final String name; + private final VertexCoordinate coordinate; private List> deserializedArcs; private PackageVertex parentPackageVertex; - private double x; - private double y; public PackageVertex(Path path, VertexType vertexType, @@ -30,19 +28,28 @@ public PackageVertex(Path path, this.arcs = new ArrayList<>(); this.sinkVertices = new ArrayList<>(); this.neighbourVertices = new ArrayList<>(); - this.name = (parentName.isEmpty()) ? path.getFileName().toString() : parentName + "." + path.getFileName().toString(); + this.coordinate = new VertexCoordinate(); + this.name = parentName.isEmpty() ? path.getFileName().toString() : String.join(".", + parentName, + path.getFileName().toString()); + } + + + public void createCoordinate(double x, double y) { + coordinate.x = x; + coordinate.y = y; } public void addArc(PackageVertex sourceVertex, PackageVertex targetVertex, ArcType arcType) { - this.arcs.add(new Arc<>(sourceVertex, targetVertex, arcType)); + arcs.add(new Arc<>(sourceVertex, targetVertex, arcType)); } public void addSinkVertex(ClassifierVertex classifierVertex) { - this.sinkVertices.add(classifierVertex); + sinkVertices.add(classifierVertex); } public void addNeighbourVertex(PackageVertex vertex) { - this.neighbourVertices.add(vertex); + neighbourVertices.add(vertex); } public void setParentNode(PackageVertex parentPackageVertex) { @@ -54,45 +61,41 @@ public void setDeserializedArcs(List> deserializ } public List> getDeserializedArcs() { - return this.deserializedArcs; + return deserializedArcs; } public List> getArcs() { - return this.arcs; + return arcs; } public List getSinkVertices() { - return this.sinkVertices; + return sinkVertices; } public List getNeighbourVertices() { - return this.neighbourVertices; + return neighbourVertices; } public Path getPath() { - return this.path; + return path; } public String getName() { - return this.name; + return name; } public VertexType getVertexType() { - return this.vertexType; + return vertexType; } public PackageVertex getParentVertex() { - return this.parentPackageVertex; + return parentPackageVertex; } public ModifierType getModifierType() { return VERTEX_MODIFIER_TYPE; } - public void setCoordinates(double x, double y) { - this.x = x; - this.y = y; + public VertexCoordinate getCoordinate() { + return coordinate; } - public Pair getCoordinates() { - return new Pair<>(x, y); - } } diff --git a/src/main/java/model/graph/VertexCoordinate.java b/src/main/java/model/graph/VertexCoordinate.java new file mode 100644 index 0000000..ce6412e --- /dev/null +++ b/src/main/java/model/graph/VertexCoordinate.java @@ -0,0 +1,18 @@ +package model.graph; + +public class VertexCoordinate { + public double x; + public double y; + + public VertexCoordinate() {} + + + public double getX() { + return x; + } + + public double getY() { + return y; + } + +} diff --git a/src/main/java/model/graph/VertexType.java b/src/main/java/model/graph/VertexType.java index f5289f7..9896f73 100644 --- a/src/main/java/model/graph/VertexType.java +++ b/src/main/java/model/graph/VertexType.java @@ -24,7 +24,9 @@ public static VertexType get(String vertexType) { return VERTEX_TYPE.get(vertexType.toLowerCase().trim()); } + @Override public String toString() { return super.toString().toLowerCase(); } + } diff --git a/src/main/java/parser/FileVisitor.java b/src/main/java/parser/FileVisitor.java new file mode 100644 index 0000000..7d2a5f6 --- /dev/null +++ b/src/main/java/parser/FileVisitor.java @@ -0,0 +1,338 @@ +package parser; + +import com.github.javaparser.ParserConfiguration; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.ConstructorDeclaration; +import com.github.javaparser.ast.body.EnumDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.RecordDeclaration; +import com.github.javaparser.ast.expr.ObjectCreationExpr; +import com.github.javaparser.ast.expr.VariableDeclarationExpr; +import com.github.javaparser.ast.visitor.VoidVisitorAdapter; +import parser.tree.LeafNode; +import parser.tree.LeafNodeBuilder; +import parser.tree.ModifierType; +import parser.tree.NodeType; +import parser.tree.PackageNode; + +import java.io.FileNotFoundException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * This class is responsible for the creation of the AST of a Java source file using Javaparser. + * Using the different visitors, it parses the file's inheritance declarations, constructor, methods parameters, + * return types, field & local variable declarations as well as the instantiated objects that aren't assigned to a variable. + */ +public class FileVisitor { + private final InheritanceVisitor inheritanceVisitor = new InheritanceVisitor(); + private final ConstructorVisitor constructorVisitor = new ConstructorVisitor(); + private final FieldVisitor fieldNameVisitor = new FieldVisitor(); + private final MethodVisitor methodNameVisitor = new MethodVisitor(); + private final EnumVisitor enumVisitor = new EnumVisitor(); + private final MemberVisitor memberVisitor = new MemberVisitor(); + private final VariableVisitor variableVisitor = new VariableVisitor(); + private final ObjectCreationVisitor objectCreationVisitor = new ObjectCreationVisitor(); + private final ImportVisitor importVisitor = new ImportVisitor(); + private final LeafNodeBuilder leafNodeBuilder; + private final Map variablesMap; + private final List objectTypes; + private final List methods; + private final List fields; + private final Path path; + private final List imports; + private final List createdObjects; + private final List unassignedObjects; + private final List implementedInterfaces; + private final List innerClasses; + private final List enums; + private final List records; + private NodeType nodeType; + private boolean isClassOrInterface; + private String baseClass; + private String nodeName; + + /** + * The FileVisitor's default constructor + * + * @param parentNode the LeafNode representing the Java source file that we are visiting + */ + public FileVisitor(PackageNode parentNode, Path path) { + this.leafNodeBuilder = new LeafNodeBuilder(parentNode, path); + this.createdObjects = new ArrayList<>(); + this.unassignedObjects = new ArrayList<>(); + this.imports = new ArrayList<>(); + this.implementedInterfaces = new ArrayList<>(); + this.objectTypes = new ArrayList<>(); + this.methods = new ArrayList<>(); + this.fields = new ArrayList<>(); + this.enums = new ArrayList<>(); + this.records = new ArrayList<>(); + this.variablesMap = new HashMap<>(); + this.innerClasses = new ArrayList<>(); + this.path = path; + this.baseClass = ""; + this.nodeName = ""; + this.nodeType = null; + } + + /** + * This method is responsible for the creation of the AST. + */ + public LeafNode createAST() { + try { + StaticJavaParser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_17); + CompilationUnit compilationUnit = StaticJavaParser.parse(path.toFile()); + + isClassOrInterface = false; + compilationUnit.accept(inheritanceVisitor, null); + + if (!isClassOrInterface) { + compilationUnit.accept(enumVisitor, null); + } else { + compilationUnit.accept(importVisitor, null); + compilationUnit.accept(memberVisitor, null); + compilationUnit.accept(constructorVisitor, null); + compilationUnit.accept(fieldNameVisitor, null); + compilationUnit.accept(variableVisitor, null); + compilationUnit.accept(methodNameVisitor, null); + compilationUnit.accept(objectCreationVisitor, null); + unassignedObjects.addAll(populateCreatedObjects()); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + return leafNodeBuilder.setNodeType(nodeType) + .setBaseClass(baseClass) + .setFields(fields) + .setCreatedObjects(unassignedObjects) + .setMethods(methods) + .setNodeName(nodeName) + .setVariables(variablesMap) + .setImports(imports) + .setRecords(records) + .setInnerClasses(innerClasses) + .setImplementedInterface(implementedInterfaces) + .setInnerEnums(enums) + .build(); + } + + private class InheritanceVisitor extends VoidVisitorAdapter { + + @Override + public void visit(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, Void arg) { + super.visit(classOrInterfaceDeclaration, arg); + + if (!path.endsWith(classOrInterfaceDeclaration.getNameAsString() + ".java")) { + innerClasses.add(classOrInterfaceDeclaration.getNameAsString()); + return; + } + nodeName = classOrInterfaceDeclaration.getNameAsString(); + isClassOrInterface = true; + NodeType localnodeType; + if (classOrInterfaceDeclaration.isInterface()) { + localnodeType = NodeType.INTERFACE; + } else { + localnodeType = NodeType.CLASS; + classOrInterfaceDeclaration.getExtendedTypes() + .forEach(classOrInterfaceType -> baseClass = classOrInterfaceType.getNameAsString()); + } + + nodeType = localnodeType; + classOrInterfaceDeclaration.getImplementedTypes() + .forEach(classOrInterfaceType -> implementedInterfaces.add(classOrInterfaceType.getNameAsString())); + + } + } + + private class ConstructorVisitor extends VoidVisitorAdapter { + + @Override + public void visit(ConstructorDeclaration constructorDeclaration, Void arg) { + super.visit(constructorDeclaration, arg); + + ModifierType modifierType; + if (constructorDeclaration.getModifiers().isEmpty()) { + modifierType = ModifierType.PACKAGE_PRIVATE; + } else { + modifierType = ModifierType.get(constructorDeclaration.getModifiers().get(0).toString()); + } + + Map parameters = new HashMap<>(); + constructorDeclaration.getParameters() + .forEach(parameter -> parameters.put(parameter.getNameAsString(), + getType(parameter.getTypeAsString()))); + methods.add(new LeafNode.Method(constructorDeclaration.getNameAsString(), + "Constructor", + modifierType, + parameters)); + } + } + + private class FieldVisitor extends VoidVisitorAdapter { + private ModifierType modifierType; + + @Override + public void visit(FieldDeclaration fieldDeclaration, Void arg) { + super.visit(fieldDeclaration, arg); + + fieldDeclaration.getVariables().forEach(variable -> { + if (fieldDeclaration.getModifiers().isEmpty()) { + this.modifierType = ModifierType.PACKAGE_PRIVATE; + } else { + this.modifierType = ModifierType.get(fieldDeclaration.getModifiers().get(0).toString()); + } + fields.add(new LeafNode.Field(variable.getNameAsString(), + getType(variable.getTypeAsString()), + modifierType)); + }); + } + } + + private class VariableVisitor extends VoidVisitorAdapter { + + @Override + public void visit(VariableDeclarationExpr variableDeclarationExpr, Void arg) { + super.visit(variableDeclarationExpr, null); + + Pattern pattern = Pattern.compile("[A-Za-z0-9]+ [A-Za-z0-9]+ = new ([A-Za-z0-9]+)\\([A-Za-z0-9]*[, A-Za-z0-9*]*\\)"); + Matcher matcher = pattern.matcher(variableDeclarationExpr.toString()); + if (!matcher.find()) { + return; + } + objectTypes.add(matcher.group(1)); + variableDeclarationExpr.getVariables() + .forEach(variableDeclaration -> variablesMap.put(variableDeclaration.getNameAsString(), + getType(variableDeclaration.getTypeAsString()))); + } + } + + private class MethodVisitor extends VoidVisitorAdapter { + + @Override + public void visit(MethodDeclaration methodDeclaration, Void arg) { + super.visit(methodDeclaration, arg); + + ModifierType modifierType; + if (methodDeclaration.getModifiers().isEmpty()) { + modifierType = ModifierType.PACKAGE_PRIVATE; + } else { + modifierType = ModifierType.get(methodDeclaration.getModifiers().get(0).toString()); + } + Map parameters = new HashMap<>(); + methodDeclaration.getParameters() + .forEach(parameter -> parameters.put(parameter.getNameAsString(), + getType(parameter.getTypeAsString()))); + methods.add(new LeafNode.Method(methodDeclaration.getNameAsString(), + getType(methodDeclaration.getTypeAsString()), + modifierType, + parameters)); + } + } + + private class ObjectCreationVisitor extends VoidVisitorAdapter { + + @Override + public void visit(ObjectCreationExpr objectCreationExpr, Void arg) { + super.visit(objectCreationExpr, arg); + + createdObjects.add(getType(objectCreationExpr.asObjectCreationExpr().getType().asString())); + } + + } + + private class EnumVisitor extends VoidVisitorAdapter { + + @Override + public void visit(EnumDeclaration enumDeclaration, Void arg) { + super.visit(enumDeclaration, arg); + + nodeName = enumDeclaration.getNameAsString(); + nodeType = NodeType.ENUM; + } + + } + + private class MemberVisitor extends VoidVisitorAdapter { + + public void visit(EnumDeclaration enumDeclaration, Void arg) { + super.visit(enumDeclaration, arg); + + enums.add(enumDeclaration.getNameAsString()); + } + + public void visit(RecordDeclaration n, Void arg) { + super.visit(n, arg); + + records.add(n.getNameAsString()); + } + + } + + private class ImportVisitor extends VoidVisitorAdapter { + + public void visit(ImportDeclaration importDeclaration, Void arg) { + super.visit(importDeclaration, arg); + + imports.add(importDeclaration + .getNameAsString() + .replaceFirst("^import ", "").trim() + .replaceAll(";$", "")); + } + + } + + private List populateCreatedObjects() { + List notAssignedCreatedObjects = filterAssignedCreatedObjects(fields.stream().map(LeafNode.Field::fieldType).collect(Collectors.toCollection(ArrayList::new)), + createdObjects); + notAssignedCreatedObjects = filterAssignedCreatedObjects(new ArrayList<>(variablesMap.values()), + notAssignedCreatedObjects); + notAssignedCreatedObjects = filterAssignedCreatedObjects(objectTypes, + notAssignedCreatedObjects); + return notAssignedCreatedObjects; + } + + private List filterAssignedCreatedObjects(List assignedObjects, + List createdObjects) { + List newList = new ArrayList<>(); + Collections.sort(assignedObjects); + Collections.sort(createdObjects); + int i = 0; + int j = 0; + + main: + while (i < createdObjects.size()) { + while (j < assignedObjects.size()) { + if (createdObjects.get(i).equals(assignedObjects.get(j))) { + j++; + } else { + newList.add(createdObjects.get(i)); + } + i++; + if (i == createdObjects.size()) { + break main; + } + } + newList.add(createdObjects.get(i)); + i++; + } + return newList; + } + + private static String getType(String type) { + return type.replaceAll("<", "[").replaceAll(">", "]"); + } +} diff --git a/src/main/java/parser/IRelationshipIdentifier.java b/src/main/java/parser/IRelationshipIdentifier.java new file mode 100644 index 0000000..9bdefea --- /dev/null +++ b/src/main/java/parser/IRelationshipIdentifier.java @@ -0,0 +1,35 @@ +package parser; + +import parser.factory.Parser; +import parser.tree.LeafNode; +import parser.tree.PackageNode; +import parser.tree.Relationship; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This class is responsible for the creation of the branches between the Java + * source files. The branches have a type, e.g., inheritance, implementation. + * The branches are also directed with a starting and an ending node. + */ +public interface IRelationshipIdentifier { + + /** + * This method is responsible for creating the relationships of the package and leaf nodes. + * + * @param packageNodes The collection of package nodes that have been parsed. + * @return The collection of relationships that were created. + */ + Map>> createLeafNodesRelationships(Map packageNodes); + + /** + * This method identifies the package node relationships by parsing the created leaf node relationships. + * + * @param leafNodeRelationships The relationships that were created by {@link Parser#createRelationships(Map)}. + * @return The package node relationships that were created by parsing the leaf node relationships. + */ + Map>> identifyPackageNodeRelationships(Map>> leafNodeRelationships); +} diff --git a/src/main/java/parser/Interpreter.java b/src/main/java/parser/Interpreter.java index 418f739..39fb5cc 100644 --- a/src/main/java/parser/Interpreter.java +++ b/src/main/java/parser/Interpreter.java @@ -16,100 +16,113 @@ import java.nio.file.Path; import java.nio.file.Paths; -import java.util.EnumMap; import java.util.HashMap; import java.util.Map; +import java.util.Set; public class Interpreter { private static final ParserType PARSER_TYPE = ParserType.JAVAPARSER; - private final Map packageNodeVertexMap; - private final Map leafNodeSinkVertexMap; - private final Map vertices; - private final Map sinkVertices; - private Map packageNodes; + private final Map packageNodeVertexMap; + private final Map leafNodeSinkVertexMap; + private final Map vertices; + private final Map sinkVertices; + private Map>> packageNodeRelationships; + private Map>> leafNodeRelationships; + private Map packageNodes; public Interpreter() { - this.vertices = new HashMap<>(); - this.sinkVertices = new HashMap<>(); - this.packageNodeVertexMap = new HashMap<>(); - this.leafNodeSinkVertexMap = new HashMap<>(); + vertices = new HashMap<>(); + sinkVertices = new HashMap<>(); + packageNodeVertexMap = new HashMap<>(); + leafNodeSinkVertexMap = new HashMap<>(); } public void parseProject(Path sourcePackagePath) { - Parser projectParser = ProjectParserFactory.createProjectParser(PARSER_TYPE); - this.packageNodes = projectParser.parseSourcePackage(sourcePackagePath); + Parser projectParser = ProjectParserFactory.createProjectParser(PARSER_TYPE); + packageNodes = projectParser.parseSourcePackage(sourcePackagePath); + leafNodeRelationships = projectParser.createRelationships(packageNodes); + packageNodeRelationships = projectParser.identifyPackageNodeRelationships(leafNodeRelationships); } public void convertTreeToGraph() { - PackageNodeCleaner packageNodeCleaner = new PackageNodeCleaner(this.packageNodes); - this.packageNodes = packageNodeCleaner.removeNonPackageNodes(); + packageNodes = PackageNodeCleaner.removeNonPackageNodes(packageNodes); populateVertexMaps(); addVertexArcs(); - this.leafNodeSinkVertexMap.values().forEach(sinkVertex -> sinkVertices.put(sinkVertex.getPath(), sinkVertex)); - this.packageNodeVertexMap.values().forEach(vertex -> vertices.put(vertex.getPath(), vertex)); + leafNodeSinkVertexMap.values() + .forEach(sinkVertex -> sinkVertices.put(sinkVertex.getPath(), sinkVertex)); + packageNodeVertexMap.values() + .forEach(vertex -> vertices.put(vertex.getPath(), vertex)); } private void populateVertexMaps() { - for (PackageNode packageNode: this.packageNodes.values()) { - PackageVertex vertex = this.packageNodeVertexMap + for (PackageNode packageNode: packageNodes.values()) { + PackageVertex vertex = packageNodeVertexMap .computeIfAbsent(packageNode, k -> - new PackageVertex(packageNode.getPackageNodesPath(), - EnumMapper.vertexTypeEnumMap.get(packageNode.getType()), - packageNode.getParentNode().getName()) - ); + new PackageVertex(packageNode.getPath(), + TypeConverter.convertVertexType(packageNode.getNodeType()), + packageNode.getParentNode().getNodeName())); + for (LeafNode leafNode: packageNode.getLeafNodes().values()) { - vertex.addSinkVertex(this.leafNodeSinkVertexMap.computeIfAbsent(leafNode, k -> createSinkVertex(leafNode))); + vertex.addSinkVertex(leafNodeSinkVertexMap.computeIfAbsent(leafNode, k -> createSinkVertex(leafNode))); } } - for (PackageNode packageNode: this.packageNodes.values()) { - this.packageNodeVertexMap.get(packageNode) - .setParentNode( - this.packageNodeVertexMap.getOrDefault(packageNode.getParentNode(), - new PackageVertex(Paths.get(""), - VertexType.PACKAGE, - "")) - ); + for (PackageNode packageNode: packageNodes.values()) { + packageNodeVertexMap.get(packageNode) + .setParentNode(packageNodeVertexMap.getOrDefault(packageNode.getParentNode(), + new PackageVertex(Paths.get(""), + VertexType.PACKAGE, + ""))); + for (PackageNode subNode: packageNode.getSubNodes().values()) { - this.packageNodeVertexMap.get(packageNode).addNeighbourVertex(this.packageNodeVertexMap.get(subNode)); + packageNodeVertexMap.get(packageNode).addNeighbourVertex(packageNodeVertexMap.get(subNode)); } } } private void addVertexArcs() { - for (PackageNode packageNode: this.packageNodes.values()) { - PackageVertex vertex = this.packageNodeVertexMap.get(packageNode); - for (Relationship relationship: packageNode.getPackageNodeRelationships()) { - vertex.addArc(vertex, this.packageNodeVertexMap.get(relationship.endingNode()), EnumMapper.edgeEnumMap.get(relationship.relationshipType())); + for (PackageNode packageNode: packageNodes.values()) { + PackageVertex vertex = packageNodeVertexMap.get(packageNode); + if (packageNodeRelationships.containsKey(packageNode)) { + for (Relationship relationship : packageNodeRelationships.get(packageNode)) { + vertex.addArc(vertex, + packageNodeVertexMap.get(relationship.endingNode()), + TypeConverter.convertRelationshipType(relationship.relationshipType())); + } + addSinkVertexArcs(packageNode); } - addSinkVertexArcs(packageNode); } } private void addSinkVertexArcs(PackageNode packageNode) { for (LeafNode leafNode: packageNode.getLeafNodes().values()) { - ClassifierVertex classifierVertex = this.leafNodeSinkVertexMap.get(leafNode); - for (Relationship relationship: leafNode.getLeafNodeRelationships()) { - classifierVertex.addArc(classifierVertex, this.leafNodeSinkVertexMap.get(relationship.endingNode()), EnumMapper.edgeEnumMap.get(relationship.relationshipType())); + ClassifierVertex classifierVertex = leafNodeSinkVertexMap.get(leafNode); + if (leafNodeRelationships.containsKey(leafNode)) { + for (Relationship relationship : leafNodeRelationships.get(leafNode)) { + classifierVertex.addArc(classifierVertex, + leafNodeSinkVertexMap.get(relationship.endingNode()), + TypeConverter.convertRelationshipType(relationship.relationshipType())); + } } } } private ClassifierVertex createSinkVertex(LeafNode leafNode) { - ClassifierVertex classifierVertex = new ClassifierVertex(leafNode.getLeafNodesPath(), leafNode.getName(), EnumMapper.vertexTypeEnumMap.get(leafNode.getType())); - leafNode.getFields() + ClassifierVertex classifierVertex = new ClassifierVertex(leafNode.path(), + leafNode.nodeName(), + TypeConverter.convertVertexType(leafNode.nodeType())); + leafNode.fields() .forEach(field -> - classifierVertex.addField(field.getValue0(), - field.getValue1(), - EnumMapper.modifierTypeEnumMap.get(field.getValue2())) - ); - leafNode.getMethods() - .forEach((method, parameters) -> - classifierVertex.addMethod(method.getValue0().split("\\$")[0], - method.getValue1(), EnumMapper.modifierTypeEnumMap.get(method.getValue2()), - parameters) - ); + classifierVertex.addField(field.fieldNames(), + field.fieldType(), + TypeConverter.convertModifierType(field.modifierType()))); + leafNode.methods() + .forEach((method) -> + classifierVertex.addMethod(method.methodName(), + method.returnType(), + TypeConverter.convertModifierType(method.modifierType()), + method.parameters())); return classifierVertex; } @@ -125,35 +138,43 @@ public Map getSinkVertices() { return sinkVertices; } - private static class EnumMapper { - - private static final EnumMap vertexTypeEnumMap = new EnumMap<>( - Map.of( - NodeType.CLASS, VertexType.CLASS, - NodeType.INTERFACE, VertexType.INTERFACE, - NodeType.ENUM, VertexType.ENUM, - NodeType.PACKAGE, VertexType.PACKAGE - ) - ); - - private static final EnumMap edgeEnumMap = new EnumMap<>( - Map.of( - RelationshipType.DEPENDENCY, ArcType.DEPENDENCY, - RelationshipType.ASSOCIATION, ArcType.ASSOCIATION, - RelationshipType.AGGREGATION, ArcType.AGGREGATION, - RelationshipType.IMPLEMENTATION, ArcType.IMPLEMENTATION, - RelationshipType.EXTENSION, ArcType.EXTENSION - ) - ); - - private static final EnumMap modifierTypeEnumMap = new EnumMap<>( - Map.of( - ModifierType.PRIVATE, model.graph.ModifierType.PRIVATE, - ModifierType.PUBLIC, model.graph.ModifierType.PUBLIC, - ModifierType.PROTECTED, model.graph.ModifierType.PROTECTED, - ModifierType.PACKAGE_PRIVATE, model.graph.ModifierType.PACKAGE_PRIVATE - ) - ); + public Map>> getPackageNodeRelationships() { + return packageNodeRelationships; + } + + public Map>> getLeafNodeRelationships() { + return leafNodeRelationships; + } + + private static class TypeConverter { + + private static VertexType convertVertexType(NodeType nodeType) { + return switch (nodeType) { + case CLASS -> VertexType.CLASS; + case INTERFACE -> VertexType.INTERFACE; + case ENUM -> VertexType.ENUM; + case PACKAGE -> VertexType.PACKAGE; + }; + } + + private static ArcType convertRelationshipType(RelationshipType relationshipType) { + return switch (relationshipType) { + case DEPENDENCY -> ArcType.DEPENDENCY; + case ASSOCIATION -> ArcType.ASSOCIATION; + case AGGREGATION -> ArcType.AGGREGATION; + case IMPLEMENTATION -> ArcType.IMPLEMENTATION; + case EXTENSION -> ArcType.EXTENSION; + }; + } + + private static model.graph.ModifierType convertModifierType(ModifierType modifierType) { + return switch (modifierType) { + case PRIVATE -> model.graph.ModifierType.PRIVATE; + case PUBLIC -> model.graph.ModifierType.PUBLIC; + case PROTECTED -> model.graph.ModifierType.PROTECTED; + case PACKAGE_PRIVATE -> model.graph.ModifierType.PACKAGE_PRIVATE; + }; + } } } diff --git a/src/main/java/parser/PackageNodeCleaner.java b/src/main/java/parser/PackageNodeCleaner.java index 5aeb5ab..25f7183 100644 --- a/src/main/java/parser/PackageNodeCleaner.java +++ b/src/main/java/parser/PackageNodeCleaner.java @@ -7,30 +7,25 @@ import java.util.Map; public class PackageNodeCleaner { - private final Map packageNodes; - public PackageNodeCleaner(Map packageNodes) { - this.packageNodes = packageNodes; - } - - public Map removeNonPackageNodes() { + public static Map removeNonPackageNodes(Map packageNodes) { Map validPackageNodes = new HashMap<>(); - for (PackageNode packageNode: this.packageNodes.values()) { + for (PackageNode packageNode: packageNodes.values()) { if (isPackageNodeValid(packageNode)) { - validPackageNodes.put(packageNode.getPackageNodesPath(), packageNode); + validPackageNodes.put(packageNode.getPath(), packageNode); continue; } PackageNode parentNode = packageNode.getParentNode(); - if (parentNode.getPackageNodesPath().toString().isEmpty()) { + if (parentNode.getPath().toString().isEmpty()) { continue; } - parentNode.getSubNodes().remove(packageNode.getPackageNodesPath()); + parentNode.getSubNodes().remove(packageNode.getPath()); } return validPackageNodes; } - private boolean isPackageNodeValid(PackageNode packageNode) { + private static boolean isPackageNodeValid(PackageNode packageNode) { if (packageNode.getSubNodes().isEmpty()) { return packageNode.isValid(); } diff --git a/src/main/java/parser/ProjectParser.java b/src/main/java/parser/ProjectParser.java new file mode 100644 index 0000000..08d5a42 --- /dev/null +++ b/src/main/java/parser/ProjectParser.java @@ -0,0 +1,70 @@ +package parser; + +import parser.factory.Parser; +import parser.tree.LeafNode; +import parser.tree.PackageNode; +import parser.tree.Relationship; + +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class ProjectParser implements Parser { + + private final Map packageNodes; + + public ProjectParser() { + this.packageNodes = new HashMap<>(); + } + + + @Override + public Map parseSourcePackage(Path sourcePackagePath) { + PackageNode sourcePackage = new PackageNode(sourcePackagePath); + packageNodes.put(sourcePackage.getPath(), sourcePackage); + parseFolder(sourcePackage); + return packageNodes; + } + + @Override + public Map>> createRelationships(Map packageNodes) { + IRelationshipIdentifier relationshipIdentifier = new RelationshipIdentifier(); + return relationshipIdentifier.createLeafNodesRelationships(packageNodes); + } + + @Override + public Map>> identifyPackageNodeRelationships(Map>> leafNodeRelationships) { + IRelationshipIdentifier relationshipIdentifier = new RelationshipIdentifier(); + return relationshipIdentifier.identifyPackageNodeRelationships(leafNodeRelationships); + } + + private void parseFolder(PackageNode currentNode) { + try (DirectoryStream filesStream = Files.newDirectoryStream(currentNode.getPath())) { + for (Path path: filesStream) { + if (Files.isDirectory(path)) { + PackageNode subNode = new PackageNode(currentNode, path); + packageNodes.put(subNode.getPath(), subNode); + currentNode.getSubNodes().put(subNode.getPath(), subNode); + parseFolder(subNode); + } + else if (isJavaSourceFile(path)) { + FileVisitor fileVisitor = new FileVisitor(currentNode, path); + LeafNode leafNode = fileVisitor.createAST(); + currentNode.getLeafNodes().put(leafNode.nodeName(), leafNode); + } + } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + + private boolean isJavaSourceFile(Path filePath) { + return filePath.normalize().toString().toLowerCase().endsWith(".java"); + } + +} diff --git a/src/main/java/parser/RelationshipIdentifier.java b/src/main/java/parser/RelationshipIdentifier.java new file mode 100644 index 0000000..5e154a3 --- /dev/null +++ b/src/main/java/parser/RelationshipIdentifier.java @@ -0,0 +1,209 @@ +package parser; + +import parser.tree.LeafNode; +import parser.tree.PackageNode; +import parser.tree.Relationship; +import parser.tree.RelationshipType; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +public class RelationshipIdentifier implements IRelationshipIdentifier { + private final Map>> leafNodeRelationships; + private final List leafNodes; + + public RelationshipIdentifier() { + leafNodes = new ArrayList<>(); + leafNodeRelationships = new HashMap<>(); + } + + public Map>> createLeafNodesRelationships(Map packageNodes) { + packageNodes.values().forEach(packageNode -> leafNodes.addAll(packageNode.getLeafNodes().values())); + for (int i = 0; i < leafNodes.size(); i++) { + for (int j = i+1; j < leafNodes.size(); j++) { + checkRelationship(i, j); + checkRelationship(j, i); + } + } + return leafNodeRelationships; + } + + public Map>> identifyPackageNodeRelationships(Map>> leafNodeRelationships) { + Map>> packageNodeRelationships = new HashMap<>(); + ArrayList> relationships = leafNodeRelationships + .values() + .stream() + .flatMap(Set::stream) + .collect(Collectors.toCollection(ArrayList::new)); + + for (Relationship relationship: relationships) { + if (relationship.startingNode().parentNode().equals(relationship.endingNode().parentNode())) { + continue; + } + packageNodeRelationships.computeIfAbsent(relationship.startingNode().parentNode(), + packageNode -> new HashSet<>()).add(new Relationship<>(relationship.startingNode().parentNode(), + relationship.endingNode().parentNode(), + RelationshipType.DEPENDENCY)); + } + return packageNodeRelationships; + } + + private boolean isAssociation(int i, int j) { + return doesRelationshipExist(leafNodes.get(i).fields() + .stream() + .map(LeafNode.Field::fieldType) + .collect(Collectors.toCollection(ArrayList::new)), + leafNodes.get(j).nodeName()); + } + + private boolean isAggregation(int i, int j) { + return isRelationshipAggregation(leafNodes.get(i).fields() + .stream() + .map(LeafNode.Field::fieldType) + .collect(Collectors.toCollection(ArrayList::new)), + leafNodes.get(j).nodeName()); + } + + private boolean doesRelationshipExist(List leafNodesTypes, + String leafNodesName) { + for (String leafNodesType : leafNodesTypes) { + if (doesFieldBelongToClass(leafNodesType, leafNodesName)) { + return true; + } + } + return false; + } + + private boolean isRelationshipAggregation(List leafNodesTypes, + String leafNodesName) { + for (String leafNodeType: leafNodesTypes) { + if (isFieldOfTypeCollection(leafNodeType, leafNodesName) && + doesFieldBelongToClass(leafNodeType, leafNodesName)) { + return true; + } + } + return false; + } + + private boolean doesFieldBelongToClass(String leafNodesType, + String leafNodesName) { + for (String type: leafNodesType.replace("[", ",").replace("]", ",").split(",")) { + if (leafNodesName.equals(type)) { + return true; + } + } + return false; + } + + private boolean isFieldOfTypeCollection(String s, + String leafNodesName) { + return s.contains(leafNodesName+"[") || + s.startsWith("List") || + s.startsWith("ArrayList") || + s.startsWith("Map") || + s.startsWith("HashMap") || + s.startsWith("ArrayDeque") || + s.startsWith("Deque") || + s.startsWith("LinkedList") || + s.startsWith("LinkedHashMap") || + s.startsWith("PriorityQueue") || + s.startsWith("Queue"); + } + + private void createRelationship(int i, + int j, + RelationshipType relationshipType) { + leafNodeRelationships + .computeIfAbsent(leafNodes.get(i), leafNode -> new HashSet<>()) + .add(new Relationship<>(leafNodes.get(i), + leafNodes.get(j), + relationshipType)); + } + + private void checkRelationship(int i, int j) { + List imports = leafNodes.get(i).imports(); + boolean isImported = imports + .stream() + .anyMatch(imprt -> (String.format("%s.%s", + leafNodes.get(j).parentNode().getNodeName(), + leafNodes.get(j).nodeName())).endsWith(imprt) || + (String.format("%s.*", + leafNodes.get(j).parentNode().getNodeName())).endsWith(imprt)); + + if (!isImported && !isSubNode(i, j)) { + return; + } + if (isDependency(i, j)) { + createRelationship(i, j, RelationshipType.DEPENDENCY); + } + if (isAggregation(i, j)) { + createRelationship(i, j, RelationshipType.AGGREGATION); + } else if (isAssociation(i, j)) { + createRelationship(i, j, RelationshipType.ASSOCIATION); + } + + if (isExtension(i, j)) { + createRelationship(i, j, RelationshipType.EXTENSION); + } + if (isImplementation(i, j)) { + createRelationship(i, j, RelationshipType.IMPLEMENTATION); + } + } + + private boolean isSubNode(int i, int j) { + PackageNode node = leafNodes.get(j).parentNode(); + while (true) { + if (node.equals(leafNodes.get(i).parentNode())) { + return true; + } + + if (node.getPath().toString().isEmpty()) { + return false; + } + node = node.getParentNode(); + } + } + + private boolean isDependency(int i, int j) { + if (doesRelationshipExist(leafNodes.get(i).getMethodParameterTypes(), + leafNodes.get(j).nodeName()) || + doesRelationshipExist(leafNodes.get(i).getMethodReturnTypes(), + leafNodes.get(j).nodeName()) || + doesRelationshipExist(new ArrayList<>(getLeafNode(i).variables().values()), + leafNodes.get(j).nodeName())) { + return true; + } + return doesRelationshipExist(leafNodes.get(i).createdObjects(), + leafNodes.get(j).nodeName()); + } + + private boolean isExtension(int i, int j) { + if (leafNodes.get(i).baseClass().isEmpty()) { + return false; + } + return leafNodes.get(i).baseClass().equals(leafNodes.get(j).nodeName()); + } + + private boolean isImplementation(int i, int j) { + if (leafNodes.get(i).implementedInterfaces().isEmpty()) { + return false; + } + + for (String implementedInterface: leafNodes.get(i).implementedInterfaces()) { + if (implementedInterface.equals(leafNodes.get(j).nodeName())) { + return true; + } + } + return false; + } + + private LeafNode getLeafNode(int i) { + return leafNodes.get(i); + } +} diff --git a/src/main/java/parser/factory/Parser.java b/src/main/java/parser/factory/Parser.java index 855e33a..08ea06f 100644 --- a/src/main/java/parser/factory/Parser.java +++ b/src/main/java/parser/factory/Parser.java @@ -1,21 +1,36 @@ package parser.factory; +import parser.tree.LeafNode; import parser.tree.PackageNode; +import parser.tree.Relationship; import java.nio.file.Path; +import java.util.List; import java.util.Map; +import java.util.Set; public interface Parser { /** - * This method creates the root of the tree, from the path of the source package, calls the - * parseFolder method, that's responsible for the parsing of the source's folder and creates an object - * of the RelationshipIdentifier class with the created nodes in order to create the Relationships. + * This method creates the root of the tree, from the path of the source package, calls the parseFolder method, that's responsible for the parsing of the source's folder and creates an object of the RelationshipIdentifier class with the created nodes in order to create the Relationships. * - * @param sourcePackagePath the path of the project's source folder - * @return a Map with the internal nodes of the tree, i.e. the valid source packages that contain - * java source files + * @param sourcePackagePath the path of the project's source folder */ Map parseSourcePackage(Path sourcePackagePath); + /** + * This method creates the relationships among the nodes of the tree + * + * @param packageNodes The collection of package nodes that have been parsed. + * @return The collection of relationships that were created. + */ + Map>> createRelationships(Map packageNodes); + + /** + * This method identifies the package node relationships by parsing the created leaf node relationships. + * + * @param leafNodeRelationships The relationships that were created by {@link Parser#createRelationships(Map)}. + * @return The package node relationships that were created by parsing the leaf node relationships. + */ + Map>> identifyPackageNodeRelationships(Map>> leafNodeRelationships); } diff --git a/src/main/java/parser/factory/ProjectParserFactory.java b/src/main/java/parser/factory/ProjectParserFactory.java index 35ca647..cfbdaf8 100644 --- a/src/main/java/parser/factory/ProjectParserFactory.java +++ b/src/main/java/parser/factory/ProjectParserFactory.java @@ -1,14 +1,13 @@ package parser.factory; -import parser.javaparser.JavaparserProjectParser; -import parser.jdt.JDTProjectParser; +import parser.ProjectParser; public class ProjectParserFactory { public static Parser createProjectParser(ParserType parserType) { if (parserType.equals(ParserType.JDT)) { - return new JDTProjectParser(); + throw new RuntimeException(); } - return new JavaparserProjectParser(); + return new ProjectParser(); } } diff --git a/src/main/java/parser/javaparser/JavaparserFileVisitor.java b/src/main/java/parser/javaparser/JavaparserFileVisitor.java deleted file mode 100644 index 8b5e85d..0000000 --- a/src/main/java/parser/javaparser/JavaparserFileVisitor.java +++ /dev/null @@ -1,292 +0,0 @@ -package parser.javaparser; - -import com.github.javaparser.ParserConfiguration; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.ast.Node; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import com.github.javaparser.ast.body.ConstructorDeclaration; -import com.github.javaparser.ast.body.EnumDeclaration; -import com.github.javaparser.ast.body.FieldDeclaration; -import com.github.javaparser.ast.body.MethodDeclaration; -import com.github.javaparser.ast.expr.ObjectCreationExpr; -import com.github.javaparser.ast.expr.VariableDeclarationExpr; -import com.github.javaparser.ast.visitor.VoidVisitor; -import com.github.javaparser.ast.visitor.VoidVisitorAdapter; -import parser.tree.LeafNode; -import parser.tree.ModifierType; -import parser.tree.NodeType; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * This class is responsible for the creation of the AST of a Java source file using Javaparser. - * Using the different visitors, it parses the file's inheritance declarations, constructor, methods parameters, - * return types, field & local variable declarations as well as the instantiated objects that aren't assigned to a variable. - */ -public class JavaparserFileVisitor { - - private final List allCreatedObjects; - private final List createdAssignedObjects; - - public JavaparserFileVisitor(){ - this.allCreatedObjects = new ArrayList<>(); - this.createdAssignedObjects = new ArrayList<>(); - } - - /** - * This method is responsible for the creation of the AST. - * - * @param file the Java source file - * @param leafNode the leaf node representing the Java source file - */ - public void createAST(File file, - LeafNode leafNode) { - try { - JavaparserLeafNode javaparserLeafNode = (JavaparserLeafNode) leafNode; - StaticJavaParser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_17); - CompilationUnit compilationUnit = StaticJavaParser.parse(file); - List imports = compilationUnit.getImports() - .stream() - .map(Node::toString) - .map(imprt -> imprt.replaceFirst("^import ", "").trim()) - .map(imprt -> imprt.replaceAll(";$", "")).collect(Collectors.toList()); - javaparserLeafNode.setImports(imports); - - InheritanceVisitor inheritanceVisitor = new InheritanceVisitor(javaparserLeafNode); - inheritanceVisitor.visit(compilationUnit, null); - - VoidVisitor constructorVisitor = new ConstructorVisitor(javaparserLeafNode); - constructorVisitor.visit(compilationUnit, null); - - VoidVisitor fieldNameVisitor = new FieldVisitor(javaparserLeafNode); - fieldNameVisitor.visit(compilationUnit, null); - - VoidVisitor> variableVisitor = new VariableVisitor(javaparserLeafNode); - variableVisitor.visit(compilationUnit, this.createdAssignedObjects); - - VoidVisitor methodNameVisitor = new MethodVisitor(javaparserLeafNode); - methodNameVisitor.visit(compilationUnit, null); - - VoidVisitor> objectCreationVisitor = new ObjectCreationVisitor(); - objectCreationVisitor.visit(compilationUnit, this.allCreatedObjects); - populateCreatedObjects(javaparserLeafNode); - - VoidVisitor enumVisitor = new EnumVisitor(javaparserLeafNode, - inheritanceVisitor.isClassOrInterface()); - enumVisitor.visit(compilationUnit, null); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - private static class InheritanceVisitor extends VoidVisitorAdapter { - private final JavaparserLeafNode leafNode; - private boolean isClassOrInterface = false; - - public InheritanceVisitor(JavaparserLeafNode leafNode) { - this.leafNode = leafNode; - } - - @Override - public void visit(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, Void arg) { - super.visit(classOrInterfaceDeclaration, arg); - this.leafNode.setNodeName(classOrInterfaceDeclaration.getNameAsString()); - this.isClassOrInterface = true; - - if (classOrInterfaceDeclaration.isInterface()) { - this.leafNode.setNodeType(NodeType.INTERFACE); - return; - } - - this.leafNode.setNodeType(NodeType.CLASS); - classOrInterfaceDeclaration.getExtendedTypes() - .forEach(classOrInterfaceType -> this.leafNode.setBaseClass(classOrInterfaceType.getNameAsString())); - - classOrInterfaceDeclaration.getImplementedTypes() - .forEach(classOrInterfaceType -> this.leafNode.addImplementedInterface(classOrInterfaceType.getNameAsString())); - } - - public boolean isClassOrInterface() { - return this.isClassOrInterface; - } - } - - private static class ConstructorVisitor extends VoidVisitorAdapter { - private final JavaparserLeafNode leafNode; - - public ConstructorVisitor(JavaparserLeafNode leafNode) { - this.leafNode = leafNode; - } - - @Override - public void visit(ConstructorDeclaration constructorDeclaration, Void arg) { - super.visit(constructorDeclaration, arg); - ModifierType modifierType = ModifierType.PACKAGE_PRIVATE; - if (!constructorDeclaration.getModifiers().isEmpty()) { - modifierType = ModifierType.get(constructorDeclaration.getModifiers().get(0).toString()); - } - - Map parameters = new HashMap<>(); - constructorDeclaration.getParameters() - .forEach(parameter -> parameters.put(parameter.getNameAsString(), - getType(parameter.getTypeAsString()))); - this.leafNode.addMethod(constructorDeclaration.getNameAsString(), - "Constructor", - modifierType, - parameters); - } - } - - private static class FieldVisitor extends VoidVisitorAdapter { - private final JavaparserLeafNode leafNode; - - public FieldVisitor(JavaparserLeafNode leafNode) { - this.leafNode = leafNode; - } - - @Override - public void visit(FieldDeclaration fieldDeclaration, Void arg) { - super.visit(fieldDeclaration, arg); - fieldDeclaration.getVariables().forEach(variable -> { - ModifierType modifierType = ModifierType.PACKAGE_PRIVATE; - if (!fieldDeclaration.getModifiers().isEmpty()) { - modifierType = ModifierType.get(fieldDeclaration.getModifiers().get(0).toString()); - } - this.leafNode.addField(variable.getNameAsString(), - getType(variable.getTypeAsString()), - modifierType); - }); - } - } - - private static class VariableVisitor extends VoidVisitorAdapter> { - private final JavaparserLeafNode leafNode; - - public VariableVisitor(JavaparserLeafNode leafNode) { - this.leafNode = leafNode; - } - - @Override - public void visit(VariableDeclarationExpr variableDeclarationExpr, - List createdAssignedObjects) { - super.visit(variableDeclarationExpr, createdAssignedObjects); - Pattern pattern = Pattern.compile("[A-Za-z0-9]+ [A-Za-z0-9]+ = new ([A-Za-z0-9]+)\\([A-Za-z0-9]*[, A-Za-z0-9*]*\\)"); - Matcher matcher = pattern.matcher(variableDeclarationExpr.toString()); - if (!matcher.find()) { - return; - } - createdAssignedObjects.add(matcher.group(1)); - - variableDeclarationExpr.getVariables() - .forEach(variableDeclaration -> leafNode.addVariable(variableDeclaration.getNameAsString(), - getType(variableDeclaration.getTypeAsString()))); - } - } - - private static class MethodVisitor extends VoidVisitorAdapter { - private final JavaparserLeafNode leafNode; - - public MethodVisitor(JavaparserLeafNode leafNode) { - this.leafNode = leafNode; - } - - @Override - public void visit(MethodDeclaration methodDeclaration, Void arg) { - super.visit(methodDeclaration, arg); - ModifierType modifierType = ModifierType.PACKAGE_PRIVATE; - if (!methodDeclaration.getModifiers().isEmpty()) { - modifierType = ModifierType.get(methodDeclaration.getModifiers().get(0).toString()); - } - - Map parameters = new HashMap<>(); - methodDeclaration.getParameters() - .forEach(parameter -> parameters.put(parameter.getNameAsString(), - getType(parameter.getTypeAsString()))); - - this.leafNode.addMethod(methodDeclaration.getNameAsString(), - getType(methodDeclaration.getTypeAsString()), - modifierType, - parameters); - } - } - - private static class ObjectCreationVisitor extends VoidVisitorAdapter> { - - @Override - public void visit(ObjectCreationExpr objectCreationExpr, - List createdObjects) { - super.visit(objectCreationExpr, createdObjects); - createdObjects.add(getType(objectCreationExpr.asObjectCreationExpr().getType().asString())); - } - } - - private static class EnumVisitor extends VoidVisitorAdapter { - private final JavaparserLeafNode leafNode; - private final boolean isClassOrInterface; - - public EnumVisitor(JavaparserLeafNode leafNode, boolean isClassOrInterface) { - this.leafNode = leafNode; - this.isClassOrInterface = isClassOrInterface; - } - - @Override - public void visit(EnumDeclaration enumDeclaration, Void arg) { - super.visit(enumDeclaration, arg); - if (!enumDeclaration.isEnumDeclaration() || this.isClassOrInterface) { - return; - } - this.leafNode.setNodeName(enumDeclaration.getNameAsString()); - this.leafNode.setNodeType(NodeType.ENUM); - } - - } - - private void populateCreatedObjects(JavaparserLeafNode leafNode) { - List notAssignedCreatedObjects = getNotAssignedCreatedObjects(leafNode.getFieldsTypes(), this.allCreatedObjects); - notAssignedCreatedObjects = getNotAssignedCreatedObjects(leafNode.getVariablesTypes(), notAssignedCreatedObjects); - notAssignedCreatedObjects = getNotAssignedCreatedObjects(this.createdAssignedObjects, notAssignedCreatedObjects); - notAssignedCreatedObjects.forEach(leafNode::addCreatedObject); - } - - private List getNotAssignedCreatedObjects(List assignedObjects, - List createdObjects) { - List newList = new ArrayList<>(); - Collections.sort(createdObjects); - Collections.sort(assignedObjects); - - int i = 0; - int j = 0; - main: - while (i < createdObjects.size()) { - while (j < assignedObjects.size()) { - if (createdObjects.get(i).equals(assignedObjects.get(j))) { - j++; - }else { - newList.add(createdObjects.get(i)); - } - i++; - if (i == createdObjects.size()) { - break main; - } - } - newList.add(createdObjects.get(i)); - i++; - } - return newList; - } - - private static String getType(String type) { - return type.replaceAll("<", "[").replaceAll(">", "]"); - } - -} diff --git a/src/main/java/parser/javaparser/JavaparserLeafNode.java b/src/main/java/parser/javaparser/JavaparserLeafNode.java deleted file mode 100644 index 2a6011f..0000000 --- a/src/main/java/parser/javaparser/JavaparserLeafNode.java +++ /dev/null @@ -1,88 +0,0 @@ -package parser.javaparser; - -import parser.tree.LeafNode; -import parser.tree.NodeType; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class JavaparserLeafNode extends LeafNode { - - private final List implementedInterfaces; - private final Map variables; - private final List createdObjects; - private String nodeName; - private String baseClass; - private NodeType nodeType; - private List imports; - - public JavaparserLeafNode(Path path) { - super(path); - this.implementedInterfaces = new ArrayList<>(); - this.variables = new HashMap<>(); - this.createdObjects = new ArrayList<>(); - this.baseClass = ""; - this.nodeName = ""; - } - - public void addVariable(String variableName, String variableType) { - this.variables.put(variableName, variableType); - } - - public void setNodeType(NodeType nodeType) { - this.nodeType = nodeType; - } - - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - - public void setBaseClass(String baseClass) { - this.baseClass = baseClass; - } - - public void addImplementedInterface(String interfaceName) { - this.implementedInterfaces.add(interfaceName); - } - - public void addCreatedObject(String createdObject) { - this.createdObjects.add(createdObject); - } - - public void setImports(List imports) { - this.imports = imports; - } - - public List getVariablesTypes() { - return new ArrayList<>(this.variables.values()); - } - - public String getBaseClass() { - return this.baseClass; - } - - public List getCreatedObjects() { - return this.createdObjects; - } - - public List getImplementedInterfaces() { - return this.implementedInterfaces; - } - - public List getImports() { - return this.imports; - } - - @Override - public String getName() { - return this.nodeName; - } - - @Override - public NodeType getType() { - return this.nodeType; - } -} \ No newline at end of file diff --git a/src/main/java/parser/javaparser/JavaparserProjectParser.java b/src/main/java/parser/javaparser/JavaparserProjectParser.java deleted file mode 100644 index 84fc4ae..0000000 --- a/src/main/java/parser/javaparser/JavaparserProjectParser.java +++ /dev/null @@ -1,75 +0,0 @@ -package parser.javaparser; - -import parser.factory.Parser; -import parser.tree.LeafNode; -import parser.tree.PackageNode; -import parser.tree.RelationshipIdentifier; - -import java.io.File; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -public class JavaparserProjectParser implements Parser { - - private final Map packageNodes; - - public JavaparserProjectParser() { - this.packageNodes = new HashMap<>(); - } - - @Override - public Map parseSourcePackage(Path sourcePackagePath) { - PackageNode rootPackageNode = new PackageNode(sourcePackagePath); - this.packageNodes.put(rootPackageNode.getPackageNodesPath(), rootPackageNode); - try { - parseFolder(rootPackageNode); - RelationshipIdentifier relationshipIdentifier = new JavaparserRelationshipIdentifier(this.packageNodes); - relationshipIdentifier.createLeafNodesRelationships(); - } catch (Exception e) { - e.printStackTrace(); - } - return this.packageNodes; - } - - private void parseFolder(PackageNode currentNode) { - try (DirectoryStream filesStream = Files.newDirectoryStream(currentNode.getPackageNodesPath())) { - for (Path path: filesStream) { - if (Files.isDirectory(path)) { - createPackageSubNode(currentNode, new PackageNode(getSubNodesPath(currentNode, path.toFile()))); - } else if (isExtensionJava(path.normalize().toString())) { - createLeafNode(currentNode, new JavaparserLeafNode(path), path.toFile()); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void createPackageSubNode(PackageNode currentNode, PackageNode subNode){ - subNode.setParentNode(currentNode); - this.packageNodes.put(subNode.getPackageNodesPath(), subNode); - currentNode.addSubNode(subNode); - parseFolder(subNode); - } - - private void createLeafNode(PackageNode currentNode, LeafNode leafNode, File file) { - leafNode.setParentNode(currentNode); - currentNode.setValid(); - JavaparserFileVisitor fileVisitor = new JavaparserFileVisitor(); - fileVisitor.createAST(file, leafNode); - currentNode.addLeafNode(leafNode); - } - - private boolean isExtensionJava(String filePath) { - return filePath.toLowerCase().endsWith(".java"); - } - - private Path getSubNodesPath(PackageNode currentPackage, File file) { - return Paths.get(currentPackage.getPackageNodesPath().normalize() + "/" + file.getName()); - } - -} diff --git a/src/main/java/parser/javaparser/JavaparserRelationshipIdentifier.java b/src/main/java/parser/javaparser/JavaparserRelationshipIdentifier.java deleted file mode 100644 index 488941c..0000000 --- a/src/main/java/parser/javaparser/JavaparserRelationshipIdentifier.java +++ /dev/null @@ -1,98 +0,0 @@ -package parser.javaparser; - -import parser.tree.PackageNode; -import parser.tree.RelationshipIdentifier; -import parser.tree.RelationshipType; - -import java.nio.file.Path; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class JavaparserRelationshipIdentifier extends RelationshipIdentifier { - - public JavaparserRelationshipIdentifier(Map packageNodes) { - super(packageNodes); - } - - @Override - protected void checkRelationship(int i, int j) { - List imports = ((JavaparserLeafNode) this.allLeafNodes.get(i)).getImports(); - Optional optional = imports - .stream() - .filter(imprt -> - (this.allLeafNodes.get(j).getParentNode().getName() + "." + this.allLeafNodes.get(j).getName()).endsWith(imprt) || - (this.allLeafNodes.get(j).getParentNode().getName() + "." + "*").endsWith(imprt)) - .findFirst(); - - if (optional.isEmpty() && !isSubNode(i, j)) { - return; - } - if (isDependency(i, j)) { - createRelationship(i, j, RelationshipType.DEPENDENCY); - } - if (isAggregation(i, j)) { - createRelationship(i, j, RelationshipType.AGGREGATION); - }else if (isAssociation(i, j)) { - createRelationship(i, j, RelationshipType.ASSOCIATION); - } - - if (isExtension(i, j)) { - createRelationship(i, j, RelationshipType.EXTENSION); - } - if (isImplementation(i, j)) { - createRelationship(i, j, RelationshipType.IMPLEMENTATION); - } - } - - private boolean isSubNode(int i, int j) { - PackageNode node = this.allLeafNodes.get(j).getParentNode(); - while (true) { - if (node.equals(this.allLeafNodes.get(i).getParentNode())) { - return true; - } - - if (node.getPackageNodesPath().toString().isEmpty()) { - return false; - } - node = node.getParentNode(); - } - } - - @Override - protected boolean isDependency(int i, int j) { - return - doesRelationshipExist( - this.allLeafNodes.get(i).getMethodParameterTypes(), this.allLeafNodes.get(j).getName())|| - doesRelationshipExist(this.allLeafNodes.get(i).getMethodsReturnTypes(), this.allLeafNodes.get(j).getName()) || - doesRelationshipExist(getLeafNode(i).getVariablesTypes(), this.allLeafNodes.get(j).getName()) || - doesRelationshipExist(getLeafNode(i).getCreatedObjects(), this.allLeafNodes.get(j).getName() - ); - } - - @Override - protected boolean isExtension(int i, int j) { - if (getLeafNode(i).getBaseClass().isEmpty()) { - return false; - } - return getLeafNode(i).getBaseClass().equals(this.allLeafNodes.get(j).getName()); - } - - @Override - protected boolean isImplementation(int i, int j) { - if (getLeafNode(i).getImplementedInterfaces().isEmpty()) { - return false; - } - - for (String implementedInterface: getLeafNode(i).getImplementedInterfaces()) { - if (implementedInterface.equals(this.allLeafNodes.get(j).getName())) { - return true; - } - } - return false; - } - - private JavaparserLeafNode getLeafNode(int i) { - return (JavaparserLeafNode) this.allLeafNodes.get(i); - } -} diff --git a/src/main/java/parser/jdt/JDTFileVisitor.java b/src/main/java/parser/jdt/JDTFileVisitor.java deleted file mode 100644 index 5127a89..0000000 --- a/src/main/java/parser/jdt/JDTFileVisitor.java +++ /dev/null @@ -1,176 +0,0 @@ -package parser.jdt; - -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.VariableDeclaration; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.text.edits.MalformedTreeException; -import parser.tree.LeafNode; -import parser.tree.ModifierType; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.eclipse.jdt.core.dom.ASTNode.METHOD_DECLARATION; - -/** - * This class is responsible for the creation of the AST of a Java source file using JDT. - * The ASTNode API parses the files methods parameters, return types and field declarations. - * - */ -public class JDTFileVisitor { - - private CompilationUnit unit; - private String[] sourceFile; - - /** - * This method is responsible for the creation of the AST. - * - * @param file the Java source file - * @param leafNode the leaf node representing the Java source file - */ - public void createAST(File file, LeafNode leafNode) { - try { - ASTParser parser = ASTParser.newParser(AST.JLS17); - this.sourceFile = ReadFileToCharArray(file.getAbsolutePath()).split("/n"); - parser.setSource(ReadFileToCharArray(file.getAbsolutePath()).toCharArray()); - this.unit = (CompilationUnit)parser.createAST(null); - JDTLeafNode jdtLeafNode = (JDTLeafNode) leafNode; - processJavaFile(jdtLeafNode); - } catch (IOException | MalformedTreeException e) { - e.printStackTrace(); - } - } - - private void processJavaFile(JDTLeafNode jdtLeafNode) throws MalformedTreeException { - // to iterate through methods - List types = new ArrayList<>(); - for (Object o: unit.types()) { - types.add((AbstractTypeDeclaration)(o)); - } - if (types.isEmpty()) { - jdtLeafNode.setInheritanceLine(new String[]{"enum"}); - } - for (AbstractTypeDeclaration type : types) { - if (type.getNodeType() == ASTNode.TYPE_DECLARATION) { - jdtLeafNode.setInheritanceLine(convertInheritanceLine(type)); - List bodies = new ArrayList<>(); - for (Object o: type.bodyDeclarations()) { - bodies.add((BodyDeclaration)(o)); - } - for (BodyDeclaration body : bodies) { - if (isField(body)) { - String fieldName = ""; - FieldDeclaration field = (FieldDeclaration)body; - List fragments = new ArrayList<>(); - for (Object o: field.fragments()) { - fragments.add((VariableDeclarationFragment)(o)); - } - for(VariableDeclarationFragment fragment: fragments) { - fieldName = fragment.getName().toString(); - Map map = new HashMap<>(); - for (Object ob: fragment.properties().keySet()) { - map.put(ob, map.get(ob)); - } - } - int fieldModifiers = field.getModifiers(); - jdtLeafNode.addField(fieldName, field.getType().toString().replaceAll("<", "[").replaceAll(">", "]"), getVisibility(fieldModifiers)); - } - if (isMethod(body)) { - MethodDeclaration method = (MethodDeclaration)body; - String methodName = method.getName().getFullyQualifiedName(); - Type returnType = method.getReturnType2(); - - String returnTypeName; - if (returnType==null) returnTypeName = "Constructor"; - else returnTypeName = returnType.toString(); - - Map parameters = new HashMap<>(); - - for (Object parameter : method.parameters()) { - VariableDeclaration variableDeclaration = (VariableDeclaration) parameter; - String variableType = variableDeclaration. - getStructuralProperty(SingleVariableDeclaration.TYPE_PROPERTY).toString() + "[]".repeat(Math.max(0, variableDeclaration.getExtraDimensions())); - - parameters.put(variableDeclaration.getName().getIdentifier(), - variableType.replaceAll("<", "[").replaceAll(">", "]")); - } - - int methodModifiers = method.getModifiers(); - jdtLeafNode.addMethod(methodName, returnTypeName.replaceAll("<", "[").replaceAll(">", "]"), getVisibility(methodModifiers), parameters); - } - } - } - } - }//end processJavaFile - - private String[] convertInheritanceLine(AbstractTypeDeclaration type) { - String[] inheritanceLine = Arrays.copyOfRange(getInheritanceLine(type), 1, getInheritanceLine(type).length); - for (int i = 0; i < inheritanceLine.length; i++) { - inheritanceLine[i] = inheritanceLine[i].trim(); - inheritanceLine[i] = inheritanceLine[i].replace(",", ""); - inheritanceLine[i] = inheritanceLine[i].replace("{", ""); - } - List list = new ArrayList<>(Arrays.asList(inheritanceLine)); - list.removeAll(Arrays.asList("", null)); - return list.toArray(new String[0]); - } - - private String[] getInheritanceLine(AbstractTypeDeclaration type) { - return sourceFile[unit.getLineNumber(type.getName().getStartPosition())-1].split(" "); - } - - private boolean isMethod(BodyDeclaration body) { - return body.getNodeType() == METHOD_DECLARATION; - } - - private boolean isField(BodyDeclaration body) { - return body.getNodeType() == ASTNode.FIELD_DECLARATION; - } - - private String ReadFileToCharArray(String filePath) throws IOException { - StringBuilder fileData = new StringBuilder(1000); - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - - char[] buf = new char[10]; - int numRead; - while ((numRead = reader.read(buf)) != -1) { - String readData = String.valueOf(buf, 0, numRead); - fileData.append(readData); - buf = new char[1024]; - } - - reader.close(); - - return fileData.toString(); - }//end ReadFileToCharArray - - - private static ModifierType getVisibility(int modifiers) { - if(Modifier.isPublic(modifiers)) { - return ModifierType.PUBLIC; - } else if (Modifier.isProtected(modifiers)) { - return ModifierType.PROTECTED; - } else if (Modifier.isPrivate(modifiers)) { - return ModifierType.PRIVATE; - } else { - return ModifierType.PACKAGE_PRIVATE; - } - } -} diff --git a/src/main/java/parser/jdt/JDTLeafNode.java b/src/main/java/parser/jdt/JDTLeafNode.java deleted file mode 100644 index bded0d5..0000000 --- a/src/main/java/parser/jdt/JDTLeafNode.java +++ /dev/null @@ -1,43 +0,0 @@ -package parser.jdt; - -import parser.tree.LeafNode; -import parser.tree.NodeType; - -import java.nio.file.Path; - -public class JDTLeafNode extends LeafNode { - - private String[] inheritanceLine; - - public JDTLeafNode(Path path) { - super(path); - } - - /** - * This method is responsible for setting the nodes line that contains the declaration - * of the source file. - * - * @param inheritanceLine the Java source file's line holding the information regarding its inheritance - */ - public void setInheritanceLine(String[] inheritanceLine) { - this.inheritanceLine = inheritanceLine; - } - - public String[] getInheritanceLine() { - return inheritanceLine; - } - - public String getName() { - return path.normalize().toString().substring(path.normalize().toString().lastIndexOf("/") + 1, path.normalize().toString().lastIndexOf(".")); - } - - public NodeType getType() { - if (inheritanceLine[0].equals("enum")) { - return NodeType.ENUM; - }else if (inheritanceLine[0].equals("interface")) { - return NodeType.INTERFACE; - }else { - return NodeType.CLASS; - } - } -} diff --git a/src/main/java/parser/jdt/JDTProjectParser.java b/src/main/java/parser/jdt/JDTProjectParser.java deleted file mode 100644 index 3660c75..0000000 --- a/src/main/java/parser/jdt/JDTProjectParser.java +++ /dev/null @@ -1,80 +0,0 @@ -package parser.jdt; - -import parser.factory.Parser; -import parser.tree.LeafNode; -import parser.tree.PackageNode; -import parser.tree.RelationshipIdentifier; - -import java.io.File; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - - -/** - * This class is responsible for the parsing of a Java project. While parsing the project - * it creates a tree where nodes are the packages and leafs are the Java source files. - * In order to create the tree it uses the ASTNode API from the JDT library. - * - */ -public class JDTProjectParser implements Parser { - private final Map packageNodes; - - public JDTProjectParser() { - packageNodes = new HashMap<>(); - } - - public Map parseSourcePackage(Path sourcePackagePath) { - PackageNode rootPackageNode = new PackageNode(sourcePackagePath); - packageNodes.put(rootPackageNode.getPackageNodesPath(), rootPackageNode); - try { - parseFolder(rootPackageNode); - RelationshipIdentifier relationshipIdentifier = new JDTRelationshipIdentifier(packageNodes); - relationshipIdentifier.createLeafNodesRelationships(); - } catch (Exception e) { - e.printStackTrace(); - } - return packageNodes; - } - - private void parseFolder(PackageNode currentNode) { - try (DirectoryStream filesStream = Files.newDirectoryStream(currentNode.getPackageNodesPath())) { - for (Path path: filesStream) { - if (Files.isDirectory(path)) { - createPackageSubNode(currentNode, new PackageNode(getSubNodesPath(currentNode, path.toFile()))); - }else if (isExtensionJava(path.normalize().toString())) { - createLeafNode(currentNode, new JDTLeafNode(path), path.toFile()); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void createPackageSubNode(PackageNode currentNode, PackageNode subNode){ - subNode.setParentNode(currentNode); - packageNodes.put(subNode.getPackageNodesPath(), subNode); - currentNode.addSubNode(subNode); - parseFolder(subNode); - } - - private void createLeafNode(PackageNode currentNode, LeafNode leafNode, File file) { - leafNode.setParentNode(currentNode); - currentNode.setValid(); - JDTFileVisitor fileVisitor = new JDTFileVisitor(); - fileVisitor.createAST(file, leafNode); - currentNode.addLeafNode(leafNode); - } - - private boolean isExtensionJava(String filePath) { - return filePath.toLowerCase().endsWith(".java"); - } - - private Path getSubNodesPath(PackageNode currentPackage, File file) { - return Paths.get(currentPackage.getPackageNodesPath().normalize() + "/" + file.getName()); - } - -} diff --git a/src/main/java/parser/jdt/JDTRelationshipIdentifier.java b/src/main/java/parser/jdt/JDTRelationshipIdentifier.java deleted file mode 100644 index 8dad6d2..0000000 --- a/src/main/java/parser/jdt/JDTRelationshipIdentifier.java +++ /dev/null @@ -1,90 +0,0 @@ -package parser.jdt; - -import parser.tree.PackageNode; -import parser.tree.RelationshipIdentifier; -import parser.tree.RelationshipType; - -import java.nio.file.Path; -import java.util.Map; - -public class JDTRelationshipIdentifier extends RelationshipIdentifier { - - public static final int DECLARATION_LINE_STANDARD_SIZE = 2; - public static final int INHERITANCE_TYPE = 2; - public static final int SUPERCLASS_NAME = 3; - public static final int MULTIPLE_IMPLEMENTATIONS = 5; - public static final int INHERITANCE_TYPE_WITH_MULTIPLE_IMPLEMENTATIONS = 4; - - public JDTRelationshipIdentifier(Map packageNodes) { - super(packageNodes); - } - - @Override - protected void checkRelationship(int i, int j) { - if (isDependency(i, j)) { - createRelationship(i, j, RelationshipType.DEPENDENCY); - } - if (isAggregation(i, j)) { - createRelationship(i, j, RelationshipType.AGGREGATION); - }else if (isAssociation(i, j)) { - createRelationship(i, j, RelationshipType.ASSOCIATION); - } - if (isInheritance(i)) { - if (isExtension(i, j)) { - createRelationship(i, j, RelationshipType.EXTENSION); - } - if (isImplementation(i, j)) { - createRelationship(i, j, RelationshipType.IMPLEMENTATION); - } - } - } - - @Override - protected boolean isDependency(int i, int j) { - return doesRelationshipExist(allLeafNodes.get(i).getMethodParameterTypes(), allLeafNodes.get(j).getName()) - || doesRelationshipExist(allLeafNodes.get(i).getMethodsReturnTypes(), allLeafNodes.get(j).getName()); - } - - @Override - protected boolean isExtension(int i, int j) { - if (getNodesInheritanceLine(i)[INHERITANCE_TYPE].equals("extends")) { - for (int k = 0; k < allLeafNodes.size(); k++) { - if (getNodesInheritanceLine(i)[SUPERCLASS_NAME].equals(allLeafNodes.get(j).getName())) { - return true; - } - } - } - return false; - } - - @Override - protected boolean isImplementation(int i, int j) { - if (getNodesInheritanceLine(i)[INHERITANCE_TYPE].equals("implements")) { - for (int l = 3; l < getNodesInheritanceLine(i).length; l++) { - if (getNodesInheritanceLine(i)[l].equals(allLeafNodes.get(j).getName())) { - return true; - } - } - }else if (getNodesInheritanceLine(i).length > MULTIPLE_IMPLEMENTATIONS - && getNodesInheritanceLine(i)[INHERITANCE_TYPE_WITH_MULTIPLE_IMPLEMENTATIONS].equals("implements")) { - for (int l = 5; l < getNodesInheritanceLine(i).length; l++) { - if (getNodesInheritanceLine(i)[l].equals(allLeafNodes.get(j).getName())) { - return true; - } - } - } - return false; - } - - private boolean isInheritance(int i) { - return getNodesInheritanceLine(i).length > DECLARATION_LINE_STANDARD_SIZE; - } - - private String[] getNodesInheritanceLine(int i) { - return getLeafNode(i).getInheritanceLine(); - } - - private JDTLeafNode getLeafNode(int i) { - return (JDTLeafNode) allLeafNodes.get(i); - } -} diff --git a/src/main/java/parser/tree/LeafNode.java b/src/main/java/parser/tree/LeafNode.java index 1caeb46..b5247af 100644 --- a/src/main/java/parser/tree/LeafNode.java +++ b/src/main/java/parser/tree/LeafNode.java @@ -1,119 +1,43 @@ package parser.tree; -import org.javatuples.Triplet; - import java.nio.file.Path; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -/** - * This class is responsible for the implementation of a leaf node in the tree. - * Each node has a parent node(the parent package), the path of the source file, - * the branches that start from that node and also the field/method/method parameter types. - */ -public abstract class LeafNode { - private final Map, Map> methods; - private final List> leafNodeRelationships; - private final List> fields; - protected final Path path; - private PackageNode parentNode; - private int methodId; - - public LeafNode(Path path) { - this.path = path; - this.leafNodeRelationships = new ArrayList<>(); - this.fields = new ArrayList<>(); - this.methods = new HashMap<>(); - this.methodId = 0; - } - - /** - * This method is responsible for adding the nodes' method's name, return type, modifier type & its parameters - * that include the name and the type. - * - * @param name the method's name - * @param returnType the method's return type - * @param modifierType the method's modifier type - * @param parameters the method's parameters - */ - public void addMethod(String name, - String returnType, - ModifierType modifierType, - Map parameters) { - this.methods.put( - new Triplet<>( - name + "$" + this.methodId, - returnType, - modifierType - ), - parameters); - this.methodId++; - } +public record LeafNode(Path path, + String nodeName, + NodeType nodeType, + String baseClass, + PackageNode parentNode, + List implementedInterfaces, + List methods, + List fields, + Map variables, + List imports, + List records, + List innerClasses, + List innerEnums, + List createdObjects) { - /** - * This method is responsible for adding the nodes' field's name, type & modifier type. - * @param fieldName the field's name - * @param fieldType the field's type - * @param modifierType the field's modifier type - */ - public void addField(String fieldName, - String fieldType, - ModifierType modifierType) { - this.fields.add(new Triplet<>( - fieldName, - fieldType, - modifierType)); - } - public void setParentNode(PackageNode p) { - this.parentNode = p; - } - - public void addLeafNodeRelationship(Relationship relationship) { - this.leafNodeRelationships.add(relationship); - } - - public List> getLeafNodeRelationships() { - return this.leafNodeRelationships; - } - - public Path getLeafNodesPath() { - return this.path; - } - - public PackageNode getParentNode() { - return this.parentNode; - } - - public Map, Map> getMethods(){ - return this.methods; - } - - public List getMethodsReturnTypes() { - return this.methods.keySet().stream().map(Triplet::getValue1).collect(Collectors.toList()); + public List getMethodReturnTypes() { + return methods.stream().map(method -> method.returnType).collect(Collectors.toCollection(ArrayList::new)); } public List getMethodParameterTypes() { - List parameterTypes = new ArrayList<>(); - this.methods.forEach( - (method, parameters) -> parameterTypes.addAll(new ArrayList<>(parameters.values())) - ); - return parameterTypes; + return methods.stream().flatMap(method -> method.parameters().values().stream()).collect(Collectors.toCollection(ArrayList::new)); } - public List> getFields() { - return this.fields; - } - - public List getFieldsTypes(){ - return this.fields.stream().map(Triplet::getValue1).collect(Collectors.toList()); - } - public abstract NodeType getType(); + public record Method(String methodName, + String returnType, + ModifierType modifierType, + Map parameters) {} - public abstract String getName(); + public record Field(String fieldNames, + String fieldType, + ModifierType modifierType) {} -} +} \ No newline at end of file diff --git a/src/main/java/parser/tree/LeafNodeBuilder.java b/src/main/java/parser/tree/LeafNodeBuilder.java new file mode 100644 index 0000000..2566b5f --- /dev/null +++ b/src/main/java/parser/tree/LeafNodeBuilder.java @@ -0,0 +1,119 @@ +package parser.tree; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class LeafNodeBuilder { + private final Map variables; + private final List methods; + private final List fields; + private final List imports; + private final List implementedInterfaces; + private final List createdObjects; + private final List innerClasses; + private final List innerEnums; + private final List records; + private final PackageNode parentNode; + private final Path path; + private String nodeName; + private String baseClass; + private NodeType nodeType; + + public LeafNodeBuilder(PackageNode parentNode, Path path) { + this.parentNode = parentNode; + this.path = path; + this.implementedInterfaces = new ArrayList<>(); + this.createdObjects = new ArrayList<>(); + this.innerClasses = new ArrayList<>(); + this.innerEnums = new ArrayList<>(); + this.records = new ArrayList<>(); + this.variables = new HashMap<>(); + this.imports = new ArrayList<>(); + this.methods = new ArrayList<>(); + this.fields = new ArrayList<>(); + this.nodeType = null; + this.baseClass = ""; + this.nodeName = ""; + } + + public LeafNodeBuilder setVariables(Map variables) { + this.variables.putAll(variables); + return this; + } + + public LeafNodeBuilder setInnerClasses(List innerClasses) { + this.innerClasses.addAll(innerClasses); + return this; + } + + public LeafNodeBuilder setNodeType(NodeType nodeType) { + this.nodeType = nodeType; + return this; + } + + public LeafNodeBuilder setNodeName(String nodeName) { + this.nodeName = nodeName; + return this; + } + + public LeafNodeBuilder setBaseClass(String baseClass) { + this.baseClass = baseClass; + return this; + } + + public LeafNodeBuilder setImplementedInterface(List interfaces) { + this.implementedInterfaces.addAll(interfaces); + return this; + } + + public LeafNodeBuilder setCreatedObjects(List createdObjects) { + this.createdObjects.addAll(createdObjects); + return this; + } + + public LeafNodeBuilder setInnerEnums(List enums) { + this.innerEnums.addAll(enums); + return this; + } + + public LeafNodeBuilder setRecords(List records) { + this.records.addAll(records); + return this; + } + + public LeafNodeBuilder setImports(List imprts) { + this.imports.addAll(imprts); + return this; + } + + public LeafNodeBuilder setMethods(List methods) { + this.methods.addAll(methods); + return this; + } + + public LeafNodeBuilder setFields(List fields) { + this.fields.addAll(fields); + return this; + } + + public LeafNode build() { + return new LeafNode(path, + nodeName, + nodeType, + baseClass, + parentNode, + implementedInterfaces, + methods, + fields, + variables, + imports, + records, + innerClasses, + innerEnums, + createdObjects); + } + +} diff --git a/src/main/java/parser/tree/ModifierType.java b/src/main/java/parser/tree/ModifierType.java index 2de7dcd..bb72227 100644 --- a/src/main/java/parser/tree/ModifierType.java +++ b/src/main/java/parser/tree/ModifierType.java @@ -24,7 +24,9 @@ public static ModifierType get(String modifierType) { return MODIFIER_TYPE.get(modifierType.toLowerCase().trim()); } + @Override public String toString() { return super.toString().toLowerCase(); } + } diff --git a/src/main/java/parser/tree/NodeType.java b/src/main/java/parser/tree/NodeType.java index 3718046..cd420a9 100644 --- a/src/main/java/parser/tree/NodeType.java +++ b/src/main/java/parser/tree/NodeType.java @@ -6,6 +6,7 @@ public enum NodeType { ENUM, PACKAGE; + @Override public String toString() { return super.toString().toLowerCase(); } diff --git a/src/main/java/parser/tree/PackageNode.java b/src/main/java/parser/tree/PackageNode.java index 4da4cbc..8e6abab 100644 --- a/src/main/java/parser/tree/PackageNode.java +++ b/src/main/java/parser/tree/PackageNode.java @@ -1,98 +1,95 @@ package parser.tree; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; +import java.util.stream.Stream; /** * This class is responsible for the implementation of a package node in the tree. * Each has node has a parent node(the parent package), the path of the package folder, - * the nodes children(the sub packages), the nodes leafs(the Java source files inside the + * the nodes children(the sub packages), the nodes leaves(the Java source files inside the * current package), a flag to identify if a package is empty or not. */ public class PackageNode { - private final Map subNodes; - private final Map leafNodes; - private final Path path; - private final List> packageNodeRelationships; - private PackageNode parentNode; - private boolean isValid; + private final Map subNodes; + private final Map leafNodes; + private final Path path; + private final PackageNode parentNode; + private final boolean isValid; - public PackageNode(Path path) { - this.packageNodeRelationships = new ArrayList<>(); - this.subNodes = new HashMap<>(); - this.leafNodes = new HashMap<>(); - this.path = path; - this.isValid = false; - } - public void addLeafNode(LeafNode leafNode) { - this.leafNodes.put(leafNode.getName(), leafNode); + public PackageNode(Path path) { + this.path = path; + parentNode = new PackageNode(null, Paths.get("")); + subNodes = new HashMap<>(); + leafNodes = new HashMap<>(); + isValid = isValid(path); } - public void addSubNode(PackageNode packageNode) { - this.subNodes.put(packageNode.getPackageNodesPath(), packageNode); + public PackageNode(PackageNode parentNode, Path path) { + this.parentNode = parentNode; + subNodes = new HashMap<>(); + leafNodes = new HashMap<>(); + this.path = path; + isValid = isValid(path); } - public void setValid() { - this.isValid = true; - } - public void setParentNode(PackageNode p) { - this.parentNode = p; + private static boolean isValid(Path path) { + boolean v; + try (Stream filesStream = Files.list(path)) { + v = filesStream.anyMatch(filePath -> filePath.normalize().toString().toLowerCase().endsWith(".java")); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + return v; } - public void addPackageNodeRelationship(Relationship relationship) { - this.packageNodeRelationships.add(relationship); + private static Path getPath(PackageNode parentNode, Path path) { + return Paths.get(String.format("%s/%s", + parentNode.getPath().normalize(), + path.toFile().getName())); } public boolean isValid() { - return this.isValid; + return isValid; } - public List> getPackageNodeRelationships() { - return this.packageNodeRelationships; - } - - public Path getPackageNodesPath() { - return this.path; + public Path getPath() { + return path; } public PackageNode getParentNode() { - if (this.parentNode != null) { - return this.parentNode; - }else { - return new PackageNode(Paths.get("")); - } + return parentNode; } public Map getSubNodes() { - return this.subNodes; + return subNodes; } public Map getLeafNodes() { - return this.leafNodes; + return leafNodes; } - public String getName() { - if (doesParentNodeExist()) { - return String.join(".", getParentNodesName(), this.path.getFileName().toString()); + public String getNodeName() { + if (!doesParentNodeExist()) { + return path.getFileName().toString(); } - return this.path.getFileName().toString(); - } + return String.join(".", + getParentNode().getNodeName(), + path.getFileName().toString()); + } private boolean doesParentNodeExist() { - return !getParentNode().getPackageNodesPath().normalize().toString().isEmpty(); - } - - private String getParentNodesName() { - return getParentNode().getName(); + return getParentNode() != null && !getParentNode().getPath().normalize().toString().isEmpty(); } - public NodeType getType() { + public NodeType getNodeType() { return NodeType.PACKAGE; } diff --git a/src/main/java/parser/tree/Relationship.java b/src/main/java/parser/tree/Relationship.java index c23f866..c15d0d1 100644 --- a/src/main/java/parser/tree/Relationship.java +++ b/src/main/java/parser/tree/Relationship.java @@ -2,4 +2,4 @@ public record Relationship(T startingNode, T endingNode, - RelationshipType relationshipType) { } + RelationshipType relationshipType) {} diff --git a/src/main/java/parser/tree/RelationshipIdentifier.java b/src/main/java/parser/tree/RelationshipIdentifier.java deleted file mode 100644 index 0b51f0a..0000000 --- a/src/main/java/parser/tree/RelationshipIdentifier.java +++ /dev/null @@ -1,131 +0,0 @@ -package parser.tree; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class is responsible for the creation of the branches between the Java - * source files. The branches have a type, e.g., inheritance, implementation. - * The branches are also directed with a starting and an ending node. - */ -public abstract class RelationshipIdentifier { - private final Map packageNodes; - protected final List allLeafNodes; - private int relationshipsCreated; - - /** - * This method is responsible for retrieving the leaf nodes that have been created - * and then creating the branches between them. - * - * @param packageNodes a collection with the package nodes created by the parser - */ - public RelationshipIdentifier(Map packageNodes) { - this.packageNodes = packageNodes; - this.allLeafNodes = new ArrayList<>(); - this.relationshipsCreated = 0; - populateLeafNodes(); - } - - public int createLeafNodesRelationships() { - for (int i = 0; i < allLeafNodes.size(); i++) { - for (int j = i+1; j < allLeafNodes.size(); j++) { - checkRelationship(i, j); - checkRelationship(j, i); - } - } - return relationshipsCreated; - } - - private void populateLeafNodes() { - for (PackageNode p: this.packageNodes.values()) { - this.allLeafNodes.addAll(p.getLeafNodes().values()); - } - } - - protected boolean isAssociation(int i, int j) { - return doesRelationshipExist(this.allLeafNodes.get(i).getFieldsTypes(), - this.allLeafNodes.get(j).getName()); - } - - protected boolean isAggregation(int i, int j) { - return isRelationshipAggregation(this.allLeafNodes.get(i).getFieldsTypes(), - this.allLeafNodes.get(j).getName()); - } - - protected boolean doesRelationshipExist(List leafNodesTypes, - String leafNodesName) { - for (String leafNodesType : leafNodesTypes) { - if (doesFieldBelongToClass(leafNodesType, leafNodesName)) { - return true; - } - } - return false; - } - - private boolean isRelationshipAggregation(List leafNodesTypes, - String leafNodesName) { - for (String leafNodeType: leafNodesTypes) { - if (isFieldOfTypeCollection(leafNodeType, leafNodesName) && doesFieldBelongToClass(leafNodeType, leafNodesName)){ - return true; - } - } - return false; - } - - private boolean doesFieldBelongToClass(String leafNodesType, - String leafNodesName) { - for (String type: leafNodesType.replace("[", ",").replace("]", ",").split(",")) { - if (leafNodesName.equals(type)) { - return true; - } - } - return false; - } - - private boolean isFieldOfTypeCollection(String s, - String leafNodesName) { - return - ( - s.startsWith("List") || s.startsWith("ArrayList") || s.startsWith("Map") || s.startsWith("HashMap") || - s.contains(leafNodesName+"[") || s.startsWith("ArrayDeque") || s.startsWith("LinkedList") || s.startsWith("PriorityQueue") - ); - } - - protected void createRelationship(int i, - int j, - RelationshipType relationshipType) { - this.allLeafNodes.get(i).addLeafNodeRelationship(new Relationship<>(this.allLeafNodes.get(i), this.allLeafNodes.get(j), relationshipType)); - this.relationshipsCreated++; - for (Relationship r: this.allLeafNodes.get(i).getParentNode().getPackageNodeRelationships()) { - if (doesPackageRelationshipAlreadyExist(j, r)) { - return; - } - } - if (isRelationshipBetweenTheSamePackages(i, j)) { - return; - } - this.allLeafNodes.get(i).getParentNode().addPackageNodeRelationship(new Relationship<>(this.allLeafNodes.get(i).getParentNode(), - this.allLeafNodes.get(j).getParentNode(), - RelationshipType.DEPENDENCY)); - this.relationshipsCreated++; - } - - private boolean doesPackageRelationshipAlreadyExist(int j, Relationship relationship) { - return relationship.endingNode().equals(allLeafNodes.get(j).getParentNode()); - } - - private boolean isRelationshipBetweenTheSamePackages(int i, int j) { - return this.allLeafNodes.get(i).getParentNode().equals(this.allLeafNodes.get(j).getParentNode()); - } - - protected abstract void checkRelationship(int i, int j); - - protected abstract boolean isDependency(int i, int j); - - protected abstract boolean isExtension(int i, int j); - - protected abstract boolean isImplementation(int i, int j); - -} diff --git a/src/main/java/parser/tree/RelationshipType.java b/src/main/java/parser/tree/RelationshipType.java index 59372af..fcc240b 100644 --- a/src/main/java/parser/tree/RelationshipType.java +++ b/src/main/java/parser/tree/RelationshipType.java @@ -7,6 +7,7 @@ public enum RelationshipType { EXTENSION, IMPLEMENTATION; + @Override public String toString() { return super.toString().toLowerCase(); } diff --git a/src/main/java/view/DiagramCreation.java b/src/main/java/view/DiagramCreation.java index 4e69b83..a8d1c21 100644 --- a/src/main/java/view/DiagramCreation.java +++ b/src/main/java/view/DiagramCreation.java @@ -85,7 +85,7 @@ public void exportPlantUMLText() { private List getSelectedFiles(String diagramType) { if (diagramType.equals("Package")) { return projectTreeView.getSelectedFiles(projectTreeView.getFolderFiles(), "package"); - }else{ + } else { return projectTreeView.getSelectedFiles(projectTreeView.getJavaSourceFiles(), "java"); } } diff --git a/src/main/java/view/DiagramVisualization.java b/src/main/java/view/DiagramVisualization.java index 222eda5..62fc597 100644 --- a/src/main/java/view/DiagramVisualization.java +++ b/src/main/java/view/DiagramVisualization.java @@ -11,8 +11,11 @@ import java.io.IOException; import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; public class DiagramVisualization { + private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private static final int EDGE_STARTING_NODE = 0; private static final int EDGE_ENDING_NODE = 1; @@ -72,8 +75,9 @@ public void loadLoadedDiagramVisualization(SmartGraphPanel graph graphView.init(); graphView.update(); } catch (IllegalStateException e) { - // Just continue. Handling here the expection in order not showing the error to the user. + // Just continue. Handling here the exception to not show the error to the user. // We do this, because this error doesn't affect the system. + logger.log(Level.WARNING, e.toString()); } } catch (IOException e) { e.printStackTrace(); diff --git a/src/main/java/view/DiagramVisualizationController.java b/src/main/java/view/DiagramVisualizationController.java index dcf9ef2..9345a30 100644 --- a/src/main/java/view/DiagramVisualizationController.java +++ b/src/main/java/view/DiagramVisualizationController.java @@ -78,7 +78,7 @@ public void exportDiagramAsImage() { ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", selectedDirectory); graphView.setScaleX(changeScaleX); graphView.setScaleY(changeScaleY); - }catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } @@ -105,7 +105,7 @@ public void closeDiagram() { Stage window = (Stage) menuBar.getScene().getWindow(); window.setScene(diagramCreationScene); window.show(); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -125,7 +125,8 @@ public void exportDiagramAsPlantUMLText() { public void aboutPage() { MenuUtility.aboutPage(menuBar); } public void showInfoWindow() { - PopupWindow.createPopupInfoWindow("Close the current diagram first!", "Error"); + PopupWindow.createPopupInfoWindow("Close the current diagram first!", + "Error"); } public void openProject() { diff --git a/src/main/java/view/FileAndDirectoryUtility.java b/src/main/java/view/FileAndDirectoryUtility.java index 7644072..0c36b78 100644 --- a/src/main/java/view/FileAndDirectoryUtility.java +++ b/src/main/java/view/FileAndDirectoryUtility.java @@ -41,7 +41,7 @@ public static File saveFile(String windowTitle, MenuBar menuBar, String fileType String directoryName = directoryPath[directoryPath.length - 1]; if (fileType.equals("PlantUML Files") || fileType.equals("PlantUML Text Files")) { fileChooser.setInitialFileName(String.format(directoryName + "_plantUML%s", availableExtensionTypes.get(fileType).substring(1))); - }else { + } else { fileChooser.setInitialFileName(String.format(directoryName + "_createdDiagram%s", availableExtensionTypes.get(fileType).substring(1))); } Stage window = (Stage) menuBar.getScene().getWindow(); diff --git a/src/main/java/view/ProjectTreeView.java b/src/main/java/view/ProjectTreeView.java index c5ccb21..d0a150a 100644 --- a/src/main/java/view/ProjectTreeView.java +++ b/src/main/java/view/ProjectTreeView.java @@ -82,7 +82,7 @@ public List getSelectedFiles(List files, String fileType) { } if (fileType.equals("java")) { selectedFiles.add(subtractFileExtension((String) c.getValue())); - }else { + } else { selectedFiles.add(((String) c.getValue())); } } diff --git a/src/test/java/manager/ClassDiagramManagerTest.java b/src/test/java/manager/ClassDiagramManagerTest.java index 9f0ac31..221352e 100644 --- a/src/test/java/manager/ClassDiagramManagerTest.java +++ b/src/test/java/manager/ClassDiagramManagerTest.java @@ -32,10 +32,24 @@ public class ClassDiagramManagerTest { @Test void createSourceProjectTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - SourceProject sourceProject = classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - Map vertices = sourceProject.getInterpreter().getVertices(); - Interpreter interpreter = new Interpreter(); - interpreter.parseProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + SourceProject sourceProject = classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + Map vertices = sourceProject.getInterpreter().getVertices(); + Interpreter interpreter = new Interpreter(); + interpreter.parseProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); interpreter.convertTreeToGraph(); ArrayList interpreterVertices = new ArrayList<>(interpreter.getVertices().values()); @@ -68,21 +82,49 @@ void createSourceProjectTest() { @Test void populateGraphNodesTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - SourceProject sourceProject = classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - classDiagramManager.convertTreeToDiagram(List.of("AddLatexCommand", "ChangeVersionsStrategyCommand", "Command", "CommandFactory", - "CreateCommand", "DisableVersionsManagementCommand", "EditCommand", "EnableVersionsManagementCommand", - "LoadCommand", "RollbackToPreviousVersionCommand", "SaveCommand")); + SourceProject sourceProject = classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + classDiagramManager.convertTreeToDiagram(List.of("AddLatexCommand", + "ChangeVersionsStrategyCommand", + "Command", + "CommandFactory", + "CreateCommand", + "DisableVersionsManagementCommand", + "EditCommand", + "EnableVersionsManagementCommand", + "LoadCommand", + "RollbackToPreviousVersionCommand", + "SaveCommand")); Map graphNodes = classDiagramManager.getClassDiagram().getGraphNodes(); List l1 = new ArrayList<>(); List l2 = new ArrayList<>(); assertEquals(sourceProject.getInterpreter().getVertices().get( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))) + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))) .getSinkVertices().size(), graphNodes.size()); Iterator iter1 = sourceProject.getInterpreter().getVertices() - .get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))) + .get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))) .getSinkVertices().iterator(); Iterator> iter2 = graphNodes.entrySet().iterator(); while(iter1.hasNext() || iter2.hasNext()) { @@ -99,8 +141,17 @@ void populateGraphNodesTest() { @Test void createDiagramTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); Map>> testingCreatedDiagram = classDiagramManager.getClassDiagram().getDiagram(); @@ -117,11 +168,26 @@ void createDiagramTest() { void exportDiagramToGraphMLTest() { try { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); classDiagramManager.arrangeDiagram(); - File actualFile = classDiagramManager.exportDiagramToGraphML(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.graphML"))); + File actualFile = classDiagramManager.exportDiagramToGraphML(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.graphML")))); DiagramArrangementManagerInterface classDiagramArrangement = new ClassDiagramArrangementManager(classDiagramManager.getClassDiagram()); classDiagramManager.getClassDiagram().setGraphMLDiagramGeometry(classDiagramArrangement.arrangeGraphMLDiagram()); @@ -131,7 +197,13 @@ void exportDiagramToGraphMLTest() { graphMLClassifierVertexArc.convertSinkVertexArc(); DiagramExporter graphMLExporter = new GraphMLClassDiagramExporter(classDiagramManager.getClassDiagram()); - File expectedFile = graphMLExporter.exportDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.graphML"))); + File expectedFile = graphMLExporter.exportDiagram(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.graphML")))); assertTrue(FileUtils.contentEquals(expectedFile, actualFile)); } catch (IOException e) { e.printStackTrace(); @@ -142,8 +214,17 @@ void exportDiagramToGraphMLTest() { void saveDiagramTest() { try { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); File testingSavedFile = classDiagramManager.saveDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingSavedFile.txt"))); @@ -157,29 +238,49 @@ void saveDiagramTest() { @Test void loadDiagramTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); Map>> createdDiagram = classDiagramManager.getClassDiagram().getDiagram(); - classDiagramManager.saveDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); - classDiagramManager.loadDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); + classDiagramManager.saveDiagram(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); + classDiagramManager.loadDiagram(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); Map>> loadedDiagram = classDiagramManager.getClassDiagram().getDiagram(); for (ClassifierVertex classifierVertex : createdDiagram.keySet()) { - Optional optionalSinkVertex = loadedDiagram.keySet().stream().filter(sinkVertex1 -> - sinkVertex1.getName().equals(classifierVertex.getName()) - ).findFirst(); + Optional optionalSinkVertex = loadedDiagram.keySet() + .stream() + .filter(sinkVertex1 -> sinkVertex1.getName().equals(classifierVertex.getName())).findFirst(); assertTrue(optionalSinkVertex.isPresent()); assertEquals(createdDiagram.get(classifierVertex).size(), loadedDiagram.get(optionalSinkVertex.get()).size()); for (Arc arc: createdDiagram.get(classifierVertex)) { - assertTrue( - loadedDiagram.get(optionalSinkVertex.get()).stream() - .anyMatch(a -> - a.sourceVertex().getName().equals(arc.sourceVertex().getName()) && - a.targetVertex().getName().equals(arc.targetVertex().getName()) && - a.arcType().equals(arc.arcType()) - )); + assertTrue(loadedDiagram.get(optionalSinkVertex.get()) + .stream() + .anyMatch(a -> + a.sourceVertex().getName().equals(arc.sourceVertex().getName()) && + a.targetVertex().getName().equals(arc.targetVertex().getName()) && + a.arcType().equals(arc.arcType()))); } } } diff --git a/src/test/java/manager/PackageDiagramManagerTest.java b/src/test/java/manager/PackageDiagramManagerTest.java index 9043949..7b53134 100644 --- a/src/test/java/manager/PackageDiagramManagerTest.java +++ b/src/test/java/manager/PackageDiagramManagerTest.java @@ -21,18 +21,29 @@ public class PackageDiagramManagerTest { @Test void populateGraphMLPackageNodeTest() { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - SourceProject sourceProject = packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram(List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); + SourceProject sourceProject = packageDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); Map graphNodes = packageDiagramManager.getPackageDiagram().getGraphNodes(); - Map packageNodes = sourceProject.getInterpreter().getVertices(); - packageNodes.remove(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + packageNodes.remove(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); assertEquals(packageNodes.size(), graphNodes.size()); Iterator> iter1 = packageNodes.entrySet().iterator(); Iterator> iter2 = graphNodes.entrySet().iterator(); diff --git a/src/test/java/model/GraphClassDiagramConverterTest.java b/src/test/java/model/GraphClassDiagramConverterTest.java index 4b6ba92..b94bf23 100644 --- a/src/test/java/model/GraphClassDiagramConverterTest.java +++ b/src/test/java/model/GraphClassDiagramConverterTest.java @@ -25,22 +25,31 @@ public class GraphClassDiagramConverterTest { @Test void convertGraphToClassDiagramTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); - Set graphNodes = classDiagramManager.getClassDiagram().getGraphNodes().keySet(); - Map>> diagram = classDiagramManager.getClassDiagram().getDiagram(); + Set graphNodes = classDiagramManager.getClassDiagram().getGraphNodes().keySet(); + Map>> diagram = classDiagramManager.getClassDiagram().getDiagram(); List> arcs = new ArrayList<>(); for (Set> arcSet: diagram.values()) { arcs.addAll(arcSet); } - GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(diagram.keySet()); - Map>> adjacencyList = graphClassDiagramConverter.convertGraphToClassDiagram(); + GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(diagram.keySet()); + Map>> adjacencyList = graphClassDiagramConverter.convertGraphToClassDiagram(); classDiagramManager.getClassDiagram().setDiagram(adjacencyList); ShadowCleaner shadowCleaner = new ShadowCleaner(classDiagramManager.getClassDiagram()); - adjacencyList = shadowCleaner.shadowWeakRelationships(); + adjacencyList = shadowCleaner.shadowWeakRelationships(); Set> actualArcs = new HashSet<>(); for (Set> value : adjacencyList.values()) { @@ -57,4 +66,5 @@ void convertGraphToClassDiagramTest() { assertTrue(graphNodes.contains(classifierVertex)); } } + } diff --git a/src/test/java/model/GraphPackageDiagramConverterTest.java b/src/test/java/model/GraphPackageDiagramConverterTest.java index 22d250a..988cb5f 100644 --- a/src/test/java/model/GraphPackageDiagramConverterTest.java +++ b/src/test/java/model/GraphPackageDiagramConverterTest.java @@ -23,15 +23,19 @@ public class GraphPackageDiagramConverterTest { @Test void convertGraphToPackageDiagramTest() { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram( - List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); + packageDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); Map>> diagram = packageDiagramManager.getPackageDiagram().getDiagram(); List> arcs = new ArrayList<>(); @@ -39,8 +43,8 @@ void convertGraphToPackageDiagramTest() { arcs.addAll(arcSet); } - GraphPackageDiagramConverter graphPackageDiagramConverter = new GraphPackageDiagramConverter(diagram.keySet()); - Map>> adjacencyList = graphPackageDiagramConverter.convertGraphToPackageDiagram(); + GraphPackageDiagramConverter graphPackageDiagramConverter = new GraphPackageDiagramConverter(diagram.keySet()); + Map>> adjacencyList = graphPackageDiagramConverter.convertGraphToPackageDiagram(); Set> actualArcs = new HashSet<>(); for (Set> value : adjacencyList.values()) { diff --git a/src/test/java/model/ShadowCleanerTest.java b/src/test/java/model/ShadowCleanerTest.java index 48b4f66..fc2108d 100644 --- a/src/test/java/model/ShadowCleanerTest.java +++ b/src/test/java/model/ShadowCleanerTest.java @@ -25,23 +25,33 @@ public class ShadowCleanerTest { @Test void shadowWeakRelationshipsTest () { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = - Arrays.asList( - "MainWindow", "LatexEditorView", "ChooseTemplate", "LatexEditorController", "VersionsManager", "DocumentManager", "Document" - ); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "ChooseTemplate", + "LatexEditorController", + "VersionsManager", + "DocumentManager", + "Document"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); Map graphNodes = classDiagramManager.getClassDiagram().getGraphNodes(); - GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(graphNodes.keySet()); - Map>> shadowedDiagram = graphClassDiagramConverter.convertGraphToClassDiagram(); + GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(graphNodes.keySet()); + Map>> shadowedDiagram = graphClassDiagramConverter.convertGraphToClassDiagram(); classDiagramManager.getClassDiagram().setDiagram(shadowedDiagram); int numberOfArcsBeforeShadowCleaner = 0; for (Set> arcs: shadowedDiagram.values()) { numberOfArcsBeforeShadowCleaner += arcs.size(); } - ShadowCleaner shadowCleaner = new ShadowCleaner(classDiagramManager.getClassDiagram()); - Map>> diagram = shadowCleaner.shadowWeakRelationships(); + ShadowCleaner shadowCleaner = new ShadowCleaner(classDiagramManager.getClassDiagram()); + Map>> diagram = shadowCleaner.shadowWeakRelationships(); int numberOfArcsAfterShadowCleaner = 0; for (Set> arcs: diagram.values()) { numberOfArcsAfterShadowCleaner += arcs.size(); @@ -49,22 +59,31 @@ void shadowWeakRelationshipsTest () { assertEquals(numberOfArcsAfterShadowCleaner + 7, numberOfArcsBeforeShadowCleaner); ClassifierVertex chooseTemplate = diagram.keySet().stream().filter(sinkVertex -> sinkVertex.getName().equals("ChooseTemplate")).findFirst().orElseGet(Assertions::fail); - List> chooseTemplateLatexEditorViewArc = diagram.get(chooseTemplate).stream() + List> chooseTemplateLatexEditorViewArc = diagram.get(chooseTemplate) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("LatexEditorView")) .toList(); assertEquals(1, chooseTemplateLatexEditorViewArc.size()); assertEquals(ArcType.ASSOCIATION, chooseTemplateLatexEditorViewArc.get(0).arcType()); - ClassifierVertex latexEditorView = diagram.keySet().stream().filter(sinkVertex -> sinkVertex.getName().equals("LatexEditorView")).findFirst().orElseGet(Assertions::fail); - List> latexEditorViewVersionsManagerArc = diagram.get(latexEditorView).stream() + ClassifierVertex latexEditorView = diagram + .keySet() + .stream() + .filter(sinkVertex -> + sinkVertex.getName().equals("LatexEditorView")) + .findFirst() + .orElseGet(Assertions::fail); + List> latexEditorViewVersionsManagerArc = diagram.get(latexEditorView) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("VersionsManager")) .toList(); assertEquals(1, latexEditorViewVersionsManagerArc.size()); assertEquals(ArcType.ASSOCIATION, latexEditorViewVersionsManagerArc.get(0).arcType()); - List> LatexEditorViewLatexEditorControllerArc = diagram.get(latexEditorView).stream() + List> LatexEditorViewLatexEditorControllerArc = diagram.get(latexEditorView) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("LatexEditorController")) .toList(); @@ -80,24 +99,48 @@ void shadowWeakRelationshipsTest () { assertEquals(1, LatexEditorViewDocumentArc.size()); assertEquals(ArcType.ASSOCIATION, LatexEditorViewDocumentArc.get(0).arcType()); - ClassifierVertex mainWindow = diagram.keySet().stream().filter(sinkVertex -> sinkVertex.getName().equals("MainWindow")).findFirst().orElseGet(Assertions::fail); - List> mainWindowLatexEditorViewArc = diagram.get(mainWindow).stream() + ClassifierVertex mainWindow = diagram + .keySet() + .stream() + .filter(sinkVertex -> + sinkVertex.getName().equals("MainWindow")) + .findFirst() + .orElseGet(Assertions::fail); + List> mainWindowLatexEditorViewArc = diagram + .get(mainWindow) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("LatexEditorView")) .toList(); assertEquals(1, mainWindowLatexEditorViewArc.size()); assertEquals(ArcType.ASSOCIATION, mainWindowLatexEditorViewArc.get(0).arcType()); - ClassifierVertex versionsManager = diagram.keySet().stream().filter(sinkVertex -> sinkVertex.getName().equals("VersionsManager")).findFirst().orElseGet(Assertions::fail); - List> versionsManagerLatexEditorViewArc = diagram.get(versionsManager).stream() + ClassifierVertex versionsManager = diagram + .keySet() + .stream() + .filter(sinkVertex -> + sinkVertex.getName().equals("VersionsManager")) + .findFirst() + .orElseGet(Assertions::fail); + List> versionsManagerLatexEditorViewArc = diagram + .get(versionsManager) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("LatexEditorView")) .toList(); assertEquals(1, versionsManagerLatexEditorViewArc.size()); assertEquals(ArcType.ASSOCIATION, versionsManagerLatexEditorViewArc.get(0).arcType()); - ClassifierVertex documentManager = diagram.keySet().stream().filter(sinkVertex -> sinkVertex.getName().equals("DocumentManager")).findFirst().orElseGet(Assertions::fail); - List> documentManagerDocumentArc = diagram.get(documentManager).stream() + ClassifierVertex documentManager = diagram + .keySet() + .stream() + .filter(sinkVertex -> + sinkVertex.getName().equals("DocumentManager")) + .findFirst() + .orElseGet(Assertions::fail); + List> documentManagerDocumentArc = diagram + .get(documentManager) + .stream() .filter(sinkVertexArc -> sinkVertexArc.targetVertex().getName().equals("Document")) .toList(); diff --git a/src/test/java/model/exportation/GraphMLClassDiagramExporterTest.java b/src/test/java/model/exportation/GraphMLClassDiagramExporterTest.java index 4799235..55af91b 100644 --- a/src/test/java/model/exportation/GraphMLClassDiagramExporterTest.java +++ b/src/test/java/model/exportation/GraphMLClassDiagramExporterTest.java @@ -30,17 +30,32 @@ public class GraphMLClassDiagramExporterTest { void exportDiagramTest() { try { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); classDiagramManager.arrangeDiagram(); DiagramArrangementManagerInterface classDiagramArrangement = new ClassDiagramArrangementManager(classDiagramManager.getClassDiagram()); - Map> nodesGeometry = classDiagramArrangement.arrangeGraphMLDiagram(); + Map> nodesGeometry = classDiagramArrangement.arrangeGraphMLDiagram(); classDiagramManager.getClassDiagram().setGraphMLDiagramGeometry(nodesGeometry); DiagramExporter graphMLExporter = new GraphMLClassDiagramExporter(classDiagramManager.getClassDiagram()); - File exportedFile = graphMLExporter.exportDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); - Stream lines = Files.lines(exportedFile.toPath()); - String actualFileContents = lines.collect(Collectors.joining("\n")) + "\n"; + File exportedFile = graphMLExporter.exportDiagram(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); + Stream lines = Files.lines(exportedFile.toPath()); + String actualFileContents = lines.collect(Collectors.joining("\n")) + "\n"; lines.close(); String expectedFileContents = getExpectedFileContents(classDiagramManager); @@ -57,11 +72,10 @@ private static String getExpectedFileContents(ClassDiagramManager classDiagramMa StringBuilder graphMLNodeBuffer = graphMLClassifierVertex.convertSinkVertex(); GraphMLClassifierVertexArc graphMLClassifierVertexArc = new GraphMLClassifierVertexArc(classDiagramManager.getClassDiagram()); StringBuilder graphMLEdgeBuffer = graphMLClassifierVertexArc.convertSinkVertexArc(); - String expectedFileContents = ""; - expectedFileContents += (GraphMLSyntax.getInstance().getGraphMLPrefix()); - expectedFileContents += (graphMLNodeBuffer.toString()); - expectedFileContents += (graphMLEdgeBuffer.toString()); - expectedFileContents += (GraphMLSyntax.getInstance().getGraphMLSuffix()); - return expectedFileContents; + return String.format("%s%s%s%s", + GraphMLSyntax.getInstance().getGraphMLPrefix(), + graphMLNodeBuffer.toString(), + graphMLEdgeBuffer.toString(), + GraphMLSyntax.getInstance().getGraphMLSuffix()); } } diff --git a/src/test/java/model/exportation/JavaFXClassDiagramExporterTest.java b/src/test/java/model/exportation/JavaFXClassDiagramExporterTest.java index a594939..453088a 100644 --- a/src/test/java/model/exportation/JavaFXClassDiagramExporterTest.java +++ b/src/test/java/model/exportation/JavaFXClassDiagramExporterTest.java @@ -27,76 +27,30 @@ public class JavaFXClassDiagramExporterTest { void exportDiagramTest() { try { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); classDiagramManager.convertTreeToDiagram(chosenFiles); DiagramExporter javaFXExporter = new JavaFXClassDiagramExporter(classDiagramManager.getClassDiagram()); - File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); + File actualFile = javaFXExporter.exportDiagram(Path.of(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); - String expectedJsonString = - "[{" + - "\"name\":\"MainWindow\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\MainWindow.java\"," + - "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"editContents\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"type\\\":\\\"String\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"initialize\",\"returnType\":\"void\",\"modifier\":\"private\",\"parameters\":\"{}\"}," + - "{\"name\":\"MainWindow\",\"returnType\":\"Constructor\",\"modifier\":\"public\",\"parameters\":\"{\\\"latexEditorView\\\":\\\"LatexEditorView\\\"}\"}]," + - "\"fields\":[{\"name\":\"frame\",\"returnType\":\"JFrame\",\"modifier\":\"private\"}," + - "{\"name\":\"editorPane\",\"returnType\":\"JEditorPane\",\"modifier\":\"private\"}," + - "{\"name\":\"latexEditorView\",\"returnType\":\"LatexEditorView\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"MainWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"dependency\"}," + - "{\"source\":\"MainWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"association\"},{\"source\":\"MainWindow\",\"target\":\"ChooseTemplate\",\"arcType\":\"dependency\"}]}," + - "{\"name\":\"OpeningWindow\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\OpeningWindow.java\"," + - "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"OpeningWindow\",\"returnType\":\"Constructor\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"main\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"args\\\":\\\"String[]\\\"}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"},{\"name\":\"run\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + - "{\"name\":\"initialize\",\"returnType\":\"void\",\"modifier\":\"private\",\"parameters\":\"{}\"}],\"fields\":[{\"name\":\"frame\",\"returnType\":\"JFrame\",\"modifier\":\"private\"}," + - "{\"name\":\"latexEditorView\",\"returnType\":\"LatexEditorView\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"OpeningWindow\",\"target\":\"LatexEditorController\",\"arcType\":\"dependency\"}," + - "{\"source\":\"OpeningWindow\",\"target\":\"VersionsManager\",\"arcType\":\"dependency\"},{\"source\":\"OpeningWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"association\"}," + - "{\"source\":\"OpeningWindow\",\"target\":\"ChooseTemplate\",\"arcType\":\"dependency\"},{\"source\":\"OpeningWindow\",\"target\":\"VersionsStrategy\",\"arcType\":\"dependency\"}," + - "{\"source\":\"OpeningWindow\",\"target\":\"VolatileVersionsStrategy\",\"arcType\":\"dependency\"}]}," + - "{\"name\":\"LatexEditorView\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\LatexEditorView.java\"," + - "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"getStrategy\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"getController\",\"returnType\":\"LatexEditorController\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"setVersionsManager\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"versionsManager\\\":\\\"VersionsManager\\\"}\"}," + - "{\"name\":\"getType\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"},{\"name\":\"setController\"," + - "\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"controller\\\":\\\"LatexEditorController\\\"}\"},{\"name\":\"getFilename\",\"returnType\":\"String\"," + - "\"modifier\":\"public\",\"parameters\":\"{}\"},{\"name\":\"setType\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"type\\\":\\\"String\\\"}\"}," + - "{\"name\":\"loadFromFile\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"getCurrentDocument\",\"returnType\":\"Document\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"getText\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"setCurrentDocument\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"currentDocument\\\":\\\"Document\\\"}\"}," + - "{\"name\":\"getVersionsManager\",\"returnType\":\"VersionsManager\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"setText\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"text\\\":\\\"String\\\"}\"}," + - "{\"name\":\"saveContents\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"setFilename\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"filename\\\":\\\"String\\\"}\"}," + - "{\"name\":\"saveToFile\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + - "{\"name\":\"setStrategy\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"strategy\\\":\\\"String\\\"}\"}]," + - "\"fields\":[{\"name\":\"controller\",\"returnType\":\"LatexEditorController\",\"modifier\":\"private\"}," + - "{\"name\":\"currentDocument\",\"returnType\":\"Document\",\"modifier\":\"private\"}," + - "{\"name\":\"type\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"text\",\"returnType\":\"String\",\"modifier\":\"private\"}," + - "{\"name\":\"filename\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"strategy\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"versionsManager\"," + - "\"returnType\":\"VersionsManager\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"LatexEditorView\",\"target\":\"LatexEditorController\",\"arcType\":\"dependency\"}," + - "{\"source\":\"LatexEditorView\",\"target\":\"LatexEditorController\",\"arcType\":\"association\"},{\"source\":\"LatexEditorView\",\"target\":\"VersionsManager\",\"" + - "arcType\":\"dependency\"},{\"source\":\"LatexEditorView\",\"target\":\"VersionsManager\",\"arcType\":\"association\"},{\"source\":\"LatexEditorView\",\"target\":\"Document\"," + - "\"arcType\":\"dependency\"},{\"source\":\"LatexEditorView\",\"target\":\"Document\",\"arcType\":\"association\"}]}]"; - JsonArray expectedJsonArray = JsonParser.parseString(expectedJsonString).getAsJsonArray(); - JsonArray actualJsonArray = JsonParser.parseString(Files.readAllLines(actualFile.toPath()).get(0)).getAsJsonArray(); + String expectedJsonString = getExpectedJsonString(); + JsonArray expectedJsonArray = JsonParser.parseString(expectedJsonString).getAsJsonArray(); + JsonArray actualJsonArray = JsonParser.parseString(Files.readAllLines(actualFile.toPath()).get(0)).getAsJsonArray(); assertEquals(expectedJsonArray.size(), actualJsonArray.size()); for (JsonElement element: expectedJsonArray) { for (JsonElement actualElement: actualJsonArray) { @@ -105,31 +59,96 @@ void exportDiagramTest() { } assertEquals(element.getAsJsonObject().size(), actualElement.getAsJsonObject().size()); - JsonArray expectedMethods = JsonParser.parseString(element.getAsJsonObject().get("methods").toString()).getAsJsonArray(); - JsonArray actualMethods = JsonParser.parseString(actualElement.getAsJsonObject().get("methods").toString()).getAsJsonArray(); + JsonArray expectedMethods = JsonParser.parseString(element.getAsJsonObject().get("methods").toString()).getAsJsonArray(); + JsonArray actualMethods = JsonParser.parseString(actualElement.getAsJsonObject().get("methods").toString()).getAsJsonArray(); Set expectedJsonElementSet = CompareArray.setOfElements(expectedMethods); Set actualJsonElementSet = CompareArray.setOfElements(actualMethods); assertEquals(expectedJsonElementSet, actualJsonElementSet); JsonArray expectedFields = JsonParser.parseString(element.getAsJsonObject().get("fields").toString()).getAsJsonArray(); - JsonArray actualFields = JsonParser.parseString(actualElement.getAsJsonObject().get("fields").toString()).getAsJsonArray(); - expectedJsonElementSet = CompareArray.setOfElements(expectedFields); - actualJsonElementSet = CompareArray.setOfElements(actualFields); + JsonArray actualFields = JsonParser.parseString(actualElement.getAsJsonObject().get("fields").toString()).getAsJsonArray(); + expectedJsonElementSet = CompareArray.setOfElements(expectedFields); + actualJsonElementSet = CompareArray.setOfElements(actualFields); assertEquals(expectedJsonElementSet, actualJsonElementSet); JsonArray expectedArcs = JsonParser.parseString(element.getAsJsonObject().get("arcs").toString()).getAsJsonArray(); - JsonArray actualArcs = JsonParser.parseString(actualElement.getAsJsonObject().get("arcs").toString()).getAsJsonArray(); + JsonArray actualArcs = JsonParser.parseString(actualElement.getAsJsonObject().get("arcs").toString()).getAsJsonArray(); expectedJsonElementSet = CompareArray.setOfElements(expectedArcs); - actualJsonElementSet = CompareArray.setOfElements(actualArcs); + actualJsonElementSet = CompareArray.setOfElements(actualArcs); assertEquals(expectedJsonElementSet, actualJsonElementSet); } } - } catch (IOException e) { e.printStackTrace(); } } + + private static String getExpectedJsonString() + { + return "[{" + + "\"name\":\"MainWindow\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\MainWindow.java\"," + + "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"arg0\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"editContents\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"type\\\":\\\"String\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"initialize\",\"returnType\":\"void\",\"modifier\":\"private\",\"parameters\":\"{}\"}," + + "{\"name\":\"MainWindow\",\"returnType\":\"Constructor\",\"modifier\":\"public\",\"parameters\":\"{\\\"latexEditorView\\\":\\\"LatexEditorView\\\"}\"}]," + + "\"fields\":[{\"name\":\"frame\",\"returnType\":\"JFrame\",\"modifier\":\"private\"}," + + "{\"name\":\"editorPane\",\"returnType\":\"JEditorPane\",\"modifier\":\"private\"}," + + "{\"name\":\"latexEditorView\",\"returnType\":\"LatexEditorView\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"MainWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"dependency\"}," + + "{\"source\":\"MainWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"association\"},{\"source\":\"MainWindow\",\"target\":\"ChooseTemplate\",\"arcType\":\"dependency\"}]}," + + "{\"name\":\"OpeningWindow\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\OpeningWindow.java\"," + + "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"OpeningWindow\",\"returnType\":\"Constructor\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"main\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"args\\\":\\\"String[]\\\"}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"},{\"name\":\"run\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"actionPerformed\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"e\\\":\\\"ActionEvent\\\"}\"}," + + "{\"name\":\"initialize\",\"returnType\":\"void\",\"modifier\":\"private\",\"parameters\":\"{}\"}],\"fields\":[{\"name\":\"frame\",\"returnType\":\"JFrame\",\"modifier\":\"private\"}," + + "{\"name\":\"latexEditorView\",\"returnType\":\"LatexEditorView\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"OpeningWindow\",\"target\":\"LatexEditorController\",\"arcType\":\"dependency\"}," + + "{\"source\":\"OpeningWindow\",\"target\":\"VersionsManager\",\"arcType\":\"dependency\"},{\"source\":\"OpeningWindow\",\"target\":\"LatexEditorView\",\"arcType\":\"association\"}," + + "{\"source\":\"OpeningWindow\",\"target\":\"ChooseTemplate\",\"arcType\":\"dependency\"},{\"source\":\"OpeningWindow\",\"target\":\"VersionsStrategy\",\"arcType\":\"dependency\"}," + + "{\"source\":\"OpeningWindow\",\"target\":\"VolatileVersionsStrategy\",\"arcType\":\"dependency\"}]}," + + "{\"name\":\"LatexEditorView\",\"path\":\"C:\\\\Users\\\\user\\\\IntelliJProjects\\\\ObjectOrientedArchitectureDiagrammerDaintiness\\\\src\\\\test\\\\resources\\\\LatexEditor\\\\src\\\\view\\\\LatexEditorView.java\"," + + "\"vertexType\":\"class\",\"coordinate_x\":0.0,\"coordinate_y\":0.0,\"methods\":[{\"name\":\"getStrategy\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"getController\",\"returnType\":\"LatexEditorController\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"setVersionsManager\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"versionsManager\\\":\\\"VersionsManager\\\"}\"}," + + "{\"name\":\"getType\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"},{\"name\":\"setController\"," + + "\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"controller\\\":\\\"LatexEditorController\\\"}\"},{\"name\":\"getFilename\",\"returnType\":\"String\"," + + "\"modifier\":\"public\",\"parameters\":\"{}\"},{\"name\":\"setType\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"type\\\":\\\"String\\\"}\"}," + + "{\"name\":\"loadFromFile\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"getCurrentDocument\",\"returnType\":\"Document\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"getText\",\"returnType\":\"String\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"setCurrentDocument\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"currentDocument\\\":\\\"Document\\\"}\"}," + + "{\"name\":\"getVersionsManager\",\"returnType\":\"VersionsManager\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"setText\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"text\\\":\\\"String\\\"}\"}," + + "{\"name\":\"saveContents\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"setFilename\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"filename\\\":\\\"String\\\"}\"}," + + "{\"name\":\"saveToFile\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{}\"}," + + "{\"name\":\"setStrategy\",\"returnType\":\"void\",\"modifier\":\"public\",\"parameters\":\"{\\\"strategy\\\":\\\"String\\\"}\"}]," + + "\"fields\":[{\"name\":\"controller\",\"returnType\":\"LatexEditorController\",\"modifier\":\"private\"}," + + "{\"name\":\"currentDocument\",\"returnType\":\"Document\",\"modifier\":\"private\"}," + + "{\"name\":\"type\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"text\",\"returnType\":\"String\",\"modifier\":\"private\"}," + + "{\"name\":\"filename\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"strategy\",\"returnType\":\"String\",\"modifier\":\"private\"},{\"name\":\"versionsManager\"," + + "\"returnType\":\"VersionsManager\",\"modifier\":\"private\"}],\"arcs\":[{\"source\":\"LatexEditorView\",\"target\":\"LatexEditorController\",\"arcType\":\"dependency\"}," + + "{\"source\":\"LatexEditorView\",\"target\":\"LatexEditorController\",\"arcType\":\"association\"},{\"source\":\"LatexEditorView\",\"target\":\"VersionsManager\",\"" + + "arcType\":\"dependency\"},{\"source\":\"LatexEditorView\",\"target\":\"VersionsManager\",\"arcType\":\"association\"},{\"source\":\"LatexEditorView\",\"target\":\"Document\"," + + "\"arcType\":\"dependency\"},{\"source\":\"LatexEditorView\",\"target\":\"Document\",\"arcType\":\"association\"}]}]"; + } + public static class CompareArray { public static Set setOfElements(JsonArray arr) { Set set = new HashSet<>(); diff --git a/src/test/java/model/exportation/JavaFXPackageDiagramExporterTest.java b/src/test/java/model/exportation/JavaFXPackageDiagramExporterTest.java index 3b1fec3..5200821 100644 --- a/src/test/java/model/exportation/JavaFXPackageDiagramExporterTest.java +++ b/src/test/java/model/exportation/JavaFXPackageDiagramExporterTest.java @@ -42,14 +42,21 @@ public class JavaFXPackageDiagramExporterTest { void exportDiagramTest() { try { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src"))); packageDiagramManager.convertTreeToDiagram(getPackages()); DiagramExporter javaFXExporter = new JavaFXPackageDiagramExporter(packageDiagramManager.getPackageDiagram()); - File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); + File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt"))); JsonArray expectedJsonArray = getJsonArray(); - JsonArray actualJsonArray = JsonParser.parseString(Files.readAllLines(actualFile.toPath()).get(0)).getAsJsonArray(); + JsonArray actualJsonArray = JsonParser.parseString(Files.readAllLines(actualFile.toPath()).get(0)).getAsJsonArray(); assertEquals(expectedJsonArray.size(), actualJsonArray.size()); for (JsonElement element: expectedJsonArray) { for (JsonElement actualElement: actualJsonArray) { @@ -78,11 +85,11 @@ void exportDiagramTest() { } for (ClassifierVertex classifierVertex : expSinkVertices) { Optional optionalSinkVertex = actSinkVertices.stream().filter(sinkVertex1 -> - sinkVertex1.getName().equals(classifierVertex.getName()) && - sinkVertex1.getVertexType().equals(classifierVertex.getVertexType()) && - sinkVertex1.getArcs().size() == classifierVertex.getArcs().size() && + sinkVertex1.getName().equals(classifierVertex.getName()) && + sinkVertex1.getVertexType().equals(classifierVertex.getVertexType()) && + sinkVertex1.getArcs().size() == classifierVertex.getArcs().size() && sinkVertex1.getMethods().size() == classifierVertex.getMethods().size() && - sinkVertex1.getFields().size() == classifierVertex.getFields().size()) + sinkVertex1.getFields().size() == classifierVertex.getFields().size()) .findFirst(); assertTrue(optionalSinkVertex.isPresent()); @@ -101,7 +108,7 @@ void exportDiagramTest() { for (ClassifierVertex.Method method: classifierVertex.getMethods()) { assertTrue(methods.stream() .anyMatch(method1 -> - method1.name().equals(method.name()) && + method1.name().equals(method.name()) && method1.returnType().equals(method.returnType()) && method1.parameters().equals(method.parameters()) ) @@ -332,16 +339,15 @@ public static void setUp(){ private JsonArray getJsonArray() { if (os.equals("Linux")) { return JsonParser.parseString(expectedString2).getAsJsonArray(); - }else { + } else { return JsonParser.parseString(expectedJsonString).getAsJsonArray(); } } - private List getPackages() { if (os.equals("Linux")){ return List.of("src.view", "src.model"); - }else { + } else { return List.of( "src.view", @@ -353,7 +359,6 @@ private List getPackages() { } } - public static class CompareArray { public static Set setOfElements(JsonArray arr) { Set set = new HashSet<>(); @@ -374,7 +379,5 @@ public static Set setOfElements2(JsonArray arr) { } return set; } - - } } diff --git a/src/test/java/model/exportation/PlantUMLClassDiagramTextExporterTest.java b/src/test/java/model/exportation/PlantUMLClassDiagramTextExporterTest.java index 933d710..24aaaa4 100644 --- a/src/test/java/model/exportation/PlantUMLClassDiagramTextExporterTest.java +++ b/src/test/java/model/exportation/PlantUMLClassDiagramTextExporterTest.java @@ -24,32 +24,49 @@ public class PlantUMLClassDiagramTextExporterTest { void exportDiagramTest() { try { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - classDiagramManager.convertTreeToDiagram( - List.of( - "StableVersionsStrategy", "VersionsStrategy", "VersionsStrategyFactory", "VolatileVersionsStrategy", - "VersionsManager", "Document", "DocumentManager" - )); - - PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(classDiagramManager.getClassDiagram()); - String sinkVertexBuffer = plantUMLClassifierVertex.convertSinkVertex().toString(); - PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(classDiagramManager.getClassDiagram()); - String sinkVertexArcBuffer = plantUMLEdge.convertSinkVertexArc().toString(); - - DiagramExporter graphMLExporter = new PlantUMLClassDiagramTextExporter(classDiagramManager.getClassDiagram()); - File exportedFile = graphMLExporter.exportDiagram(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); - Stream lines = Files.lines(exportedFile.toPath()); - String actualFileContents = lines.collect(Collectors.joining("\n")); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + classDiagramManager.convertTreeToDiagram(List.of("StableVersionsStrategy", + "VersionsStrategy", + "VersionsStrategyFactory", + "VolatileVersionsStrategy", + "VersionsManager", + "Document", + "DocumentManager")); + + PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(classDiagramManager.getClassDiagram()); + String sinkVertexBuffer = plantUMLClassifierVertex.convertSinkVertex().toString(); + PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(classDiagramManager.getClassDiagram()); + String sinkVertexArcBuffer = plantUMLEdge.convertSinkVertexArc().toString(); + DiagramExporter graphMLExporter = new PlantUMLClassDiagramTextExporter(classDiagramManager.getClassDiagram()); + File exportedFile = graphMLExporter.exportDiagram(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); + Stream lines = Files.lines(exportedFile.toPath()); + String actualFileContents = lines.collect(Collectors.joining("\n")); lines.close(); String expectedFileContents = "@startuml\n" + - "skinparam class {\n" + - " BackgroundColor lightyellow\n" + - " BorderColor black\n" + - " ArrowColor black\n" + - "}\n\n"; + "skinparam class {\n" + + " BackgroundColor lightyellow\n" + + " BorderColor black\n" + + " ArrowColor black\n" + + "}\n\n"; - expectedFileContents += sinkVertexBuffer + "\n\n" + sinkVertexArcBuffer + "\n @enduml"; + expectedFileContents += sinkVertexBuffer + + "\n\n" + + sinkVertexArcBuffer + + "\n @enduml"; assertEquals(expectedFileContents, actualFileContents); } catch (IOException e) { e.printStackTrace(); diff --git a/src/test/java/model/graphml/GraphMLPackageVertexArcTest.java b/src/test/java/model/graphml/GraphMLPackageVertexArcTest.java index 20bc5c2..b1def9c 100644 --- a/src/test/java/model/graphml/GraphMLPackageVertexArcTest.java +++ b/src/test/java/model/graphml/GraphMLPackageVertexArcTest.java @@ -20,39 +20,44 @@ public class GraphMLPackageVertexArcTest { @Test void convertVertexArcsToGraphMLTest() { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram( - List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); + packageDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); GraphMLPackageVertexArc graphMLPackageVertexArc = new GraphMLPackageVertexArc(packageDiagramManager.getPackageDiagram()); - StringBuilder actual = graphMLPackageVertexArc.convertVertexArc(); + StringBuilder actual = graphMLPackageVertexArc.convertVertexArc(); - StringBuilder expected = new StringBuilder(); - List> arcs = new ArrayList<>(); + StringBuilder expected = new StringBuilder(); + List> arcs = new ArrayList<>(); for (Set> arcSet: packageDiagramManager.getPackageDiagram().getDiagram().values()) { arcs.addAll(arcSet); } int edgeId = 0; for (Arc e: arcs) { - expected.append( - String.format(" \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " ", edgeId, packageDiagramManager.getPackageDiagram().getGraphNodes().get(e.sourceVertex()), - packageDiagramManager.getPackageDiagram().getGraphNodes().get(e.targetVertex()))); + expected.append(String.format(" \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " ", + edgeId, + packageDiagramManager.getPackageDiagram().getGraphNodes().get(e.sourceVertex()), + packageDiagramManager.getPackageDiagram().getGraphNodes().get(e.targetVertex()))); edgeId++; } assertEquals(expected.toString(), actual.toString()); diff --git a/src/test/java/model/graphml/GraphMLPackageVertexTest.java b/src/test/java/model/graphml/GraphMLPackageVertexTest.java index a710946..f9c5fc5 100644 --- a/src/test/java/model/graphml/GraphMLPackageVertexTest.java +++ b/src/test/java/model/graphml/GraphMLPackageVertexTest.java @@ -22,40 +22,37 @@ class GraphMLPackageVertexTest { void convertVerticesToGraphMLTest() { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram( - List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); - packageDiagramManager.getPackageDiagram().setGraphMLDiagramGeometry( - Map.ofEntries( - Map.entry(0, new Pair<>(10.0, 10.0)), - Map.entry(1, new Pair<>(10.0, 10.0)), - Map.entry(2, new Pair<>(10.0, 10.0)), - Map.entry(3, new Pair<>(10.0, 10.0)), - Map.entry(4, new Pair<>(10.0, 10.0)), - Map.entry(5, new Pair<>(10.0, 10.0)) - )); + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); + packageDiagramManager.getPackageDiagram().setGraphMLDiagramGeometry(Map.ofEntries(Map.entry(0, new Pair<>(10.0, 10.0)), + Map.entry(1, new Pair<>(10.0, 10.0)), + Map.entry(2, new Pair<>(10.0, 10.0)), + Map.entry(3, new Pair<>(10.0, 10.0)), + Map.entry(4, new Pair<>(10.0, 10.0)), + Map.entry(5, new Pair<>(10.0, 10.0)))); GraphMLPackageVertex graphMLPackageVertex = new GraphMLPackageVertex(packageDiagramManager.getPackageDiagram()); - StringBuilder actual = graphMLPackageVertex.convertVertex(); + StringBuilder actual = graphMLPackageVertex.convertVertex(); StringBuilder expected = new StringBuilder(); for (PackageVertex packageNode : packageDiagramManager.getPackageDiagram().getGraphNodes().keySet()) { expected.append(String.format(" \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " %s\n" + - " \n" + - " \n" + - " \n", packageDiagramManager.getPackageDiagram().getGraphNodes().get(packageNode), 10.0, - 10.0, packageNode.getName())); + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " %s\n" + + " \n" + + " \n" + + " \n", + packageDiagramManager.getPackageDiagram().getGraphNodes().get(packageNode), + 10.0, + 10.0, + packageNode.getName())); } assertEquals(expected.toString(), actual.toString()); } diff --git a/src/test/java/model/graphml/GraphMLSinkPackageVertexArcTest.java b/src/test/java/model/graphml/GraphMLSinkPackageVertexArcTest.java index 8e83e5e..ff6cf45 100644 --- a/src/test/java/model/graphml/GraphMLSinkPackageVertexArcTest.java +++ b/src/test/java/model/graphml/GraphMLSinkPackageVertexArcTest.java @@ -22,17 +22,23 @@ public class GraphMLSinkPackageVertexArcTest { void convertSinkVertexArcsToGraphMLTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - classDiagramManager.convertTreeToDiagram( - List.of("AddLatexCommand", "ChangeVersionsStrategyCommand", "Command", "CommandFactory", - "CreateCommand", "DisableVersionsManagementCommand", "EditCommand", "EnableVersionsManagementCommand", - "LoadCommand", "RollbackToPreviousVersionCommand", "SaveCommand") - ); + classDiagramManager.convertTreeToDiagram(List.of("AddLatexCommand", + "ChangeVersionsStrategyCommand", + "Command", + "CommandFactory", + "CreateCommand", + "DisableVersionsManagementCommand", + "EditCommand", + "EnableVersionsManagementCommand", + "LoadCommand", + "RollbackToPreviousVersionCommand", + "SaveCommand")); GraphMLClassifierVertexArc graphMLClassifierVertexArc = new GraphMLClassifierVertexArc(classDiagramManager.getClassDiagram()); - StringBuilder actual = graphMLClassifierVertexArc.convertSinkVertexArc(); + StringBuilder actual = graphMLClassifierVertexArc.convertSinkVertexArc(); - StringBuilder expected = new StringBuilder(); - List> arcs = new ArrayList<>(); + StringBuilder expected = new StringBuilder(); + List> arcs = new ArrayList<>(); for (Set> arcSet: classDiagramManager.getClassDiagram().getDiagram().values()) { arcs.addAll(arcSet); } @@ -40,17 +46,21 @@ void convertSinkVertexArcsToGraphMLTest() { for (Arc e: arcs) { expected.append( String.format("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n", edgeId, classDiagramManager.getClassDiagram().getGraphNodes().get(e.sourceVertex()), - classDiagramManager.getClassDiagram().getGraphNodes().get(e.targetVertex()), getEdgesDescription(e).get(0), - getEdgesDescription(e).get(1),getEdgesDescription(e).get(2))); + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n", + edgeId, + classDiagramManager.getClassDiagram().getGraphNodes().get(e.sourceVertex()), + classDiagramManager.getClassDiagram().getGraphNodes().get(e.targetVertex()), + getEdgesDescription(e).get(0), + getEdgesDescription(e).get(1), + getEdgesDescription(e).get(2))); edgeId++; } assertEquals(expected.toString(), actual.toString()); @@ -62,11 +72,11 @@ private List getEdgesDescription(Arc relationship) { } private List identifyEdgeType(Arc relationship){ return switch (relationship.arcType()) { - case DEPENDENCY -> Arrays.asList("dashed", "none", "plain"); + case DEPENDENCY -> Arrays.asList("dashed", "none", "plain"); case AGGREGATION -> Arrays.asList("line", "white_diamond", "none"); case ASSOCIATION -> Arrays.asList("line", "none", "standard"); - case EXTENSION -> Arrays.asList("line", "none", "white_delta"); - default -> Arrays.asList("dashed", "none", "white_delta"); + case EXTENSION -> Arrays.asList("line", "none", "white_delta"); + default -> Arrays.asList("dashed", "none", "white_delta"); }; } } diff --git a/src/test/java/model/graphml/GraphMLSinkPackageVertexTest.java b/src/test/java/model/graphml/GraphMLSinkPackageVertexTest.java index 0d21cf8..8eb0c66 100644 --- a/src/test/java/model/graphml/GraphMLSinkPackageVertexTest.java +++ b/src/test/java/model/graphml/GraphMLSinkPackageVertexTest.java @@ -20,49 +20,65 @@ public class GraphMLSinkPackageVertexTest { @Test void convertSinkVerticesToGraphMLTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - classDiagramManager.convertTreeToDiagram( - List.of("AddLatexCommand", "ChangeVersionsStrategyCommand", "Command", "CommandFactory", - "CreateCommand", "DisableVersionsManagementCommand", "EditCommand", "EnableVersionsManagementCommand", - "LoadCommand", "RollbackToPreviousVersionCommand", "SaveCommand") - ); - classDiagramManager.getClassDiagram().setGraphMLDiagramGeometry( - Map.ofEntries( - Map.entry(0, new Pair<>(10.0, 10.0)), - Map.entry(1, new Pair<>(10.0, 10.0)), - Map.entry(2, new Pair<>(10.0, 10.0)), - Map.entry(3, new Pair<>(10.0, 10.0)), - Map.entry(4, new Pair<>(10.0, 10.0)), - Map.entry(5, new Pair<>(10.0, 10.0)), - Map.entry(6, new Pair<>(10.0, 10.0)), - Map.entry(7, new Pair<>(10.0, 10.0)), - Map.entry(8, new Pair<>(10.0, 10.0)), - Map.entry(9, new Pair<>(10.0, 10.0)), - Map.entry(10, new Pair<>(10.0, 10.0)) - )); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + classDiagramManager.convertTreeToDiagram(List.of("AddLatexCommand", + "ChangeVersionsStrategyCommand", + "Command", + "CommandFactory", + "CreateCommand", + "DisableVersionsManagementCommand", + "EditCommand", + "EnableVersionsManagementCommand", + "LoadCommand", + "RollbackToPreviousVersionCommand", + "SaveCommand")); + classDiagramManager.getClassDiagram().setGraphMLDiagramGeometry(Map.ofEntries(Map.entry(0, new Pair<>(10.0, 10.0)), + Map.entry(1, new Pair<>(10.0, 10.0)), + Map.entry(2, new Pair<>(10.0, 10.0)), + Map.entry(3, new Pair<>(10.0, 10.0)), + Map.entry(4, new Pair<>(10.0, 10.0)), + Map.entry(5, new Pair<>(10.0, 10.0)), + Map.entry(6, new Pair<>(10.0, 10.0)), + Map.entry(7, new Pair<>(10.0, 10.0)), + Map.entry(8, new Pair<>(10.0, 10.0)), + Map.entry(9, new Pair<>(10.0, 10.0)), + Map.entry(10, new Pair<>(10.0, 10.0)))); GraphMLClassifierVertex graphMLClassifierVertex = new GraphMLClassifierVertex(classDiagramManager.getClassDiagram()); - StringBuilder actual = graphMLClassifierVertex.convertSinkVertex(); + StringBuilder actual = graphMLClassifierVertex.convertSinkVertex(); StringBuilder expected = new StringBuilder(); for (ClassifierVertex leafNode: classDiagramManager.getClassDiagram().getGraphNodes().keySet()) { expected.append(String.format(" \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " %s\n" + - " \n" + - " %s\n" + - " %s\n" + - " \n" + - " \n" + - " \n" + - " \n", classDiagramManager.getClassDiagram().getGraphNodes().get(leafNode), 10.0, 10.0, getNodesColor(leafNode), leafNode.getName(), - getNodesFields(leafNode), getNodesMethods(leafNode))); + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " %s\n" + + " \n" + + " %s\n" + + " %s\n" + + " \n" + + " \n" + + " \n" + + " \n", + classDiagramManager.getClassDiagram().getGraphNodes().get(leafNode), + 10.0, + 10.0, + getNodesColor(leafNode), + leafNode.getName(), + getNodesFields(leafNode), + getNodesMethods(leafNode))); } assertEquals(expected.toString(), actual.toString()); } diff --git a/src/test/java/model/javafx/JavaFXClassDiagramLoaderTest.java b/src/test/java/model/javafx/JavaFXClassDiagramLoaderTest.java index 073aa2f..763afe4 100644 --- a/src/test/java/model/javafx/JavaFXClassDiagramLoaderTest.java +++ b/src/test/java/model/javafx/JavaFXClassDiagramLoaderTest.java @@ -28,62 +28,62 @@ public class JavaFXClassDiagramLoaderTest { @Test void loadDiagramTest() { ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - List chosenFiles = Arrays.asList("MainWindow", "LatexEditorView", "OpeningWindow"); + List chosenFiles = Arrays.asList("MainWindow", + "LatexEditorView", + "OpeningWindow"); classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); classDiagramManager.convertTreeToDiagram(chosenFiles); Map graphNodes = classDiagramManager.getClassDiagram().getGraphNodes(); - GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(graphNodes.keySet()); - Map>> createdDiagram = graphClassDiagramConverter.convertGraphToClassDiagram(); + GraphClassDiagramConverter graphClassDiagramConverter = new GraphClassDiagramConverter(graphNodes.keySet()); + Map>> createdDiagram = graphClassDiagramConverter.convertGraphToClassDiagram(); DiagramExporter javaFXExporter = new JavaFXClassDiagramExporter(classDiagramManager.getClassDiagram()); - File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); + File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); JavaFXClassDiagramLoader javaFXClassDiagramLoader = new JavaFXClassDiagramLoader(actualFile.toPath()); - Set loadedDiagram = javaFXClassDiagramLoader.loadDiagram(); + Set loadedDiagram = javaFXClassDiagramLoader.loadDiagram(); assertEquals(createdDiagram.size(), loadedDiagram.size()); for (ClassifierVertex classifierVertex : createdDiagram.keySet()) { - Optional optionalSinkVertex = loadedDiagram.stream() - .filter( - sinkVertex1 -> sinkVertex1.getName().equals(classifierVertex.getName()) && - sinkVertex1.getVertexType().equals(classifierVertex.getVertexType())) + Optional optionalSinkVertex = loadedDiagram + .stream() + .filter(sinkVertex1 -> + sinkVertex1.getName().equals(classifierVertex.getName()) && + sinkVertex1.getVertexType().equals(classifierVertex.getVertexType())) .findFirst(); assertTrue(optionalSinkVertex.isPresent()); List> arcs = optionalSinkVertex.get().getArcs(); assertEquals(createdDiagram.get(classifierVertex).size(), arcs.size()); for (Arc arc: createdDiagram.get(classifierVertex)) { - assertTrue(arcs.stream() - .anyMatch(sinkVertexArc -> - sinkVertexArc.sourceVertex().getName().equals(arc.sourceVertex().getName()) && - sinkVertexArc.targetVertex().getName().equals(arc.targetVertex().getName()) && - sinkVertexArc.arcType().equals(arc.arcType()) - ) - ); + assertTrue(arcs + .stream() + .anyMatch(sinkVertexArc -> + sinkVertexArc.sourceVertex().getName().equals(arc.sourceVertex().getName()) && + sinkVertexArc.targetVertex().getName().equals(arc.targetVertex().getName()) && + sinkVertexArc.arcType().equals(arc.arcType()))); } List methods = optionalSinkVertex.get().getMethods(); assertEquals(classifierVertex.getMethods().size(), methods.size()); for (ClassifierVertex.Method method: classifierVertex.getMethods()) { - assertTrue(methods.stream() - .anyMatch(method1 -> - method1.name().equals(method.name()) && - method1.returnType().equals(method.returnType()) && - method1.modifier().equals(method.modifier()) - ) - ); + assertTrue(methods + .stream() + .anyMatch(method1 -> + method1.name().equals(method.name()) && + method1.returnType().equals(method.returnType()) && + method1.modifier().equals(method.modifier()))); } List fields = optionalSinkVertex.get().getFields(); assertEquals(classifierVertex.getFields().size(), fields.size()); for (ClassifierVertex.Field field: classifierVertex.getFields()) { - assertTrue(fields.stream() - .anyMatch(field1 -> - field1.name().equals(field.name()) && - field1.type().equals(field.type()) && - field1.modifier().equals(field.modifier()) - ) - ); + assertTrue(fields + .stream() + .anyMatch(field1 -> + field1.name().equals(field.name()) && + field1.type().equals(field.type()) && + field1.modifier().equals(field.modifier()))); } } } diff --git a/src/test/java/model/javafx/JavaFXPackageDiagramLoaderTest.java b/src/test/java/model/javafx/JavaFXPackageDiagramLoaderTest.java index 2ceaff5..563547d 100644 --- a/src/test/java/model/javafx/JavaFXPackageDiagramLoaderTest.java +++ b/src/test/java/model/javafx/JavaFXPackageDiagramLoaderTest.java @@ -27,57 +27,77 @@ public class JavaFXPackageDiagramLoaderTest { @Test void loadDiagramTest() { PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram( - List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); + packageDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); Map>> createdDiagram = packageDiagramManager.getPackageDiagram().getDiagram(); DiagramExporter javaFXExporter = new JavaFXPackageDiagramExporter(packageDiagramManager.getPackageDiagram()); - File actualFile = javaFXExporter.exportDiagram(Path.of(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "testingExportedFile.txt"))); + File actualFile = javaFXExporter.exportDiagram(Path.of(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "testingExportedFile.txt")))); - JavaFXPackageDiagramLoader javaFXLoader = new JavaFXPackageDiagramLoader(actualFile.toPath()); - Set loadedDiagram = javaFXLoader.loadDiagram(); + JavaFXPackageDiagramLoader javaFXLoader = new JavaFXPackageDiagramLoader(actualFile.toPath()); + Set loadedDiagram = javaFXLoader.loadDiagram(); assertEquals(createdDiagram.size(), loadedDiagram.size()); for (PackageVertex vertex: createdDiagram.keySet()) { - Optional optionalVertex = loadedDiagram.stream() - .filter(vertex1 -> - vertex1.getName().equals(vertex.getName()) && - vertex1.getVertexType().equals(vertex.getVertexType()) - ).findFirst(); + Optional optionalVertex = loadedDiagram + .stream() + .filter(vertex1 -> + vertex1.getName().equals(vertex.getName()) && + vertex1.getVertexType().equals(vertex.getVertexType())) + .findFirst(); assertTrue(optionalVertex.isPresent()); List> arcs = optionalVertex.get().getArcs(); assertEquals(createdDiagram.get(vertex).size(), arcs.size()); for (Arc arc: createdDiagram.get(vertex)) { - arcs.stream().filter(vertexArc -> - vertexArc.sourceVertex().getName().equals(arc.sourceVertex().getName()) && - vertexArc.targetVertex().getName().equals(arc.targetVertex().getName()) && - vertexArc.arcType().equals(arc.arcType())) - .findFirst().orElseGet(Assertions::fail); + arcs + .stream() + .filter(vertexArc -> + vertexArc.sourceVertex().getName().equals(arc.sourceVertex().getName()) && + vertexArc.targetVertex().getName().equals(arc.targetVertex().getName()) && + vertexArc.arcType().equals(arc.arcType())) + .findFirst() + .orElseGet(Assertions::fail); } List sinkVertices = optionalVertex.get().getSinkVertices(); assertEquals(vertex.getSinkVertices().size(), sinkVertices.size()); for (ClassifierVertex classifierVertex : vertex.getSinkVertices()) { - sinkVertices.stream().filter(sinkVertex1 -> - sinkVertex1.getName().equals(classifierVertex.getName()) && - sinkVertex1.getVertexType().equals(classifierVertex.getVertexType()) - ).findFirst().orElseGet(Assertions::fail); + sinkVertices + .stream() + .filter(sinkVertex1 -> + sinkVertex1.getName().equals(classifierVertex.getName()) && + sinkVertex1.getVertexType().equals(classifierVertex.getVertexType())) + .findFirst() + .orElseGet(Assertions::fail); } List neighbours = optionalVertex.get().getNeighbourVertices(); assertEquals(vertex.getNeighbourVertices().size(), neighbours.size()); for (PackageVertex neighbour: vertex.getNeighbourVertices()) { - neighbours.stream().filter(vertex1 -> - vertex1.getName().equals(neighbour.getName()) && - vertex1.getVertexType().equals(neighbour.getVertexType()) - ).findFirst().orElseGet(Assertions::fail); + neighbours + .stream() + .filter(vertex1 -> + vertex1.getName().equals(neighbour.getName()) && + vertex1.getVertexType().equals(neighbour.getVertexType())) + .findFirst() + .orElseGet(Assertions::fail); } } } diff --git a/src/test/java/model/plantuml/PlantUMLClassifierVertexArcTest.java b/src/test/java/model/plantuml/PlantUMLClassifierVertexArcTest.java index c6ee441..651cfd3 100644 --- a/src/test/java/model/plantuml/PlantUMLClassifierVertexArcTest.java +++ b/src/test/java/model/plantuml/PlantUMLClassifierVertexArcTest.java @@ -35,10 +35,10 @@ void convertSinkVertexArcTest() { "VersionsManager", "Document", "DocumentManager")); PlantUMLClassifierVertexArc plantUMLEdge = new PlantUMLClassifierVertexArc(classDiagramManager.getClassDiagram()); - String actualBuffer = plantUMLEdge.convertSinkVertexArc().toString(); + String actualBuffer = plantUMLEdge.convertSinkVertexArc().toString(); List expectedRelationships = Arrays.asList(expectedBuffer.split("\n")); - List actualRelationships = Arrays.asList(actualBuffer.split("\n")); + List actualRelationships = Arrays.asList(actualBuffer.split("\n")); Collections.sort(expectedRelationships); Collections.sort(actualRelationships); assertEquals(expectedRelationships, actualRelationships); diff --git a/src/test/java/model/plantuml/PlantUMLClassifierVertexTest.java b/src/test/java/model/plantuml/PlantUMLClassifierVertexTest.java index 6c84556..c474dc0 100644 --- a/src/test/java/model/plantuml/PlantUMLClassifierVertexTest.java +++ b/src/test/java/model/plantuml/PlantUMLClassifierVertexTest.java @@ -19,101 +19,114 @@ public class PlantUMLClassifierVertexTest { @Test void convertSinkVertexTest() { - String expectedBuffer = """ - class VersionsManager { - -enabled: boolean - -strategy: VersionsStrategy - -latexEditorView: LatexEditorView - +changeStrategy(): void - +setPreviousVersion(): Document - +VersionsManager(LatexEditorView latexEditorView, VersionsStrategy versionsStrategy): Constructor - +setStrategy(VersionsStrategy strategy): void - +saveContents(): void - +enable(): void - +getType(): String - +rollback(): void - +getStrategy(): VersionsStrategy - +isEnabled(): boolean - +disable(): void - +putVersion(Document document): void - +rollbackToPreviousVersion(): void - +enableStrategy(): void - +saveToFile(): void - +setCurrentVersion(Document document): void - +loadFromFile(): void - } - - class VolatileVersionsStrategy { - -history: ArrayList[Document] - +removeVersion(): void - +getVersion(): Document - +VolatileVersionsStrategy(): Constructor - +setEntireHistory(List[Document] documents): void - +putVersion(Document document): void - +getEntireHistory(): List[Document] - } - - interface VersionsStrategy { - +removeVersion(): void - +getVersion(): Document - +setEntireHistory(List[Document] documents): void - +getEntireHistory(): List[Document] - +putVersion(Document document): void - } - - class StableVersionsStrategy { - -versionID: String - +removeVersion(): void - +getVersion(): Document - +setEntireHistory(List[Document] documents): void - +getEntireHistory(): List[Document] - +putVersion(Document document): void - } - - class VersionsStrategyFactory { - -strategies: HashMap[String,VersionsStrategy] - +createStrategy(String type): VersionsStrategy - +VersionsStrategyFactory(): Constructor - } - - class Document { - -author: String - -date: String - -copyright: String - -versionID: String - -contents: String - +Document(String date, String copyright, String versionID, String contents, String author): Constructor - +clone(): Document - +getContents(): String - +Document(): Constructor - +save(String filename): void - +getVersionID(): String - +setContents(String contents): void - +changeVersion(): void - } - - class DocumentManager { - -templates: HashMap[String,Document] - +createDocument(String type): Document - +getContents(String type): String - +DocumentManager(): Constructor - } - - """; ClassDiagramManager classDiagramManager = new ClassDiagramManager(); - classDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - classDiagramManager.convertTreeToDiagram(List.of("StableVersionsStrategy", "VersionsStrategy", "VersionsStrategyFactory", "VolatileVersionsStrategy", - "VersionsManager", "Document", "DocumentManager")); + classDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + classDiagramManager.convertTreeToDiagram(List.of("StableVersionsStrategy", + "VersionsStrategy", + "VersionsStrategyFactory", + "VolatileVersionsStrategy", + "VersionsManager", + "Document", + "DocumentManager")); PlantUMLClassifierVertex plantUMLClassifierVertex = new PlantUMLClassifierVertex(classDiagramManager.getClassDiagram()); - String actualBuffer = plantUMLClassifierVertex.convertSinkVertex().toString(); + String actualBuffer = plantUMLClassifierVertex.convertSinkVertex().toString(); - List expected = Arrays.asList(expectedBuffer.split("\n")); - List actual = Arrays.asList(actualBuffer.split("\n")); + List expected = Arrays.asList(EXPECTED_BUFFER.split("\n")); + List actual = Arrays.asList(actualBuffer.split("\n")); Collections.sort(expected); Collections.sort(actual); assertEquals(expected, actual); } + + public static final String EXPECTED_BUFFER = """ + class VersionsManager { + -enabled: boolean + -strategy: VersionsStrategy + -latexEditorView: LatexEditorView + +changeStrategy(): void + +setPreviousVersion(): Document + +VersionsManager(LatexEditorView latexEditorView, VersionsStrategy versionsStrategy): Constructor + +setStrategy(VersionsStrategy strategy): void + +saveContents(): void + +enable(): void + +getType(): String + +rollback(): void + +getStrategy(): VersionsStrategy + +isEnabled(): boolean + +disable(): void + +putVersion(Document document): void + +rollbackToPreviousVersion(): void + +enableStrategy(): void + +saveToFile(): void + +setCurrentVersion(Document document): void + +loadFromFile(): void + } + + class VolatileVersionsStrategy { + -history: ArrayList[Document] + +removeVersion(): void + +getVersion(): Document + +VolatileVersionsStrategy(): Constructor + +setEntireHistory(List[Document] documents): void + +putVersion(Document document): void + +getEntireHistory(): List[Document] + } + + interface VersionsStrategy { + +removeVersion(): void + +getVersion(): Document + +setEntireHistory(List[Document] documents): void + +getEntireHistory(): List[Document] + +putVersion(Document document): void + } + + class StableVersionsStrategy { + -versionID: String + +removeVersion(): void + +getVersion(): Document + +setEntireHistory(List[Document] documents): void + +getEntireHistory(): List[Document] + +putVersion(Document document): void + } + + class VersionsStrategyFactory { + -strategies: HashMap[String,VersionsStrategy] + +createStrategy(String type): VersionsStrategy + +VersionsStrategyFactory(): Constructor + } + + class Document { + -author: String + -date: String + -copyright: String + -versionID: String + -contents: String + +Document(String date, String copyright, String versionID, String contents, String author): Constructor + +clone(): Document + +getContents(): String + +Document(): Constructor + +save(String filename): void + +getVersionID(): String + +setContents(String contents): void + +changeVersion(): void + } + + class DocumentManager { + -templates: HashMap[String,Document] + +createDocument(String type): Document + +getContents(String type): String + +DocumentManager(): Constructor + } + + """; } diff --git a/src/test/java/model/plantuml/PlantUMLPackageVertexArcTest.java b/src/test/java/model/plantuml/PlantUMLPackageVertexArcTest.java index af4fae4..2ba7ccf 100644 --- a/src/test/java/model/plantuml/PlantUMLPackageVertexArcTest.java +++ b/src/test/java/model/plantuml/PlantUMLPackageVertexArcTest.java @@ -17,36 +17,49 @@ class PlantUMLPackageVertexArcTest { + private static final String EXPECTED_BUFFER = """ + src.model ..> src.view + src.controller.commands ..> src.model + src.model ..> src.model.strategies + src.view ..> src.model + src.model.strategies ..> src.model + src.controller ..> src.model + src.view ..> src.controller + src.controller ..> src.controller.commands + src.view ..> src.model.strategies + """; + @Test void convertVertexArcTest() { - String expectedBuffer = "src.model ..> src.view\n" + - "src.controller.commands ..> src.model\n" + - "src.model ..> src.model.strategies\n" + - "src.view ..> src.model\n" + - "src.model.strategies ..> src.model\n" + - "src.controller ..> src.model\n" + - "src.view ..> src.controller\n" + - "src.controller ..> src.controller.commands\n" + - "src.view ..> src.model.strategies\n"; - + // + // Given + // PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); - packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram(List.of( - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); - + packageDiagramManager.createSourceProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + // + // When + // + packageDiagramManager.convertTreeToDiagram(List.of("src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); PlantUMLPackageVertexArc plantUMLEdge = new PlantUMLPackageVertexArc(packageDiagramManager.getPackageDiagram()); - String actualBuffer = plantUMLEdge.convertVertexArc().toString(); - - List expectedRelationship = Arrays.asList(expectedBuffer.split("\n")); - List actualRelationship = Arrays.asList(actualBuffer.split("\n")); + String actualBuffer = plantUMLEdge.convertVertexArc().toString(); + // + // Then + // + List expectedRelationship = Arrays.asList(EXPECTED_BUFFER.split("\n")); + List actualRelationship = Arrays.asList(actualBuffer.split("\n")); Collections.sort(expectedRelationship); Collections.sort(actualRelationship); - assertEquals(expectedRelationship, actualRelationship); } diff --git a/src/test/java/model/plantuml/PlantUMLPackageVertexTest.java b/src/test/java/model/plantuml/PlantUMLPackageVertexTest.java index 46642d7..1e03500 100644 --- a/src/test/java/model/plantuml/PlantUMLPackageVertexTest.java +++ b/src/test/java/model/plantuml/PlantUMLPackageVertexTest.java @@ -19,43 +19,45 @@ public class PlantUMLPackageVertexTest { @Test void convertVertexTest() { - String expectedBuffer = "package src.controller {\n" + - "}\n" + - "\n" + - "package src.controller.commands {\n" + - "}\n" + - "\n" + - "package src.model {\n" + - "}\n" + - "\n" + - "package src {\n" + - "}\n" + - "\n" + - "package src.view {\n" + - "}\n" + - "\n" + - "package src.model.strategies {\n" + - "}\n\n"; PackageDiagramManager packageDiagramManager = new PackageDiagramManager(); packageDiagramManager.createSourceProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - packageDiagramManager.convertTreeToDiagram(List.of( - "src", - "src.view", - "src.model", - "src.model.strategies", - "src.controller.commands", - "src.controller" - )); + packageDiagramManager.convertTreeToDiagram(List.of("src", + "src.view", + "src.model", + "src.model.strategies", + "src.controller.commands", + "src.controller")); PlantUMLPackageVertex plantUMLPackageVertex = new PlantUMLPackageVertex(packageDiagramManager.getPackageDiagram()); - String actualBuffer = plantUMLPackageVertex.convertVertex().toString(); + String actualBuffer = plantUMLPackageVertex.convertVertex().toString(); - List expected = Arrays.asList(expectedBuffer.split("\n")); - List actual = Arrays.asList(actualBuffer.split("\n")); + List expected = Arrays.asList(EXPECTED_BUFFER.split("\n")); + List actual = Arrays.asList(actualBuffer.split("\n")); Collections.sort(expected); Collections.sort(actual); assertEquals(expected, actual); } + + public static final String EXPECTED_BUFFER = """ + package src.controller { + } + + package src.controller.commands { + } + + package src.model { + } + + package src { + } + + package src.view { + } + + package src.model.strategies { + } + + """; } diff --git a/src/test/java/parser/FileVisitorTest.java b/src/test/java/parser/FileVisitorTest.java new file mode 100644 index 0000000..b0b9680 --- /dev/null +++ b/src/test/java/parser/FileVisitorTest.java @@ -0,0 +1,273 @@ +package parser; + +import org.junit.jupiter.api.Test; +import parser.factory.Parser; +import parser.factory.ParserType; +import parser.factory.ProjectParserFactory; +import parser.tree.LeafNode; +import parser.tree.NodeType; +import parser.tree.PackageNode; +import utils.PathConstructor; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class FileVisitorTest { + + ParserType parserType = ParserType.JAVAPARSER; + + @Test + void methodReturnTypesTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath().toString(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + + LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); + List methodReturnTypesExpected = new ArrayList<>(Arrays.asList("Constructor", + "void")); + List methodReturnTypesActual = addLatexCommand.getMethodReturnTypes(); + + Collections.sort(methodReturnTypesActual); + Collections.sort(methodReturnTypesExpected); + assertTrue(methodReturnTypesActual.size() == methodReturnTypesExpected.size() && + methodReturnTypesExpected.containsAll(methodReturnTypesActual) && + methodReturnTypesActual.containsAll(methodReturnTypesExpected)); + } + + @Test + void methodParameterTypesTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + + LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); + List methodParameterTypes = new ArrayList<>(List.of("VersionsManager")); + List methodParameterTypesTest = addLatexCommand.getMethodParameterTypes(); + + Collections.sort(methodParameterTypesTest); + Collections.sort(methodParameterTypes); + assertTrue(methodParameterTypesTest.size() == methodParameterTypes.size() && + methodParameterTypes.containsAll(methodParameterTypesTest) && + methodParameterTypesTest.containsAll(methodParameterTypes)); + } + + @Test + void fieldTypesTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages= parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); + List fieldTypes = new ArrayList<>(List.of("VersionsManager")); + List fieldTypesTest = addLatexCommand + .fields() + .stream() + .map(LeafNode.Field::fieldType) + .sorted() + .collect(Collectors.toCollection(ArrayList::new)); + + Collections.sort(fieldTypes); + assertTrue(fieldTypesTest.size() == fieldTypes.size() && + fieldTypes.containsAll(fieldTypesTest) && + fieldTypesTest.containsAll(fieldTypes)); + } + + @Test + void variableTypesTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + "/src/test/resources/LatexEditor/src/controller")); + + LeafNode latexEditorController = commandPackage.getLeafNodes().get("LatexEditorController"); + List variablesTypes = new ArrayList<>(List.of("CommandFactory")); + List variablesTypesTest = new ArrayList<>(latexEditorController.variables().values()); + + Collections.sort(variablesTypesTest); + Collections.sort(variablesTypes); + assertTrue(variablesTypesTest.size() == variablesTypes.size() && + variablesTypes.containsAll(variablesTypesTest) && + variablesTypesTest.containsAll(variablesTypes)); + } + + @Test + void objectCreationTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); + + LeafNode objectCreationSample = sourcePackage.getLeafNodes().get("ObjectCreationSample"); + List objectsCreatedExpected = new ArrayList<>(List.of("ImplementingClass", + "ImplementingClass", + "ExtensionClass", + "HashMap[String,TestingInterface]")); + List objectsCreatedActual = objectCreationSample.createdObjects(); + + Collections.sort(objectsCreatedActual); + Collections.sort(objectsCreatedExpected); + assertTrue(objectsCreatedActual.size() == objectsCreatedExpected.size() && + objectsCreatedExpected.containsAll(objectsCreatedActual) && + objectsCreatedActual.containsAll(objectsCreatedExpected)); + } + + @Test + void leafNodeTypesTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + PackageNode inheritancePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); + List classLeafs = new ArrayList<>(); + List interfaceLeafs = new ArrayList<>(); + classLeafs.add(inheritancePackage.getLeafNodes().get("ImplementingClass")); + classLeafs.add(inheritancePackage.getLeafNodes().get("ExtensionClass")); + interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface")); + interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface2")); + + for (LeafNode l : classLeafs) { + assertEquals(NodeType.CLASS, l.nodeType()); + } + for (LeafNode l : interfaceLeafs) { + assertEquals(NodeType.INTERFACE, l.nodeType()); + } + + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); + + LeafNode enumTest = sourcePackage.getLeafNodes().get("EnumSample"); + assertEquals(NodeType.ENUM, enumTest.nodeType()); + + LeafNode objectCreationTest = sourcePackage.getLeafNodes().get("ObjectCreationSample"); + assertEquals(NodeType.CLASS, objectCreationTest.nodeType()); + } + + @Test + void innerClassTest() { + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); + LeafNode innerClassSample = sourcePackage.getLeafNodes().get("InnerClassSample"); + assertEquals(innerClassSample.innerClasses().get(0), "InnerClass"); + } + + @Test + void importsTest() { + List expectedImports = List.of("javax.swing.JOptionPane", + "model.strategies.StableVersionsStrategy", + "model.strategies.VersionsStrategy", + "model.strategies.VolatileVersionsStrategy", + "view.LatexEditorView"); + + Parser parser = ProjectParserFactory.createProjectParser(parserType); + + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + "/src/test/resources/LatexEditor/src/model")); + LeafNode versionsManager = commandPackage.getLeafNodes().get("VersionsManager"); + List imports = versionsManager.imports(); + assertEquals(expectedImports, imports); + } +} diff --git a/src/test/java/parser/InterpreterTest.java b/src/test/java/parser/InterpreterTest.java index 7dff3ca..9601042 100644 --- a/src/test/java/parser/InterpreterTest.java +++ b/src/test/java/parser/InterpreterTest.java @@ -3,11 +3,9 @@ import model.graph.Arc; import model.graph.ClassifierVertex; import model.graph.PackageVertex; -import org.javatuples.Triplet; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import parser.tree.LeafNode; -import parser.tree.ModifierType; import parser.tree.PackageNode; import parser.tree.Relationship; import utils.PathConstructor; @@ -17,7 +15,7 @@ import java.nio.file.Paths; import java.util.List; import java.util.Map; -import java.util.Optional; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,10 +25,17 @@ public class InterpreterTest { @Test public void convertTreeToGraphTest() { Interpreter interpreter = new Interpreter(); - interpreter.parseProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + interpreter.parseProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); interpreter.convertTreeToGraph(); - Map packageNodes = interpreter.getPackageNodes(); - Map vertices = interpreter.getVertices(); + Map packageNodes = interpreter.getPackageNodes(); + Map vertices = interpreter.getVertices(); assertEquals(packageNodes.size(), vertices.size()); for (Map.Entry packageNodeEntry: packageNodes.entrySet()) { @@ -38,79 +43,88 @@ public void convertTreeToGraphTest() { PackageNode packageNode = packageNodeEntry.getValue(); PackageVertex vertex = vertices.get(packageNodeEntry.getKey()); - assertEquals(packageNode.getType().toString(), vertex.getVertexType().toString()); - assertEquals(packageNode.getName(), vertex.getName()); + assertEquals(packageNode.getNodeType().toString(), vertex.getVertexType().toString()); + assertEquals(packageNode.getNodeName(), vertex.getName()); Map subNodes = packageNode.getSubNodes(); List neighbours = vertex.getNeighbourVertices(); assertEquals(subNodes.size(), neighbours.size()); for (Map.Entry subNode: subNodes.entrySet()) { - Optional neighbour = neighbours.stream() - .filter(neighbour1 -> - neighbour1.getPath().toString().equals(subNode.getKey().toString()) && - neighbour1.getName().equals(subNode.getValue().getName()) && - neighbour1.getVertexType().toString().equals(subNode.getValue().getType().toString())) - .findAny(); - assertTrue(neighbour.isPresent()); + assertTrue(neighbours + .stream() + .anyMatch(neighbour1 -> + neighbour1.getPath().toString().equals(subNode.getKey().toString()) && + neighbour1.getName().equals(subNode.getValue().getNodeName()) && + neighbour1.getVertexType().toString().equals(subNode.getValue().getNodeType().toString()))); } - List> relationships = packageNode.getPackageNodeRelationships(); - List> arcs = vertex.getArcs(); + Map>> packageNodeRelationships = interpreter.getPackageNodeRelationships(); + + if (!packageNodeRelationships.containsKey(packageNode)) { + continue; + } + + Set> relationships = packageNodeRelationships.get(packageNode); + List> arcs = vertex.getArcs(); assertEquals(relationships.size(), arcs.size()); for (Relationship relationship: relationships) { - Optional> arc = arcs.stream() - .filter(a -> - a.arcType().toString().equals(relationship.relationshipType().toString()) && - a.sourceVertex().getPath().equals(relationship.startingNode().getPackageNodesPath()) && - a.targetVertex().getPath().equals(relationship.endingNode().getPackageNodesPath())) - .findAny(); - assertTrue(arc.isPresent()); + assertTrue(arcs + .stream() + .anyMatch(a -> + a.arcType().toString().equals(relationship.relationshipType().toString()) && + a.sourceVertex().getPath().equals(relationship.startingNode().getPath()) && + a.targetVertex().getPath().equals(relationship.endingNode().getPath()))); } Map leafNodes = packageNode.getLeafNodes(); List sinkVertices = vertex.getSinkVertices(); assertEquals(leafNodes.size(), sinkVertices.size()); for (Map.Entry leafNodeEntry: leafNodes.entrySet()) { - ClassifierVertex classifierVertex = sinkVertices.stream().filter(sinkVertex1 -> - sinkVertex1.getName().equals(leafNodeEntry.getKey())).findAny().orElseGet(Assertions::fail); + ClassifierVertex classifierVertex = sinkVertices + .stream() + .filter(sinkVertex1 -> + sinkVertex1.getName().equals(leafNodeEntry.getKey())).findAny().orElseGet(Assertions::fail); - Map, Map> leafMethods = leafNodeEntry.getValue().getMethods(); + List leafMethods = leafNodeEntry.getValue().methods(); List vertexMethods = classifierVertex.getMethods(); - for (Map.Entry, Map> leafMethod: leafMethods.entrySet()) { - Optional vertexMethod = vertexMethods.stream() - .filter(m -> - m.name().equals(leafMethod.getKey().getValue0().split("\\$")[0]) && - m.parameters().size() == leafMethod.getValue().size() && - m.parameters().equals( leafMethod.getValue() ) && - m.returnType().equals(leafMethod.getKey().getValue1()) && - m.modifier().toString().equals(leafMethod.getKey().getValue2().toString())) - .findAny(); - assertTrue(vertexMethod.isPresent()); + for (LeafNode.Method leafMethod: leafMethods) { + assertTrue(vertexMethods + .stream() + .anyMatch(m -> + m.name().equals(leafMethod.methodName()) && + m.parameters().size() == leafMethod.parameters().size() && + m.parameters().equals(leafMethod.parameters()) && + m.returnType().equals(leafMethod.returnType()) && + m.modifier().toString().equals(leafMethod.modifierType().toString()))); } - List> leafFields = leafNodeEntry.getValue().getFields(); + List leafFields = leafNodeEntry.getValue().fields(); List vertexFields = classifierVertex.getFields(); - for (Triplet leafField: leafFields) { - Optional vertexField = vertexFields.stream() - .filter(f -> - f.name().equals(leafField.getValue0()) && - f.type().equals(leafField.getValue1()) && - f.modifier().toString().equals(leafField.getValue2().toString())) - .findAny(); - assertTrue(vertexField.isPresent()); + for (LeafNode.Field leafField: leafFields) { + assertTrue(vertexFields + .stream() + .anyMatch(f -> + f.name().equals(leafField.fieldNames()) && + f.type().equals(leafField.fieldType()) && + f.modifier().toString().equals(leafField.modifierType().toString()))); + } + + Map>> leafNodeRelationships = interpreter.getLeafNodeRelationships(); + + if (!leafNodeRelationships.containsKey(leafNodeEntry.getValue())) { + continue; } - List> subNodeRelationships = leafNodeEntry.getValue().getLeafNodeRelationships(); - List> sinkVertexArcs = classifierVertex.getArcs(); + Set> subNodeRelationships = leafNodeRelationships.get(leafNodeEntry.getValue()); + List> sinkVertexArcs = classifierVertex.getArcs(); assertEquals(subNodeRelationships.size(), sinkVertexArcs.size()); for (Relationship relationship: subNodeRelationships) { - Optional> arc = sinkVertexArcs.stream() - .filter(a -> - a.arcType().toString().equals(relationship.relationshipType().toString()) && - a.sourceVertex().getPath().equals(relationship.startingNode().getLeafNodesPath()) && - a.targetVertex().getPath().equals(relationship.endingNode().getLeafNodesPath())) - .findAny(); - assertTrue(arc.isPresent()); + assertTrue(sinkVertexArcs + .stream() + .anyMatch(a -> + a.arcType().toString().equals(relationship.relationshipType().toString()) && + a.sourceVertex().getPath().equals(relationship.startingNode().path()) && + a.targetVertex().getPath().equals(relationship.endingNode().path()))); } } } diff --git a/src/test/java/parser/PackageNodeCleanerTest.java b/src/test/java/parser/PackageNodeCleanerTest.java index e79fe02..222bdc3 100644 --- a/src/test/java/parser/PackageNodeCleanerTest.java +++ b/src/test/java/parser/PackageNodeCleanerTest.java @@ -18,30 +18,119 @@ public class PackageNodeCleanerTest { @Test void removeNonPackageNodesTest() { Interpreter interpreter = new Interpreter(); - interpreter.parseProject(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01"))); - Map packageNodes = interpreter.getPackageNodes(); + interpreter.parseProject(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01")))); - PackageNodeCleaner packageNodeCleaner = new PackageNodeCleaner(packageNodes); - Map validPackageNodes = packageNodeCleaner.removeNonPackageNodes(); + Map packageNodes = interpreter.getPackageNodes(); + Map validPackageNodes = PackageNodeCleaner.removeNonPackageNodes(packageNodes); assertEquals(packageNodes.size(), validPackageNodes.size() + 5); // Valid Package Nodes - assertTrue(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src")))); - assertTrue(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "bookstore")))); - assertTrue(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "gui")))); - assertTrue(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01")))); + assertTrue(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src"))))); + assertTrue(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "bookstore"))))); + assertTrue(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "gui"))))); + assertTrue(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01"))))); // Non Valid Package Nodes - assertFalse(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", ".settings")))); - assertFalse(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "bin")))); - assertFalse(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "bin", "bookstore")))); - assertFalse(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "bin", "gui")))); - assertFalse(validPackageNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src", "lib")))); + assertFalse(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + ".settings"))))); + assertFalse(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "bin"))))); + assertFalse(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "bin", + "bookstore"))))); + assertFalse(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "bin", + "gui"))))); + assertFalse(validPackageNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src", + "lib"))))); - PackageNode sourcePackage = validPackageNodes.get(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01"))); + PackageNode sourcePackage = validPackageNodes.get(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01")))); Map sourcePackageSubNodes = sourcePackage.getSubNodes(); assertEquals(sourcePackageSubNodes.size(), 1); - assertTrue(sourcePackageSubNodes.containsKey(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "BookstoreAdvancedV01", "src")))); + assertTrue(sourcePackageSubNodes.containsKey(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "BookstoreAdvancedV01", + "src"))))); } } diff --git a/src/test/java/parser/ProjectParserTest.java b/src/test/java/parser/ProjectParserTest.java new file mode 100644 index 0000000..7e84cfc --- /dev/null +++ b/src/test/java/parser/ProjectParserTest.java @@ -0,0 +1,567 @@ +package parser; + +import org.junit.jupiter.api.Test; +import parser.factory.Parser; +import parser.factory.ParserType; +import parser.factory.ProjectParserFactory; +import parser.tree.LeafNode; +import parser.tree.PackageNode; +import utils.PathConstructor; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ProjectParserTest +{ + + ParserType parserType = ParserType.JAVAPARSER; + + @Test + void parsingTest() { + + Parser parser = ProjectParserFactory.createProjectParser(parserType); + Map packageNodes = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + + PackageNode controllerPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller"))); + List testingLeafNodes = new ArrayList<>(); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller")), + controllerPackage.getPath()); + + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + String.format("%s%s", + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src"))), + controllerPackage.getParentNode().getPath()); + + assertTrue(controllerPackage.isValid(), "message"); + Map subNodes = controllerPackage.getSubNodes(); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands")), + subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))).getPath()); + + for (LeafNode l : controllerPackage.getLeafNodes().values()) { + testingLeafNodes.add(l.path()); + assertEquals(l.parentNode().getPath(), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller"))); + } + Collections.sort(testingLeafNodes); + Collections.sort(CONTROLLERS_LEAF_NODES); + assertTrue(testingLeafNodes.size() == CONTROLLERS_LEAF_NODES.size() && + CONTROLLERS_LEAF_NODES.containsAll(testingLeafNodes) && + testingLeafNodes.containsAll(CONTROLLERS_LEAF_NODES)); + + testingLeafNodes.clear(); + + PackageNode commandsPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands")), + commandsPackage.getPath()); + + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller")), + commandsPackage.getParentNode().getPath()); + + assertTrue(commandsPackage.isValid()); + subNodes = commandsPackage.getSubNodes(); + assertEquals(0, subNodes.size()); + for (LeafNode l : commandsPackage.getLeafNodes().values()) { + testingLeafNodes.add(l.path()); + assertEquals(l.parentNode().getPath(), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + } + Collections.sort(testingLeafNodes); + Collections.sort(COMMANDS_LEAF_NODES); + assertTrue(testingLeafNodes.size() == COMMANDS_LEAF_NODES.size() && + COMMANDS_LEAF_NODES.containsAll(testingLeafNodes) && + testingLeafNodes.containsAll(COMMANDS_LEAF_NODES)); + + testingLeafNodes.clear(); + + PackageNode modelPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model"))); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model")), + modelPackage.getPath()); + + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + String.format("%s%s", + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src"))), + modelPackage.getParentNode().getPath()); + + assertTrue(modelPackage.isValid()); + subNodes = modelPackage.getSubNodes(); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies")), + subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies"))).getPath()); + for (LeafNode l : modelPackage.getLeafNodes().values()) { + assertEquals(l.parentNode().getPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model"))); + testingLeafNodes.add(l.path()); + } + Collections.sort(testingLeafNodes); + Collections.sort(MODELS_LEAF_NODES); + assertTrue(testingLeafNodes.size() == MODELS_LEAF_NODES.size() && + MODELS_LEAF_NODES.containsAll(testingLeafNodes) && + testingLeafNodes.containsAll(MODELS_LEAF_NODES)); + + testingLeafNodes.clear(); + + PackageNode strategiesPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies"))); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies")), + strategiesPackage.getPath()); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model")), + strategiesPackage.getParentNode().getPath()); + assertTrue(strategiesPackage.isValid()); + subNodes = strategiesPackage.getSubNodes(); + assertEquals(0, subNodes.size()); + for (LeafNode l : strategiesPackage.getLeafNodes().values()) { + assertEquals(l.parentNode().getPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies"))); + testingLeafNodes.add(l.path()); + } + Collections.sort(testingLeafNodes); + Collections.sort(STRATEGIES_LEAF_NODES); + assertTrue(testingLeafNodes.size() == STRATEGIES_LEAF_NODES.size() && + STRATEGIES_LEAF_NODES.containsAll(testingLeafNodes) && + testingLeafNodes.containsAll(STRATEGIES_LEAF_NODES)); + + testingLeafNodes.clear(); + + PackageNode viewPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view"))); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view")), + viewPackage.getPath()); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), String.format("%s%s", + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src"))), + viewPackage.getParentNode().getPath()); + assertTrue(viewPackage.isValid()); + subNodes = viewPackage.getSubNodes(); + assertEquals(0, subNodes.size()); + for (LeafNode l : viewPackage.getLeafNodes().values()) { + assertEquals(l.parentNode().getPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view"))); + testingLeafNodes.add(l.path()); + } + Collections.sort(testingLeafNodes); + Collections.sort(VIEWS_LEAF_NODES); + assertTrue(testingLeafNodes.size() == VIEWS_LEAF_NODES.size() && + VIEWS_LEAF_NODES.containsAll(testingLeafNodes) && + testingLeafNodes.containsAll(VIEWS_LEAF_NODES)); + testingLeafNodes.clear(); + + PackageNode sourcePackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + String.format("%s%s", + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + String.format("%s%s", + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src"))), + sourcePackage.getPath()); + + assertEquals(Paths.get(""), sourcePackage.getParentNode().getPath()); + assertFalse(sourcePackage.isValid()); + subNodes = sourcePackage.getSubNodes(); + List testingSubPackages = new ArrayList<>(); + for (PackageNode subP : subNodes.values()) { + testingSubPackages.add(subP.getPath()); + } + Collections.sort(testingSubPackages); + Collections.sort(SOURCES_SUB_PACKAGES); + assertTrue(testingSubPackages.size() == SOURCES_SUB_PACKAGES.size() && + SOURCES_SUB_PACKAGES.containsAll(testingSubPackages) && + testingSubPackages.containsAll(SOURCES_SUB_PACKAGES)); + assertEquals(0, sourcePackage.getLeafNodes().size()); + } + + public static final List SOURCES_SUB_PACKAGES = new ArrayList<>(Arrays.asList(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view")))); + + public static final List VIEWS_LEAF_NODES = new ArrayList<>(Arrays.asList(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view", + "ChooseTemplate.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view", + "LatexEditorView.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view", + "MainWindow.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "view", + "OpeningWindow.java")))); + + public static final List CONTROLLERS_LEAF_NODES = new ArrayList<>(List.of(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "LatexEditorController.java")))); + + public static final List STRATEGIES_LEAF_NODES = new ArrayList<>(Arrays.asList(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies", + "StableVersionsStrategy.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies", + "VersionsStrategy.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies", + "VolatileVersionsStrategy.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "strategies", + "VersionsStrategyFactory.java")))); + + public static final List MODELS_LEAF_NODES = new ArrayList<>(Arrays.asList(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "Document.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "DocumentManager.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "model", + "VersionsManager.java")))); + + public static final List COMMANDS_LEAF_NODES = new ArrayList<>(Arrays.asList(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "AddLatexCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "Command.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "CommandFactory.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "CreateCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "EditCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "LoadCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "SaveCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "ChangeVersionsStrategyCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "DisableVersionsManagementCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "EnableVersionsManagementCommand.java")), + Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands", + "RollbackToPreviousVersionCommand.java")))); +} diff --git a/src/test/java/parser/javaparser/JavaparserRelationshipIdentifierTest.java b/src/test/java/parser/RelationshipIdentifierTest.java similarity index 50% rename from src/test/java/parser/javaparser/JavaparserRelationshipIdentifierTest.java rename to src/test/java/parser/RelationshipIdentifierTest.java index ec575e5..92135ef 100644 --- a/src/test/java/parser/javaparser/JavaparserRelationshipIdentifierTest.java +++ b/src/test/java/parser/RelationshipIdentifierTest.java @@ -1,4 +1,4 @@ -package parser.javaparser; +package parser; import org.junit.jupiter.api.Test; import parser.factory.Parser; @@ -19,11 +19,14 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -public class JavaparserRelationshipIdentifierTest { +public class RelationshipIdentifierTest +{ ParserType parserType = ParserType.JAVAPARSER; @@ -31,7 +34,14 @@ public class JavaparserRelationshipIdentifierTest { void getFieldAndMethodTypesTest() { Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); List methodReturnTypes = new ArrayList<>(Arrays.asList("Constructor", "void")); List fieldTypes = new ArrayList<>(List.of("VersionsManager")); List methodParameterTypes = new ArrayList<>(List.of("VersionsManager")); @@ -43,48 +53,59 @@ void getFieldAndMethodTypesTest() { List fieldTypesTest; List methodParameterTypesTest; methodParameterTypesTest = addLatexCommand.getMethodParameterTypes(); - fieldTypesTest = addLatexCommand.getFieldsTypes(); - methodReturnTypesTest = addLatexCommand.getMethodsReturnTypes(); + fieldTypesTest = addLatexCommand.fields().stream().map(LeafNode.Field::fieldType).collect(Collectors.toCollection(ArrayList::new)); + methodReturnTypesTest = addLatexCommand.getMethodReturnTypes(); Collections.sort(methodReturnTypesTest); Collections.sort(methodReturnTypes); - assertTrue( - methodReturnTypesTest.size() == methodReturnTypes.size() && - methodReturnTypes.containsAll(methodReturnTypesTest) && - methodReturnTypesTest.containsAll(methodReturnTypes)); + assertTrue(methodReturnTypesTest.size() == methodReturnTypes.size() && + methodReturnTypes.containsAll(methodReturnTypesTest) && + methodReturnTypesTest.containsAll(methodReturnTypes)); Collections.sort(fieldTypesTest); Collections.sort(fieldTypes); - assertTrue( - fieldTypesTest.size() == fieldTypes.size() && - fieldTypes.containsAll(fieldTypesTest) && - fieldTypesTest.containsAll(fieldTypes)); + assertTrue(fieldTypesTest.size() == fieldTypes.size() && + fieldTypes.containsAll(fieldTypesTest) && + fieldTypesTest.containsAll(fieldTypes)); Collections.sort(methodParameterTypesTest); Collections.sort(methodParameterTypes); - assertTrue( - methodParameterTypesTest.size() == methodParameterTypes.size() && - methodParameterTypes.containsAll(methodParameterTypesTest) && - methodParameterTypesTest.containsAll(methodParameterTypes)); + assertTrue(methodParameterTypesTest.size() == methodParameterTypes.size() && + methodParameterTypes.containsAll(methodParameterTypesTest) && + methodParameterTypesTest.containsAll(methodParameterTypes)); } @Test void leafNodeRelationshipsTest() { Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + Map>> leafNodeRelationships = parser.createRelationships(packages); + PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - List> nodeRelationships = addLatexCommand.getLeafNodeRelationships(); + Set> nodeRelationships = leafNodeRelationships.get(addLatexCommand); boolean foundObligatoryRelationship = false; int relationshipCounter = 0; for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("AddLatexCommand")) && (relationship.endingNode().getName().equals("VersionsManager"))) { + if ((relationship.startingNode().nodeName().equals("AddLatexCommand")) && (relationship.endingNode().nodeName().equals("VersionsManager"))) { if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) { foundObligatoryRelationship = true; } else { foundObligatoryRelationship = relationship.relationshipType().equals(RelationshipType.ASSOCIATION); } - } else if ((relationship.startingNode().getName().equals("AddLatexCommand")) && (relationship.endingNode().getName().equals("Command"))) { + } else if ((relationship.startingNode().nodeName().equals("AddLatexCommand")) && (relationship.endingNode().nodeName().equals("Command"))) { assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); foundObligatoryRelationship = true; } else { @@ -94,26 +115,29 @@ void leafNodeRelationshipsTest() { } assertEquals(3, relationshipCounter); assertTrue(foundObligatoryRelationship); - assertEquals(NodeType.CLASS, addLatexCommand.getType()); + assertEquals(NodeType.CLASS, addLatexCommand.nodeType()); LeafNode commandFactory = commandPackage.getLeafNodes().get("CommandFactory"); - nodeRelationships = commandFactory.getLeafNodeRelationships(); + nodeRelationships = leafNodeRelationships.get(commandFactory); boolean foundObligatoryRelationships_CommandFactoryToVersionsManager = false; boolean foundObligatoryRelationships_CommandFactoryToCommand = false; boolean foundObligatoryRelationships_CommandFactoryToAddLatexCommand = false; relationshipCounter = 0; for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("CommandFactory")) && (relationship.endingNode().getName().equals("VersionsManager"))) { + if ((relationship.startingNode().nodeName().equals("CommandFactory")) && + (relationship.endingNode().nodeName().equals("VersionsManager"))) { if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) { foundObligatoryRelationships_CommandFactoryToVersionsManager = true; - }else { + } else { foundObligatoryRelationships_CommandFactoryToVersionsManager = relationship.relationshipType().equals(RelationshipType.ASSOCIATION); } - } else if ((relationship.startingNode().getName().equals("CommandFactory")) && (relationship.endingNode().getName().equals("Command"))) { + } else if ((relationship.startingNode().nodeName().equals("CommandFactory")) && + (relationship.endingNode().nodeName().equals("Command"))) { if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) foundObligatoryRelationships_CommandFactoryToCommand = true; - }else if ((relationship.startingNode().getName().equals("CommandFactory")) && (relationship.endingNode().getName().equals("AddLatexCommand"))) { + } else if ((relationship.startingNode().nodeName().equals("CommandFactory")) && + (relationship.endingNode().nodeName().equals("AddLatexCommand"))) { if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) foundObligatoryRelationships_CommandFactoryToAddLatexCommand = true; } @@ -124,33 +148,47 @@ void leafNodeRelationshipsTest() { assertTrue(foundObligatoryRelationships_CommandFactoryToAddLatexCommand); assertEquals(13, relationshipCounter); - assertEquals(NodeType.CLASS, commandFactory.getType()); + assertEquals(NodeType.CLASS, commandFactory.nodeType()); parser = ProjectParserFactory.createProjectParser(parserType); - packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); + packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + leafNodeRelationships = parser.createRelationships(packages); + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); - LeafNode objectCreation = sourcePackage.getLeafNodes().get("ObjectCreationTest"); - nodeRelationships = objectCreation.getLeafNodeRelationships(); + LeafNode objectCreation = sourcePackage.getLeafNodes().get("ObjectCreationSample"); + nodeRelationships = leafNodeRelationships.get(objectCreation); foundObligatoryRelationship = false; relationshipCounter = 0; for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("ObjectCreationTest")) && (relationship.endingNode().getName().equals("ExtensionClass"))) { + if ((relationship.startingNode().nodeName().equals("ObjectCreationSample")) && + (relationship.endingNode().nodeName().equals("ExtensionClass"))) { if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) { foundObligatoryRelationship = true; - }else { + } else { foundObligatoryRelationship = relationship.relationshipType().equals(RelationshipType.ASSOCIATION); } - }else if ((relationship.startingNode().getName().equals("ObjectCreationTest")) && (relationship.endingNode().getName().equals("TestingInterface"))) { + } else if ((relationship.startingNode().nodeName().equals("ObjectCreationSample")) && + (relationship.endingNode().nodeName().equals("TestingInterface"))) { assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); foundObligatoryRelationship = true; - }else if ((relationship.startingNode().getName().equals("ObjectCreationTest")) && (relationship.endingNode().getName().equals("ImplementingClass"))) { + } else if ((relationship.startingNode().nodeName().equals("ObjectCreationSample")) && + (relationship.endingNode().nodeName().equals("ImplementingClass"))) { assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); foundObligatoryRelationship = true; - }else { + } else { foundObligatoryRelationship = false; } relationshipCounter++; @@ -163,22 +201,36 @@ void leafNodeRelationshipsTest() { void leafNodeInheritanceRelationshipTest() { Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + Map>> leafNodeRelationships = parser.createRelationships(packages); + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); LeafNode implementingClassLeaf = sourcePackage.getLeafNodes().get("ImplementingClass"); - List> nodeRelationships = implementingClassLeaf.getLeafNodeRelationships(); + Set> nodeRelationships = leafNodeRelationships.get(implementingClassLeaf); boolean foundObligatoryRelationship = false; int relationshipCounter = 0; for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("TestingInterface2"))) { + if ((relationship.startingNode().nodeName().equals("ImplementingClass")) && + (relationship.endingNode().nodeName().equals("TestingInterface2"))) { assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("ExtensionClass"))) { + } else if ((relationship.startingNode().nodeName().equals("ImplementingClass")) && + (relationship.endingNode().nodeName().equals("ExtensionClass"))) { assertEquals(RelationshipType.EXTENSION, relationship.relationshipType()); foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("TestingInterface"))) { + } else if ((relationship.startingNode().nodeName().equals("ImplementingClass")) && + (relationship.endingNode().nodeName().equals("TestingInterface"))) { assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); foundObligatoryRelationship = true; } else { @@ -189,22 +241,37 @@ void leafNodeInheritanceRelationshipTest() { assertTrue(foundObligatoryRelationship); assertEquals(3, relationshipCounter); - assertEquals(NodeType.CLASS, implementingClassLeaf.getType()); + assertEquals(NodeType.CLASS, implementingClassLeaf.nodeType()); } @Test void packageNodeRelationshipsTest() { Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - - PackageNode commands = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - List> packageRelationships = commands.getPackageNodeRelationships(); - + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src")))); + Map>> leafNodeRelationships = parser.createRelationships(packages); + Map>> packageNodeRelationships = parser.identifyPackageNodeRelationships(leafNodeRelationships); + PackageNode commands = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller", + "commands"))); + Set> packageRelationships = packageNodeRelationships.get(commands); boolean foundObligatoryRelationship = false; int relationshipCounter = 0; for (Relationship relationship : packageRelationships) { - if ((relationship.startingNode().getName().equals("src.controller.commands")) && (relationship.endingNode().getName().equals("src.model"))) { + if ((relationship.startingNode().getNodeName().equals("src.controller.commands")) && + (relationship.endingNode().getNodeName().equals("src.model"))) { assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); foundObligatoryRelationship = true; } else { @@ -215,18 +282,26 @@ void packageNodeRelationshipsTest() { assertTrue(foundObligatoryRelationship); assertEquals(1, relationshipCounter); - assertEquals(NodeType.PACKAGE, commands.getType()); + assertEquals(NodeType.PACKAGE, commands.getNodeType()); - PackageNode controller = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller"))); - packageRelationships = controller.getPackageNodeRelationships(); + PackageNode controller = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "LatexEditor", + "src", + "controller"))); + packageRelationships = packageNodeRelationships.get(controller); foundObligatoryRelationship = false; relationshipCounter = 0; for (Relationship relationship : packageRelationships) { - if ((relationship.startingNode().getName().equals("src.controller")) && (relationship.endingNode().getName().equals("src.model"))) { + if ((relationship.startingNode().getNodeName().equals("src.controller")) && + (relationship.endingNode().getNodeName().equals("src.model"))) { assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("src.controller")) && (relationship.endingNode().getName().equals("src.controller.commands"))) { + } else if ((relationship.startingNode().getNodeName().equals("src.controller")) && + (relationship.endingNode().getNodeName().equals("src.controller.commands"))) { assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); foundObligatoryRelationship = true; } else { @@ -237,15 +312,26 @@ void packageNodeRelationshipsTest() { assertTrue(foundObligatoryRelationship); assertEquals(2, relationshipCounter); - assertEquals(NodeType.PACKAGE, commands.getType()); + assertEquals(NodeType.PACKAGE, commands.getNodeType()); } @Test void leafNodeTypesTest() { Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); + Map packages = parser.parseSourcePackage(Paths.get(String.format("%s%s%s", + PathConstructor.getCurrentPath(), + File.separator, + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting")))); + Map>> leafNodeRelationships = parser.createRelationships(packages); + PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), + PathConstructor.constructPath("src", + "test", + "resources", + "ParserTesting"))); List classLeafs = new ArrayList<>(); List interfaceLeafs = new ArrayList<>(); classLeafs.add(sourcePackage.getLeafNodes().get("ImplementingClass")); @@ -253,10 +339,10 @@ void leafNodeTypesTest() { interfaceLeafs.add(sourcePackage.getLeafNodes().get("TestingInterface")); interfaceLeafs.add(sourcePackage.getLeafNodes().get("TestingInterface2")); for (LeafNode l : classLeafs) { - assertEquals(NodeType.CLASS, l.getType()); + assertEquals(NodeType.CLASS, l.nodeType()); } for (LeafNode l : interfaceLeafs) { - assertEquals(NodeType.INTERFACE, l.getType()); + assertEquals(NodeType.INTERFACE, l.nodeType()); } } } diff --git a/src/test/java/parser/javaparser/JavaparserFileVisitorTest.java b/src/test/java/parser/javaparser/JavaparserFileVisitorTest.java deleted file mode 100644 index 2eeb923..0000000 --- a/src/test/java/parser/javaparser/JavaparserFileVisitorTest.java +++ /dev/null @@ -1,151 +0,0 @@ -package parser.javaparser; - -import org.junit.jupiter.api.Test; -import parser.factory.Parser; -import parser.factory.ParserType; -import parser.factory.ProjectParserFactory; -import parser.tree.LeafNode; -import parser.tree.NodeType; -import parser.tree.PackageNode; -import utils.PathConstructor; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class JavaparserFileVisitorTest { - - ParserType parserType = ParserType.JAVAPARSER; - - @Test - void methodReturnTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List methodReturnTypes = new ArrayList<>(Arrays.asList("Constructor", "void")); - List methodReturnTypesTest = addLatexCommand.getMethodsReturnTypes(); - - Collections.sort(methodReturnTypesTest); - Collections.sort(methodReturnTypes); - assertTrue( - methodReturnTypesTest.size() == methodReturnTypes.size() && - methodReturnTypes.containsAll(methodReturnTypesTest) && - methodReturnTypesTest.containsAll(methodReturnTypes)); - } - - @Test - void methodParameterTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List methodParameterTypes = new ArrayList<>(List.of("VersionsManager")); - List methodParameterTypesTest = addLatexCommand.getMethodParameterTypes(); - - Collections.sort(methodParameterTypesTest); - Collections.sort(methodParameterTypes); - assertTrue( - methodParameterTypesTest.size() == methodParameterTypes.size() && - methodParameterTypes.containsAll(methodParameterTypesTest) && - methodParameterTypesTest.containsAll(methodParameterTypes)); - } - - @Test - void fieldTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List fieldTypes = new ArrayList<>(List.of("VersionsManager")); - List fieldTypesTest = addLatexCommand.getFieldsTypes(); - - Collections.sort(fieldTypesTest); - Collections.sort(fieldTypes); - assertTrue( - fieldTypesTest.size() == fieldTypes.size() && - fieldTypes.containsAll(fieldTypesTest) && - fieldTypesTest.containsAll(fieldTypes)); - } - - @Test - void variableTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - "/src/test/resources/LatexEditor/src/controller")); - LeafNode latexEditorController = commandPackage.getLeafNodes().get("LatexEditorController"); - - List variablesTypes = new ArrayList<>(List.of("CommandFactory")); - List variablesTypesTest = ((JavaparserLeafNode) latexEditorController).getVariablesTypes(); - - Collections.sort(variablesTypesTest); - Collections.sort(variablesTypes); - assertTrue( - variablesTypesTest.size() == variablesTypes.size() && - variablesTypes.containsAll(variablesTypesTest) && - variablesTypesTest.containsAll(variablesTypes)); - } - - @Test - void objectCreationTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - LeafNode objectCreationTest = sourcePackage.getLeafNodes().get("ObjectCreationTest"); - - List objectsCreated = new ArrayList<>(List.of("ImplementingClass", "ImplementingClass", "ExtensionClass", "HashMap[String,TestingInterface]")); - List objectsCreatedTest = ((JavaparserLeafNode) objectCreationTest).getCreatedObjects(); - - Collections.sort(objectsCreatedTest); - Collections.sort(objectsCreated); - assertTrue( - objectsCreatedTest.size() == objectsCreated.size() - && objectsCreated.containsAll(objectsCreatedTest) - && objectsCreatedTest.containsAll(objectsCreated)); - } - - @Test - void leafNodeTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode inheritancePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - List classLeafs = new ArrayList<>(); - List interfaceLeafs = new ArrayList<>(); - classLeafs.add(inheritancePackage.getLeafNodes().get("ImplementingClass")); - classLeafs.add(inheritancePackage.getLeafNodes().get("ExtensionClass")); - interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface")); - interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface2")); - - for (LeafNode l : classLeafs) { - assertEquals(NodeType.CLASS, l.getType()); - } - for (LeafNode l : interfaceLeafs) { - assertEquals(NodeType.INTERFACE, l.getType()); - } - - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - LeafNode enumTest = sourcePackage.getLeafNodes().get("EnumTest"); - assertEquals(NodeType.ENUM, enumTest.getType()); - - LeafNode objectCreationTest = sourcePackage.getLeafNodes().get("ObjectCreationTest"); - assertEquals(NodeType.CLASS, objectCreationTest.getType()); - } -} diff --git a/src/test/java/parser/javaparser/JavaparserProjectParserTest.java b/src/test/java/parser/javaparser/JavaparserProjectParserTest.java deleted file mode 100644 index 14bc064..0000000 --- a/src/test/java/parser/javaparser/JavaparserProjectParserTest.java +++ /dev/null @@ -1,220 +0,0 @@ -package parser.javaparser; - -import org.junit.jupiter.api.Test; -import parser.factory.Parser; -import parser.factory.ParserType; -import parser.factory.ProjectParserFactory; -import parser.tree.LeafNode; -import parser.tree.PackageNode; -import utils.PathConstructor; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class JavaparserProjectParserTest { - - ParserType parserType = ParserType.JAVAPARSER; - - @Test - void parsingTest() { - List sourcesSubPackages = new ArrayList<>( - Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view")) - )); - List viewsLeafNodes = new ArrayList<>( - Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view", "ChooseTemplate.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view", "LatexEditorView.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view", "MainWindow.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view", "OpeningWindow.java")) - )); - List controllersLeafNodes = new ArrayList<>( - List.of( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "LatexEditorController.java")) - )); - List strategiesLeafNodes = new ArrayList<>( - Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies", "StableVersionsStrategy.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies", "VersionsStrategy.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies", "VolatileVersionsStrategy.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies", "VersionsStrategyFactory.java")) - )); - List modelsLeafNodes = new ArrayList<>( - Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "Document.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "DocumentManager.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "VersionsManager.java")) - )); - List commandsLeafNodes = new ArrayList<>( - Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "AddLatexCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "Command.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "CommandFactory.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "CreateCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "EditCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "LoadCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "SaveCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "ChangeVersionsStrategyCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "DisableVersionsManagementCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "EnableVersionsManagementCommand.java")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands", "RollbackToPreviousVersionCommand.java")) - )); - - Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packageNodes = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - - PackageNode controllerPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller"))); - List testingLeafNodes = new ArrayList<>(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller")), controllerPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), controllerPackage.getParentNode().getPackageNodesPath()); - assertTrue(controllerPackage.isValid(), "message"); - Map subNodes = controllerPackage.getSubNodes(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), - subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))).getPackageNodesPath()); - - for (LeafNode l : controllerPackage.getLeafNodes().values()) { - testingLeafNodes.add(l.getLeafNodesPath()); - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller"))); - } - Collections.sort(testingLeafNodes); - Collections.sort(controllersLeafNodes); - assertTrue( - testingLeafNodes.size() == controllersLeafNodes.size() && - controllersLeafNodes.containsAll(testingLeafNodes) && - testingLeafNodes.containsAll(controllersLeafNodes)); - - testingLeafNodes.clear(); - - PackageNode commandsPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), commandsPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller")), commandsPackage.getParentNode().getPackageNodesPath()); - assertTrue(commandsPackage.isValid()); - subNodes = commandsPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : commandsPackage.getLeafNodes().values()) { - testingLeafNodes.add(l.getLeafNodesPath()); - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - } - Collections.sort(testingLeafNodes); - Collections.sort(commandsLeafNodes); - assertTrue( - testingLeafNodes.size() == commandsLeafNodes.size() && - commandsLeafNodes.containsAll(testingLeafNodes) && - testingLeafNodes.containsAll(commandsLeafNodes)); - - testingLeafNodes.clear(); - - PackageNode modelPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), modelPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), modelPackage.getParentNode().getPackageNodesPath()); - assertTrue(modelPackage.isValid()); - subNodes = modelPackage.getSubNodes(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies")), - subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))).getPackageNodesPath()); - for (LeafNode l : modelPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(modelsLeafNodes); - assertTrue( - testingLeafNodes.size() == modelsLeafNodes.size() && - modelsLeafNodes.containsAll(testingLeafNodes) && - testingLeafNodes.containsAll(modelsLeafNodes)); - - testingLeafNodes.clear(); - - PackageNode strategiesPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies")), strategiesPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), strategiesPackage.getParentNode().getPackageNodesPath()); - assertTrue(strategiesPackage.isValid()); - subNodes = strategiesPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : strategiesPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(strategiesLeafNodes); - assertTrue( - testingLeafNodes.size() == strategiesLeafNodes.size() && - strategiesLeafNodes.containsAll(testingLeafNodes) && - testingLeafNodes.containsAll(strategiesLeafNodes)); - - testingLeafNodes.clear(); - - PackageNode viewPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view")), viewPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), viewPackage.getParentNode().getPackageNodesPath()); - assertTrue(viewPackage.isValid()); - subNodes = viewPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : viewPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(viewsLeafNodes); - assertTrue( - testingLeafNodes.size() == viewsLeafNodes.size() && - viewsLeafNodes.containsAll(testingLeafNodes) && - testingLeafNodes.containsAll(viewsLeafNodes)); - testingLeafNodes.clear(); - - PackageNode sourcePackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), sourcePackage.getPackageNodesPath()); - assertEquals(Paths.get(""), sourcePackage.getParentNode().getPackageNodesPath()); - assertFalse(sourcePackage.isValid()); - subNodes = sourcePackage.getSubNodes(); - List testingSubPackages = new ArrayList<>(); - for (PackageNode subP : subNodes.values()) { - testingSubPackages.add(subP.getPackageNodesPath()); - } - Collections.sort(testingSubPackages); - Collections.sort(sourcesSubPackages); - assertTrue( - testingSubPackages.size() == sourcesSubPackages.size() && - sourcesSubPackages.containsAll(testingSubPackages) && - testingSubPackages.containsAll(sourcesSubPackages) - ); - assertEquals(0, sourcePackage.getLeafNodes().size()); - } - -} diff --git a/src/test/java/parser/jdt/JDTFileVisitorTest.java b/src/test/java/parser/jdt/JDTFileVisitorTest.java deleted file mode 100644 index df8d029..0000000 --- a/src/test/java/parser/jdt/JDTFileVisitorTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package parser.jdt; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import parser.factory.Parser; -import parser.factory.ParserType; -import parser.factory.ProjectParserFactory; -import parser.tree.LeafNode; -import parser.tree.NodeType; -import parser.tree.PackageNode; -import utils.PathConstructor; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Disabled -class JDTFileVisitorTest { - - ParserType parserType = ParserType.JDT; - - @Deprecated - @Test - void methodReturnTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List methodReturnTypes = new ArrayList<>(Arrays.asList("Constructor", "void")); - List methodReturnTypesTest = addLatexCommand.getMethodsReturnTypes(); - - Collections.sort(methodReturnTypesTest); - Collections.sort(methodReturnTypes); - assertTrue(methodReturnTypesTest.size() == methodReturnTypes.size() - && methodReturnTypes.containsAll(methodReturnTypesTest) - && methodReturnTypesTest.containsAll(methodReturnTypes)); - } - - @Deprecated - @Test - void methodParameterTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List methodParameterTypes = new ArrayList<>(List.of("VersionsManager")); - List methodParameterTypesTest = addLatexCommand.getMethodParameterTypes(); - - Collections.sort(methodParameterTypesTest); - Collections.sort(methodParameterTypes); - assertTrue( - methodParameterTypesTest.size() == methodParameterTypes.size() && - methodParameterTypes.containsAll(methodParameterTypesTest) && - methodParameterTypesTest.containsAll(methodParameterTypes)); - } - - @Deprecated - @Test - void fieldTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List fieldTypes = new ArrayList<>(List.of("VersionsManager")); - List fieldTypesTest = addLatexCommand.getFieldsTypes(); - - Collections.sort(fieldTypesTest); - Collections.sort(fieldTypes); - assertTrue( - fieldTypesTest.size() == fieldTypes.size() && - fieldTypes.containsAll(fieldTypesTest) && - fieldTypesTest.containsAll(fieldTypes)); - } - - @Deprecated - @Test - void leafNodeTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode inheritancePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - List classLeafs = new ArrayList<>(); - List interfaceLeafs = new ArrayList<>(); - classLeafs.add(inheritancePackage.getLeafNodes().get("ImplementingClass")); - classLeafs.add(inheritancePackage.getLeafNodes().get("ExtensionClass")); - interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface")); - interfaceLeafs.add(inheritancePackage.getLeafNodes().get("TestingInterface2")); - - for (LeafNode l : classLeafs) { - assertEquals(NodeType.CLASS, l.getType()); - } - for (LeafNode l : interfaceLeafs) { - assertEquals(NodeType.INTERFACE, l.getType()); - } - - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - LeafNode enumTest = sourcePackage.getLeafNodes().get("EnumTest"); - assertEquals(NodeType.ENUM, enumTest.getType()); - - LeafNode objectCreationTest = sourcePackage.getLeafNodes().get("ObjectCreationTest"); - assertEquals(NodeType.CLASS, objectCreationTest.getType()); - } -} - diff --git a/src/test/java/parser/jdt/JDTProjectParserTest.java b/src/test/java/parser/jdt/JDTProjectParserTest.java deleted file mode 100644 index 12301f7..0000000 --- a/src/test/java/parser/jdt/JDTProjectParserTest.java +++ /dev/null @@ -1,203 +0,0 @@ -package parser.jdt; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import parser.factory.Parser; -import parser.factory.ParserType; -import parser.factory.ProjectParserFactory; -import parser.tree.LeafNode; -import parser.tree.PackageNode; -import utils.PathConstructor; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Disabled -class JDTProjectParserTest { - - ParserType parserType = ParserType.JDT; - - @Deprecated - @Test - void parsingTest() { - List sourcesSubPackages = new ArrayList<>(Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view")))); - List viewsLeafNodes = new ArrayList<>(Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/view/ChooseTemplate.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/view/LatexEditorView.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/view/MainWindow.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/view/OpeningWindow.java") - )); - List controllersLeafNodes = new ArrayList<>(List.of( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/LatexEditorController.java") - )); - List strategiesLeafNodes = new ArrayList<>(Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/strategies/StableVersionsStrategy.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/strategies/VersionsStrategy.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/strategies/VolatileVersionsStrategy.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/strategies/VersionsStrategyFactory.java") - )); - List modelsLeafNodes = new ArrayList<>(Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/Document.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/DocumentManager.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/model/VersionsManager.java") - )); - List commandsLeafNodes = new ArrayList<>(Arrays.asList( - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/AddLatexCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/Command.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/CommandFactory.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/CreateCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/EditCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/LoadCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/SaveCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/ChangeVersionsStrategyCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/DisableVersionsManagementCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/EnableVersionsManagementCommand.java"), - Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "/src/test/resources/LatexEditor/src/controller/commands/RollbackToPreviousVersionCommand.java") - )); - Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packageNodes = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - - PackageNode controllerPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), "src/test/resources/LatexEditor/src/controller")); - List testingLeafNodes = new ArrayList<>(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), controllerPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), controllerPackage.getParentNode().getPackageNodesPath()); - assertTrue(controllerPackage.isValid(), "message"); - Map subNodes = controllerPackage.getSubNodes(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), - subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))).getPackageNodesPath()); - - for (LeafNode l : controllerPackage.getLeafNodes().values()) { - testingLeafNodes.add(l.getLeafNodesPath()); - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - } - Collections.sort(testingLeafNodes); - Collections.sort(controllersLeafNodes); - assertTrue(testingLeafNodes.size() == controllersLeafNodes.size() - && controllersLeafNodes.containsAll(testingLeafNodes) - && testingLeafNodes.containsAll(controllersLeafNodes)); - testingLeafNodes.clear(); - - PackageNode commandsPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), commandsPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands")), commandsPackage.getParentNode().getPackageNodesPath()); - assertTrue(commandsPackage.isValid()); - subNodes = commandsPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : commandsPackage.getLeafNodes().values()) { - testingLeafNodes.add(l.getLeafNodesPath()); - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - } - Collections.sort(testingLeafNodes); - Collections.sort(commandsLeafNodes); - assertTrue(testingLeafNodes.size() == commandsLeafNodes.size() - && commandsLeafNodes.containsAll(testingLeafNodes) - && testingLeafNodes.containsAll(commandsLeafNodes)); - testingLeafNodes.clear(); - - PackageNode modelPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), modelPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), modelPackage.getParentNode().getPackageNodesPath()); - assertTrue(modelPackage.isValid()); - subNodes = modelPackage.getSubNodes(); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies")), - subNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))).getPackageNodesPath()); - for (LeafNode l : modelPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(modelsLeafNodes); - assertTrue(testingLeafNodes.size() == modelsLeafNodes.size() - && modelsLeafNodes.containsAll(testingLeafNodes) - && testingLeafNodes.containsAll(modelsLeafNodes)); - testingLeafNodes.clear(); - - PackageNode strategiesPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies")), strategiesPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model")), strategiesPackage.getParentNode().getPackageNodesPath()); - assertTrue(strategiesPackage.isValid()); - subNodes = strategiesPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : strategiesPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "model", "strategies"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(strategiesLeafNodes); - assertTrue(testingLeafNodes.size() == strategiesLeafNodes.size() - && strategiesLeafNodes.containsAll(testingLeafNodes) - && testingLeafNodes.containsAll(strategiesLeafNodes)); - testingLeafNodes.clear(); - - PackageNode viewPackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view")), viewPackage.getPackageNodesPath()); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), viewPackage.getParentNode().getPackageNodesPath()); - assertTrue(viewPackage.isValid()); - subNodes = viewPackage.getSubNodes(); - assertEquals(0, subNodes.size()); - for (LeafNode l : viewPackage.getLeafNodes().values()) { - assertEquals(l.getParentNode().getPackageNodesPath(), Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "view"))); - testingLeafNodes.add(l.getLeafNodesPath()); - } - Collections.sort(testingLeafNodes); - Collections.sort(viewsLeafNodes); - assertTrue(testingLeafNodes.size() == viewsLeafNodes.size() - && viewsLeafNodes.containsAll(testingLeafNodes) - && testingLeafNodes.containsAll(viewsLeafNodes)); - testingLeafNodes.clear(); - - PackageNode sourcePackage = packageNodes.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - assertEquals(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), - File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src")), sourcePackage.getPackageNodesPath()); - assertEquals(Paths.get(""), sourcePackage.getParentNode().getPackageNodesPath()); - assertFalse(sourcePackage.isValid()); - subNodes = sourcePackage.getSubNodes(); - List testingSubPackages = new ArrayList<>(); - for (PackageNode subP : subNodes.values()) { - testingSubPackages.add(subP.getPackageNodesPath()); - } - Collections.sort(testingSubPackages); - Collections.sort(sourcesSubPackages); - assertTrue(testingSubPackages.size() == sourcesSubPackages.size() - && sourcesSubPackages.containsAll(testingSubPackages) - && testingSubPackages.containsAll(sourcesSubPackages)); - assertEquals(0, sourcePackage.getLeafNodes().size()); - } -} diff --git a/src/test/java/parser/jdt/JDTRelationshipIdentifierTest.java b/src/test/java/parser/jdt/JDTRelationshipIdentifierTest.java deleted file mode 100644 index 99e7145..0000000 --- a/src/test/java/parser/jdt/JDTRelationshipIdentifierTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package parser.jdt; - -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import parser.factory.Parser; -import parser.factory.ParserType; -import parser.factory.ProjectParserFactory; -import parser.tree.LeafNode; -import parser.tree.NodeType; -import parser.tree.PackageNode; -import parser.tree.Relationship; -import parser.tree.RelationshipType; -import utils.PathConstructor; - -import java.io.File; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Disabled -class JDTRelationshipIdentifierTest { - - ParserType parserType = ParserType.JDT; - - @Deprecated - @Test - void getFieldAndMethodTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - List methodReturnTypes = new ArrayList<>(Arrays.asList("Constructor", "void")); - List fieldTypes = new ArrayList<>(List.of("VersionsManager")); - List methodParameterTypes = new ArrayList<>(List.of("VersionsManager")); - - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - - List methodReturnTypesTest; - List fieldTypesTest; - List methodParameterTypesTest; - methodParameterTypesTest = addLatexCommand.getMethodParameterTypes(); - fieldTypesTest = addLatexCommand.getFieldsTypes(); - methodReturnTypesTest = addLatexCommand.getMethodsReturnTypes(); - Collections.sort(methodReturnTypesTest); - Collections.sort(methodReturnTypes); - assertTrue(methodReturnTypesTest.size() == methodReturnTypes.size() - && methodReturnTypes.containsAll(methodReturnTypesTest) - && methodReturnTypesTest.containsAll(methodReturnTypes)); - Collections.sort(fieldTypesTest); - Collections.sort(fieldTypes); - assertTrue(fieldTypesTest.size() == fieldTypes.size() - && fieldTypes.containsAll(fieldTypesTest) - && fieldTypesTest.containsAll(fieldTypes)); - Collections.sort(methodParameterTypesTest); - Collections.sort(methodParameterTypes); - assertTrue(methodParameterTypesTest.size() == methodParameterTypes.size() - && methodParameterTypes.containsAll(methodParameterTypesTest) - && methodParameterTypesTest.containsAll(methodParameterTypes)); - } - - @Deprecated - @Test - void leafNodeRelationshipsTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - PackageNode commandPackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - - LeafNode addLatexCommand = commandPackage.getLeafNodes().get("AddLatexCommand"); - List> nodeRelationships = addLatexCommand.getLeafNodeRelationships(); - - boolean foundObligatoryRelationship = false; - int relationshipCounter = 0; - for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("AddLatexCommand")) && (relationship.endingNode().getName().equals("VersionsManager"))) { - if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) { - foundObligatoryRelationship = true; - } else { - foundObligatoryRelationship = relationship.relationshipType().equals(RelationshipType.ASSOCIATION); - } - } else if ((relationship.startingNode().getName().equals("AddLatexCommand")) && (relationship.endingNode().getName().equals("Command"))) { - assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else { - foundObligatoryRelationship = false; - } - relationshipCounter++; - } - assertEquals(3, relationshipCounter); - assertTrue(foundObligatoryRelationship); - assertEquals(NodeType.CLASS, addLatexCommand.getType()); - - LeafNode commandFactory = commandPackage.getLeafNodes().get("CommandFactory"); - nodeRelationships = commandFactory.getLeafNodeRelationships(); - - boolean foundObligatoryRelationships_CommandFactoryToVersionsManager = false; - boolean foundObligatoryRelationships_CommandFactoryToCommand = false; - relationshipCounter = 0; - for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("CommandFactory")) && (relationship.endingNode().getName().equals("VersionsManager"))) { - if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY) || (relationship.relationshipType().equals(RelationshipType.ASSOCIATION))) { - foundObligatoryRelationships_CommandFactoryToVersionsManager = true; - } - } else if ((relationship.startingNode().getName().equals("CommandFactory")) && (relationship.endingNode().getName().equals("Command"))) { - if (relationship.relationshipType().equals(RelationshipType.DEPENDENCY)) - foundObligatoryRelationships_CommandFactoryToCommand = true; - } - relationshipCounter++; - } - assertTrue(foundObligatoryRelationships_CommandFactoryToVersionsManager); - assertTrue(foundObligatoryRelationships_CommandFactoryToCommand); - assertEquals(4, relationshipCounter); - assertEquals(NodeType.CLASS, commandFactory.getType()); - } - - @Deprecated - @Test - void leafNodeInheritanceRelationshipTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - - LeafNode implementingClassLeaf = sourcePackage.getLeafNodes().get("ImplementingClass"); - List> nodeRelationships = implementingClassLeaf.getLeafNodeRelationships(); - - boolean foundObligatoryRelationship = false; - int relationshipCounter = 0; - for (Relationship relationship : nodeRelationships) { - if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("TestingInterface2"))) { - assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("ExtensionClass"))) { - assertEquals(RelationshipType.EXTENSION, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("ImplementingClass")) && (relationship.endingNode().getName().equals("TestingInterface"))) { - assertEquals(RelationshipType.IMPLEMENTATION, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else { - foundObligatoryRelationship = false; - } - relationshipCounter++; - } - - assertTrue(foundObligatoryRelationship); - assertEquals(3, relationshipCounter); - assertEquals(NodeType.CLASS, implementingClassLeaf.getType()); - } - - @Deprecated - @Test - - void packageNodeRelationshipsTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src"))); - - PackageNode commands = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - List> packageRelationships = commands.getPackageNodeRelationships(); - - boolean foundObligatoryRelationship = false; - int relationshipCounter = 0; - for (Relationship relationship : packageRelationships) { - if ((relationship.startingNode().getName().equals("src.controller.commands")) && (relationship.endingNode().getName().equals("src.model"))) { - assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else { - foundObligatoryRelationship = false; - } - relationshipCounter++; - } - - assertTrue(foundObligatoryRelationship); - assertEquals(1, relationshipCounter); - assertEquals(NodeType.PACKAGE, commands.getType()); - - PackageNode controller = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "LatexEditor", "src", "controller", "commands"))); - packageRelationships = controller.getPackageNodeRelationships(); - - foundObligatoryRelationship = false; - relationshipCounter = 0; - for (Relationship relationship : packageRelationships) { - if ((relationship.startingNode().getName().equals("src.controller")) && (relationship.endingNode().getName().equals("src.model"))) { - assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else if ((relationship.startingNode().getName().equals("src.controller")) && (relationship.endingNode().getName().equals("src.controller.commands"))) { - assertEquals(RelationshipType.DEPENDENCY, relationship.relationshipType()); - foundObligatoryRelationship = true; - } else { - foundObligatoryRelationship = false; - } - relationshipCounter++; - } - - assertTrue(foundObligatoryRelationship); - assertEquals(2, relationshipCounter); - assertEquals(NodeType.PACKAGE, commands.getType()); - } - - @Deprecated - @Test - void leafNodeTypesTest() { - Parser parser = ProjectParserFactory.createProjectParser(parserType); - Map packages = parser.parseSourcePackage(Paths.get(PathConstructor.getCurrentPath() + File.separator + PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - PackageNode sourcePackage = packages.get(Paths.get(PathConstructor.getCurrentPath().normalize().toString(), PathConstructor.constructPath("src", "test", "resources", "ParserTesting"))); - - List classLeafs = new ArrayList<>(); - List interfaceLeafs = new ArrayList<>(); - classLeafs.add(sourcePackage.getLeafNodes().get("ImplementingClass")); - classLeafs.add(sourcePackage.getLeafNodes().get("ExtensionClass")); - interfaceLeafs.add(sourcePackage.getLeafNodes().get("TestingInterface")); - interfaceLeafs.add(sourcePackage.getLeafNodes().get("TestingInterface2")); - for (LeafNode l : classLeafs) { - assertEquals(NodeType.CLASS, l.getType()); - } - for (LeafNode l : interfaceLeafs) { - assertEquals(NodeType.INTERFACE, l.getType()); - } - } -} - diff --git a/src/test/resources/BicycleRaceV01/src/bicycleBody/Bicycle.java b/src/test/resources/BicycleRaceV01/src/bicycleBody/Bicycle.java index 6a45bcc..94e62de 100644 --- a/src/test/resources/BicycleRaceV01/src/bicycleBody/Bicycle.java +++ b/src/test/resources/BicycleRaceV01/src/bicycleBody/Bicycle.java @@ -67,7 +67,7 @@ public double setPedaling(double rate){ */ public double setBraking(double force){ velocity -= breaks.getSpeedReduction(force); - if(velocity < 0) + if (velocity < 0) velocity = 0; return velocity; } diff --git a/src/test/resources/ParserTesting/EnumSample.java b/src/test/resources/ParserTesting/EnumSample.java new file mode 100644 index 0000000..d058609 --- /dev/null +++ b/src/test/resources/ParserTesting/EnumSample.java @@ -0,0 +1,2 @@ + +public enum EnumSample { } \ No newline at end of file diff --git a/src/test/resources/ParserTesting/EnumTest.java b/src/test/resources/ParserTesting/EnumTest.java deleted file mode 100644 index 8839993..0000000 --- a/src/test/resources/ParserTesting/EnumTest.java +++ /dev/null @@ -1,4 +0,0 @@ - -public enum EnumTest { - -} \ No newline at end of file diff --git a/src/test/resources/ParserTesting/InnerClassSample.java b/src/test/resources/ParserTesting/InnerClassSample.java new file mode 100644 index 0000000..e249006 --- /dev/null +++ b/src/test/resources/ParserTesting/InnerClassSample.java @@ -0,0 +1,9 @@ + +public class InnerClassSample extends ExtensionClass { + + private class InnerClass implements TestingInterface { + private ObjectCreationSample e = new ObjectCreationSample(); + } + + public record RecordSample(ObjectCreationSample objectCreationSample) {} +} \ No newline at end of file diff --git a/src/test/resources/ParserTesting/ObjectCreationTest.java b/src/test/resources/ParserTesting/ObjectCreationSample.java similarity index 80% rename from src/test/resources/ParserTesting/ObjectCreationTest.java rename to src/test/resources/ParserTesting/ObjectCreationSample.java index 0fc0491..a8c56f2 100644 --- a/src/test/resources/ParserTesting/ObjectCreationTest.java +++ b/src/test/resources/ParserTesting/ObjectCreationSample.java @@ -1,9 +1,9 @@ import java.util.HashMap; -public class ObjectCreationTest { +public class ObjectCreationSample { private ExtensionClass extensionClass; - public ObjectCreationTest() { + public ObjectCreationSample() { TestingInterface implementingClass = new ImplementingClass(); extensionClass = new ExtensionClass(); } @@ -11,14 +11,11 @@ public ObjectCreationTest() { private void createObject() { new ImplementingClass(); } - private void createMapWithObject() { new HashMap(); new ExtensionClass(); new ImplementingClass(); } + private enum EnumSample { } - private enum EnumTest { - - } } \ No newline at end of file