private CompilationUnit getCompilationUnit(SourceFile sourceFile) { CompilationUnit compilationUnit; if (Files.exists(sourceFile.getOutputPath())) { try { compilationUnit = JavaParser.parse(sourceFile.getOutputPath().toFile()); } catch (Throwable t) { throw new RuntimeException(t); } } else { compilationUnit = new CompilationUnit(); compilationUnit.setComment( new LineComment(" Generated by GraphWalker (http://www.graphwalker.org)")); if (!"".equals(sourceFile.getPackageName())) { compilationUnit.setPackage(createPackageDeclaration(sourceFile)); } compilationUnit.setImports( Arrays.asList( new ImportDeclaration( new NameExpr("org.graphwalker.java.annotation.Model"), false, false), new ImportDeclaration( new NameExpr("org.graphwalker.java.annotation.Vertex"), false, false), new ImportDeclaration( new NameExpr("org.graphwalker.java.annotation.Edge"), false, false))); ASTHelper.addTypeDeclaration(compilationUnit, getInterfaceName(sourceFile)); } return compilationUnit; }
private static void write(ContextFactory factory, SourceFile file) { try { RuntimeModel model = factory.create(file.getInputPath()).getModel(); String source = generator.generate(file, model); Files.createDirectories(file.getOutputPath().getParent()); Files.write( file.getOutputPath(), source.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (Throwable t) { throw new CodeGeneratorException(t); } }
private ClassOrInterfaceDeclaration getInterfaceName(SourceFile sourceFile) { ClassOrInterfaceDeclaration classOrInterfaceDeclaration = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, sourceFile.getFileName()); List<MemberValuePair> memberValuePairs = new ArrayList<>(); memberValuePairs.add( new MemberValuePair( "file", new StringLiteralExpr( sourceFile.getRelativePath().toString().replace(File.separator, "/")))); List<AnnotationExpr> annotations = new ArrayList<>(); annotations.add(new NormalAnnotationExpr(ASTHelper.createNameExpr("Model"), memberValuePairs)); classOrInterfaceDeclaration.setAnnotations(annotations); classOrInterfaceDeclaration.setInterface(true); return classOrInterfaceDeclaration; }
private PackageDeclaration createPackageDeclaration(SourceFile sourceFile) { return new PackageDeclaration(ASTHelper.createNameExpr(sourceFile.getPackageName())); }