ClassModel(ASTNodeFactory astNodeFactory, String className, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<TypeModel> innerTypes, List<ASTNode> modifiers) { groovism = provide(); this.className = className; this.packageDeclaration = packageDeclaration; this.fields = fieldDeclarations(fields); this.methods = unmodifiableList(new LinkedList<>(methods)); this.modifiers = unmodifiableList(new LinkedList<>(modifiers)); this.imports = imports; this.innerTypes = unmodifiableList(new LinkedList<>(innerTypes)); if (isTestClass(methods)) { this.superClassType = Optional.of(astNodeFactory.simpleType(Specification.class.getSimpleName())); imports.add(0, astNodeFactory.importDeclaration(Specification.class)); } else { this.superClassType = Optional.ofNullable(superClassType); } }
InterfaceModel(String typeName, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<ASTNode> modifiers) { groovism = provide(); LinkedList<ImportDeclaration> importDeclarations = new LinkedList<>(imports); this.superClassType = Optional.ofNullable(superClassType).map(Object::toString); this.typeName = typeName; this.packageDeclaration = packageDeclaration; this.fields = unmodifiableList(new LinkedList<>(fields)); this.methods = unmodifiableList(new LinkedList<>(methods)); this.imports = unmodifiableList(importDeclarations); this.modifiers = unmodifiableList(modifiers); }
@Override public boolean visit(FieldDeclaration node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); ASTNode parent = node.getParent(); Scope scope = new Scope(cunit.getLineNumber(parent.getStartPosition()), getEndLine(parent, cunit)); TypeDeclaration dec = (TypeDeclaration) node.getParent(); String qName = dec.getName().getFullyQualifiedName(); PackageDeclaration packageDec = cunit.getPackage(); if(packageDec != null) qName = packageDec.getName().getFullyQualifiedName() + "." + qName; String type = !Modifier.isStatic(node.getModifiers()) ? qName : null; VariableTags tags = new VariableTags(varName, type, line, scope, true); variables.add(tags); } return false; }
/** * Evaluates fully qualified name of the TypeDeclaration object. */ public static String getFullName(TypeDeclaration decl) { String name = decl.getName().getIdentifier(); ASTNode parent = decl.getParent(); // resolve full name e.g.: A.B while (parent != null && parent.getClass() == TypeDeclaration.class) { name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name; parent = parent.getParent(); } // resolve fully qualified name e.g.: some.package.A.B if (decl.getRoot().getClass() == CompilationUnit.class) { CompilationUnit root = (CompilationUnit) decl.getRoot(); if (root.getPackage() != null) { PackageDeclaration pack = root.getPackage(); name = pack.getName().getFullyQualifiedName() + "." + name; } } return name; }
public static StubTypeContext createStubTypeContext( ICompilationUnit cu, CompilationUnit root, int focalPosition) throws CoreException { StringBuffer bufBefore = new StringBuffer(); StringBuffer bufAfter = new StringBuffer(); int introEnd = 0; PackageDeclaration pack = root.getPackage(); if (pack != null) introEnd = pack.getStartPosition() + pack.getLength(); List<ImportDeclaration> imports = root.imports(); if (imports.size() > 0) { ImportDeclaration lastImport = imports.get(imports.size() - 1); introEnd = lastImport.getStartPosition() + lastImport.getLength(); } bufBefore.append(cu.getBuffer().getText(0, introEnd)); fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types()); bufBefore.append(' '); bufAfter.insert(0, ' '); return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString()); }
private static int getNodeStartPosition(final ASTNode node) { if (node instanceof MethodDeclaration) { MethodDeclaration decl = (MethodDeclaration) node; return decl.isConstructor() ? decl.getName().getStartPosition() : decl.getReturnType2().getStartPosition(); } else if (node instanceof FieldDeclaration) { return ((FieldDeclaration) node).getType().getStartPosition(); } else if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration) node).getName().getStartPosition(); } else if (node instanceof AnnotationTypeMemberDeclaration) { return ((AnnotationTypeMemberDeclaration) node).getName().getStartPosition(); } else if (node instanceof EnumConstantDeclaration) { return ((EnumConstantDeclaration) node).getName().getStartPosition(); } else if (node instanceof PackageDeclaration) { return ((PackageDeclaration) node).getName().getStartPosition(); } /* TODO: Initializer */ return node.getStartPosition(); }
/** * Queries the fully qualified name of type defined by the source code file this * bridge was created for. * * @return The fully qualified name of the type defined by the source code file this * bridge was created for. {@code null} if there is nothing in the file this * desription applies to. */ String getFullyQualifiedName() { Validate.validState(this.compilationUnit != null, "getFullyQualifiedName may only be called after getAst was!"); // Compilation Units that don’t have exactly one type declaration at the root // level are not supported. The author knows of no compilable example of such a // compilation unit. final TypeDeclaration rootType = (TypeDeclaration) this.compilationUnit.types().get(0); if (rootType == null) { return null; } final PackageDeclaration cuPackage = this.compilationUnit.getPackage(); final String packageName; if (cuPackage == null) { packageName = ""; } else { packageName = cuPackage.getName() + "."; } return packageName + rootType.getName(); }
public static String qualifiedName(TypeDeclaration decl) { String name = decl.getName().getIdentifier(); ASTNode parent = decl.getParent(); // resolve full name e.g.: A.B while (parent != null && parent.getClass() == TypeDeclaration.class) { name = ((TypeDeclaration) parent).getName().getIdentifier() + "." + name; parent = parent.getParent(); } // resolve fully qualified name e.g.: some.package.A.B if (decl.getRoot().getClass() == CompilationUnit.class) { CompilationUnit root = (CompilationUnit) decl.getRoot(); if (root.getPackage() != null) { PackageDeclaration pack = root.getPackage(); name = pack.getName().getFullyQualifiedName() + "." + name; } } return name; }
public static StubTypeContext createStubTypeContext(ICompilationUnit cu, CompilationUnit root, int focalPosition) throws CoreException { StringBuffer bufBefore= new StringBuffer(); StringBuffer bufAfter= new StringBuffer(); int introEnd= 0; PackageDeclaration pack= root.getPackage(); if (pack != null) introEnd= pack.getStartPosition() + pack.getLength(); List<ImportDeclaration> imports= root.imports(); if (imports.size() > 0) { ImportDeclaration lastImport= imports.get(imports.size() - 1); introEnd= lastImport.getStartPosition() + lastImport.getLength(); } bufBefore.append(cu.getBuffer().getText(0, introEnd)); fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types()); bufBefore.append(' '); bufAfter.insert(0, ' '); return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString()); }
private void visitCompilationUnit(IFile file) { ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file); if (cu != null) { ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); parser.setSource(cu); parser.setFocalPosition(0); CompilationUnit root= (CompilationUnit)parser.createAST(null); PackageDeclaration packDecl= root.getPackage(); IPath packPath= file.getParent().getFullPath(); String cuName= file.getName(); if (packDecl == null) { addToMap(fSourceFolders, packPath, new Path(cuName)); } else { IPath relPath= new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/')); IPath folderPath= getFolderPath(packPath, relPath); if (folderPath != null) { addToMap(fSourceFolders, folderPath, relPath.append(cuName)); } } } }
protected ASTNode generateElementAST(ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException { //look for an existing package declaration IJavaElement[] children = getCompilationUnit().getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION && this.name.equals(children[i].getElementName())) { //equivalent package declaration already exists this.creationOccurred = false; return null; } } AST ast = this.cuAST.getAST(); PackageDeclaration pkgDeclaration = ast.newPackageDeclaration(); Name astName = ast.newName(this.name); pkgDeclaration.setName(astName); return pkgDeclaration; }
private void extractPackage(Repository _repo) throws MissingObjectException, IOException{ ObjectLoader newFile = _repo.open(this.newObjId); String newData = readStream(newFile.openStream()); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(newData.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); Hashtable<String, String> options = JavaCore.getOptions(); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED); parser.setCompilerOptions(options); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(PackageDeclaration _package){ packageName = _package.getName().getFullyQualifiedName(); return false; } }); }
@Override public boolean visit(PackageDeclaration node) { if (node.getAST().apiLevel() >= JLS3) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } for (Iterator<Annotation> it= node.annotations().iterator(); it.hasNext();) { Annotation p= it.next(); p.accept(this); this.fBuffer.append(" ");//$NON-NLS-1$ } } this.fBuffer.append("package ");//$NON-NLS-1$ node.getName().accept(this); this.fBuffer.append(";");//$NON-NLS-1$ return false; }
public boolean visit(PackageDeclaration node) { if (node.getAST().apiLevel() >= JLS3) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } for (Iterator it = node.annotations().iterator(); it.hasNext(); ) { Annotation p = (Annotation) it.next(); p.accept(this); this.buffer.append(" ");//$NON-NLS-1$ } } printIndent(); this.buffer.append("package ");//$NON-NLS-1$ node.getName().accept(this); this.buffer.append(";\n");//$NON-NLS-1$ return false; }
private String getFullyQualifiedTypeName(AbstractTypeDeclaration node) { LinkedList<String> nameParts = Lists.newLinkedList(); nameParts.add(node.getName().toString()); ASTNode parent = node.getParent(); while (!(parent instanceof CompilationUnit)) { nameParts.addFirst(((AbstractTypeDeclaration) parent).getName().toString()); parent = parent.getParent(); } // A Java file might not have a package. Hopefully all of ours do though... PackageDeclaration packageDecl = ((CompilationUnit) parent).getPackage(); if (packageDecl != null) { nameParts.addFirst(packageDecl.getName().toString()); } return Joiner.on(".").join(nameParts); }
/** * Evaluates fully qualified name of the TypeDeclaration object. */ public static String getFullName(TypeDeclaration decl) { String name = decl.getName().getIdentifier(); ASTNode parent = decl.getParent(); // resolve full name e.g.: A.B while (parent != null && parent.getClass() == TypeDeclaration.class) { name = ((TypeDeclaration)parent).getName().getIdentifier() + "." + name; parent = parent.getParent(); } // resolve fully qualified name e.g.: some.package.A.B if (decl.getRoot().getClass() == CompilationUnit.class) { CompilationUnit root = (CompilationUnit)decl.getRoot(); if (root.getPackage() != null) { PackageDeclaration pack = root.getPackage(); name = pack.getName().getFullyQualifiedName() + "." + name; } } return name; }
public JDTNodeWriter(JDTNodeWriter root, QCompilationUnit compilationUnit, QCompilationSetup compilationSetup) { this.compilationUnit = compilationUnit; this.compilationSetup = compilationSetup; if (root != null) { this.ast = root.getAST(); this.jdtCompilationUnit = root.getJDTCompilationUnit(); this.imports = root.imports; } else { this.ast = AST.newAST(AST.JLS8); this.jdtCompilationUnit = ast.newCompilationUnit(); this.imports = new ArrayList<String>(); // package PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); packageDeclaration.setName(ast.newName(compilationSetup.getBasePackage().split("\\."))); this.jdtCompilationUnit.setPackage(packageDeclaration); } }
@Nullable private String getFullyQualifiedTypeName(AbstractTypeDeclaration node) { LinkedList<String> nameParts = new LinkedList<>(); nameParts.add(node.getName().toString()); ASTNode parent = node.getParent(); while (!(parent instanceof CompilationUnit)) { if (parent instanceof AbstractTypeDeclaration) { nameParts.addFirst(((AbstractTypeDeclaration) parent).getName().toString()); parent = parent.getParent(); } else if (parent instanceof AnonymousClassDeclaration) { // If this is defined in an anonymous class, then there is no meaningful fully qualified // name. return null; } else { throw new RuntimeException("Unexpected parent " + parent + " for " + node); } } // A Java file might not have a package. Hopefully all of ours do though... PackageDeclaration packageDecl = ((CompilationUnit) parent).getPackage(); if (packageDecl != null) { nameParts.addFirst(packageDecl.getName().toString()); } return Joiner.on(".").join(nameParts); }
@Override public boolean visit(PackageDeclaration node) { //System.out.println("Found: " + node.getClass()); if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } print("module "); Writer w = new StringWriter(); pushWriter(w); node.getName().accept(this); popWriter(); packageName = w.toString(); println(packageName + "." + moduleName + ";"); return false; }
public static IPath guessPackageRootFragment(IProject project, boolean main) throws CoreException, FileNotFoundException { IPath folder = project.getFullPath() .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), main)); IResource interfaceFolder = ResourceManager.toResource(folder); List<IPath> paths = new ArrayList<IPath>(); if (interfaceFolder != null) { interfaceFolder.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { IJavaElement element = JavaCore.create(resource); if (element != null && element instanceof ICompilationUnit) { try { ICompilationUnit cu = (ICompilationUnit) element; CompilationUnit ast = parse(cu); ast.accept(new ASTVisitor() { public boolean visit(PackageDeclaration node) { PackageDeclaration decl = (PackageDeclaration) node; String pkgname = decl.getName().getFullyQualifiedName(); int sizePath = pkgname.split("\\.").length; paths.add(resource.getParent().getFullPath().removeLastSegments(sizePath)); return false; } }); } catch (Exception e) { ResourceManager.logException(e); } } return true; } }); } if (paths.size() == 0) return null; return paths.get(0); }
/** * @param cu * @param rewrite * @param ast * @param pkgDeclaration */ private static void addPackageDeclaration(CompilationUnit cu, ASTRewrite rewrite, AST ast, String[] pkgDeclaration) { PackageDeclaration packageDeclaration = ast.newPackageDeclaration(); Name name = ast.newName(pkgDeclaration); packageDeclaration.setName(name); rewrite.set(cu, CompilationUnit.PACKAGE_PROPERTY, packageDeclaration, null); }
protected void processCompilationUnit(String sourceFilePath, char[] fileContent, CompilationUnit compilationUnit, SDModel model) { PackageDeclaration packageDeclaration = compilationUnit.getPackage(); String packageName = ""; if (packageDeclaration != null) { packageName = packageDeclaration.getName().getFullyQualifiedName(); } String packagePath = packageName.replace('.', '/'); String sourceFolder = "/"; if (sourceFilePath.contains(packagePath)) { sourceFolder = sourceFilePath.substring(0, sourceFilePath.indexOf(packagePath)); } // RastNode nCompUnit = model.createCompilationUnit(packageName, sourceFolder, sourceFilePath, compilationUnit); BindingsRecoveryAstVisitor visitor = new BindingsRecoveryAstVisitor(model, compilationUnit, sourceFilePath, fileContent, packageName, postProcessReferences, postProcessSupertypes); compilationUnit.accept(visitor); }
protected void processCompilationUnit(String sourceFilePath, char[] fileContent, CompilationUnit compilationUnit, SDModel.Snapshot model) { PackageDeclaration packageDeclaration = compilationUnit.getPackage(); String packageName = ""; if (packageDeclaration != null) { packageName = packageDeclaration.getName().getFullyQualifiedName(); } String packagePath = packageName.replace('.', '/'); String sourceFolder = "/"; if (sourceFilePath.contains(packagePath)) { sourceFolder = sourceFilePath.substring(0, sourceFilePath.indexOf(packagePath)); } SDPackage sdPackage = model.getOrCreatePackage(packageName, sourceFolder); BindingsRecoveryAstVisitor visitor = new BindingsRecoveryAstVisitor(model, sourceFilePath, fileContent, sdPackage, postProcessReferences, postProcessSupertypes, postProcessClientCode, srbForTypes, srbForMethods, srbForAttributes); compilationUnit.accept(visitor); }
public boolean visit(PackageDeclaration node) { try { facts.add(Fact.makePackageFact(node.getName().toString())); } catch (Exception e) { System.err.println("Cannot resolve bindings for package " + node.getName().toString()); } return false; }
/** * Adds copyright header to the compilation unit * * @param compilationUnit * compilation unit affected * @return compilation unit change */ public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) { final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement(); change = new CompilationUnitChange(ADD_COPYRIGHT, unit); rewriter = ASTRewrite.create(compilationUnit.getAST()); final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(), PackageDeclaration.ANNOTATIONS_PROPERTY); final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR, ASTNode.BLOCK_COMMENT); listRewrite.insertFirst(placeHolder, null); rewriteCompilationUnit(unit, getNewUnitSource(unit, null)); return change; }
/** * Checks whether {@link CompilationUnit} has copyright header * * @param compilationUnit * checked compilation unit * @return true if {@link CompilationUnit} has copyright header */ public boolean hasCopyrightsComment(final CompilationUnit compilationUnit) { final List<Comment> comments = getCommentList(compilationUnit); boolean hasCopyrights = false; if (!comments.isEmpty()) { final PackageDeclaration packageNode = compilationUnit.getPackage(); final boolean commentBeforePackage = comments.get(0).getStartPosition() <= packageNode.getStartPosition(); final boolean hasJavaDoc = packageNode.getJavadoc() != null; hasCopyrights = commentBeforePackage || hasJavaDoc; } return hasCopyrights; }
public static String getPackageName(IJavaProject javaProject, String fileContent) { if (fileContent == null) { return ""; } //TODO probably not the most efficient way to get the package name as this reads the whole file; char[] source = fileContent.toCharArray(); ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(javaProject); parser.setIgnoreMethodBodies(true); parser.setSource(source); CompilationUnit ast = (CompilationUnit) parser.createAST(null); PackageDeclaration pkg = ast.getPackage(); return (pkg == null || pkg.getName() == null)?"":pkg.getName().getFullyQualifiedName(); }
@Override public void endVisit(PackageDeclaration node) { if (skipNode(node)) { return; } assignFlowInfo(node, node.getName()); }
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) { CompilationUnit cu= createAST(element, cuSource); if (cu != null) { PackageDeclaration packDecl= cu.getPackage(); if (packDecl != null) { return packDecl.getJavadoc(); } } return null; }
public boolean visit(PackageDeclaration node) { try { this.facts.add(Fact.makePackageFact(node.getName().toString())); } catch (Exception e) { System.err.println("Cannot resolve bindings for package " + node.getName().toString()); } return false; }
public boolean visit(PackageDeclaration node) { try { this.facts.add(Fact.makePackageFact(node.getName().toString())); } catch (Exception localException) { System.err.println("Cannot resolve bindings for package " + node.getName().toString()); } return false; }
private void copyPackageDeclarationToDestination( IPackageDeclaration declaration, ASTRewrite targetRewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException { if (destinationCuNode.getPackage() != null) return; PackageDeclaration sourceNode = ASTNodeSearchUtil.getPackageDeclarationNode(declaration, sourceCuNode); PackageDeclaration copiedNode = (PackageDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode); targetRewrite.set(destinationCuNode, CompilationUnit.PACKAGE_PROPERTY, copiedNode, null); }
private static Javadoc getPackageJavadocNode(IJavaElement element, String cuSource) { CompilationUnit cu = createAST(element, cuSource); if (cu != null) { PackageDeclaration packDecl = cu.getPackage(); if (packDecl != null) { return packDecl.getJavadoc(); } } return null; }
private final int getNodeFirstLeadingCommentIndex(final ASTNode node) { if (node instanceof PackageDeclaration) { if (commentsVisited.length > 0) { final Comment comment = (Comment) comments.get(0); if (comment.getStartPosition() + comment.getLength() <= ((PackageDeclaration) node).getName() .getStartPosition()) { return 0; } } return -1; } else { return cu.firstLeadingCommentIndex(node); } }
@Override public ModelId getModelOf(Class<?> element, ElementExporter elementExporter) throws ElementExportationException { try { Package ownPackage = element.getPackage(); if (ownPackage.getAnnotation(Model.class) != null) { return new ModelIdImpl(ownPackage.getName()); } String ownPackageName = ownPackage.getName(); IJavaProject javaProject = ProjectUtils.findJavaProject(elementExporter.getSourceProjectName()); Stream<ICompilationUnit> stream = PackageUtils.findAllPackageFragmentsAsStream(javaProject) .filter(p -> ownPackageName.startsWith(p.getElementName() + ".")) .map(pf -> pf.getCompilationUnit(PackageUtils.PACKAGE_INFO)).filter(ICompilationUnit::exists); String topPackageName = Stream.of(SharedUtils.parseICompilationUnitStream(stream, javaProject)) .map(CompilationUnit::getPackage).filter(Objects::nonNull).map(PackageDeclaration::resolveBinding) .filter(Objects::nonNull).filter(pb -> ModelUtils.findModelNameInTopPackage(pb).isPresent()) .map(IPackageBinding::getName).findFirst().get(); return new ModelIdImpl(topPackageName); } catch (NotFoundException | JavaModelException | IOException | NoSuchElementException e) { e.printStackTrace(); throw new ElementExportationException(); } }