com.github.javaparser.ast.Node Java Examples
The following examples show how to use
com.github.javaparser.ast.Node.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ASTHelper.java From stategen with GNU Affero General Public License v3.0 | 7 votes |
/** * Gets the type index. * * @param <N> the number type * @param container the container * @param clazz the clazz * @return the type index */ static <N extends Node> Integer getTypeIndex(Node container, Class<N> clazz) { List<Node> children = container.getChildNodes(); if (CollectionUtil.isNotEmpty(children)) { for (int i = 0; i < children.size(); i++) { Node child = children.get(i); if (clazz.isInstance(child)) { return i; } Integer temIdx = getTypeIndex(child, clazz); if (temIdx != null) return temIdx; } } return null; }
Example #2
Source File: ImpSort.java From impsort-maven-plugin with Apache License 2.0 | 7 votes |
private static Set<String> tokensInUse(CompilationUnit unit) { // Extract tokens from the java code: Stream<Node> packageDecl = unit.getPackageDeclaration().isPresent() ? Stream.of(unit.getPackageDeclaration().get()).map(PackageDeclaration::getAnnotations) .flatMap(NodeList::stream) : Stream.empty(); Stream<String> typesInCode = Stream.concat(packageDecl, unit.getTypes().stream()) .map(Node::getTokenRange).filter(Optional::isPresent).map(Optional::get) .filter(r -> r != TokenRange.INVALID).flatMap(r -> { // get all JavaTokens as strings from each range return StreamSupport.stream(r.spliterator(), false); }).map(JavaToken::asString); // Extract referenced class names from parsed javadoc comments: Stream<String> typesInJavadocs = unit.getAllComments().stream() .filter(c -> c instanceof JavadocComment).map(JavadocComment.class::cast) .map(JavadocComment::parse).flatMap(ImpSort::parseJavadoc); return Stream.concat(typesInCode, typesInJavadocs) .filter(t -> t != null && !t.isEmpty() && Character.isJavaIdentifierStart(t.charAt(0))) .collect(Collectors.toSet()); }
Example #3
Source File: SourceCode.java From Recaf with MIT License | 6 votes |
/** * Returns the AST node at the given position. * The child-most node may not be returned if the parent is better suited for contextual * purposes. * * @param line * Cursor line. * @param column * Cursor column. * * @return JavaParser AST node at the given position in the source code. */ public Node getNodeAt(int line, int column) { return getNodeAt(line, column, unit.findRootNode(), node -> { // We want to know more about this type, don't resolve down to the lowest AST // type... the parent has more data and is essentially just a wrapper around SimpleName. if (node instanceof SimpleName) return false; // Verify the node range can be accessed if (!node.getBegin().isPresent() || !node.getEnd().isPresent()) return false; // Same as above, we want to return the node with actual context. if (node instanceof NameExpr) return false; // Should be fine return true; }); }
Example #4
Source File: PrettyPrintVisitor.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
private void printOrphanCommentsEnding(final Node node) { List<Node> everything = new LinkedList<>(); everything.addAll(node.getChildNodes()); sortByBeginPosition(everything); if (everything.isEmpty()) { return; } int commentsAtEnd = 0; boolean findingComments = true; while (findingComments && commentsAtEnd < everything.size()) { Node last = everything.get(everything.size() - 1 - commentsAtEnd); findingComments = (last instanceof Comment); if (findingComments) { commentsAtEnd++; } } for (int i = 0; i < commentsAtEnd; i++) { everything.get(everything.size() - commentsAtEnd + i).accept(this, null); } }
Example #5
Source File: RequestMappingHelper.java From apigcc with MIT License | 6 votes |
/** * 判断是否为Rest接口 * @param n * @return */ public static boolean isRest(MethodDeclaration n){ if(n.isAnnotationPresent(ANNOTATION_RESPONSE_BODY)){ return true; } Optional<Node> parentOptional = n.getParentNode(); if(parentOptional.isPresent()){ Node parentNode = parentOptional.get(); if(parentNode instanceof ClassOrInterfaceDeclaration){ if (((ClassOrInterfaceDeclaration) parentNode).isAnnotationPresent(SpringParser.ANNOTATION_REST_CONTROLLER)) { return true; } } } return false; }
Example #6
Source File: ASTHelper.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
/** * Gets the field declaration map. * * @param <T> the generic type * @param node the class declaration * @param type the type * @return the field declaration map */ static <T extends BodyDeclaration> Map<String, T> getBodyDeclarationMap(Node node, Class<T> type) { List<Node> children = node.getChildNodes(); if (CollectionUtil.isEmpty(children)) { return new HashMap<String, T>(0); } Map<String, T> bodyMap = new CaseInsensitiveHashMap<T>(children.size()); List<T> bodyDeclarations = getNodesByType(node, type); for (T bodyDeclaration : bodyDeclarations) { if (bodyDeclaration instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration; VariableDeclarator variableDeclaratorId = getOneNodesByType(fieldDeclaration, VariableDeclarator.class); bodyMap.put(variableDeclaratorId.getName().toString(), bodyDeclaration); } else if (bodyDeclaration instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration; bodyMap.put(methodDeclaration.getNameAsString(), bodyDeclaration); } } return bodyMap; }
Example #7
Source File: MethodBoundaryExtractor.java From scott with MIT License | 6 votes |
private boolean isInTheCorrectClass(MethodDeclaration methodDeclaration) { Node n = methodDeclaration; String containingClassName = ""; while (n != null) { if (n instanceof ClassOrInterfaceDeclaration) { ClassOrInterfaceDeclaration c = (ClassOrInterfaceDeclaration) n; containingClassName = c.getName() + "$" + containingClassName; } Optional<Node> no = n.getParentNode(); if (no.isEmpty()) { n = null; } else { n = no.get(); } } containingClassName = containingClassName.substring(0, containingClassName.length() - 1); return containingClassName.equals(className); }
Example #8
Source File: SourceCode.java From Recaf with MIT License | 6 votes |
private Node getNodeAt(int line, int column, Node root, Predicate<Node> filter) { if (!filter.test(root)) return null; // Check cursor is in bounds // We won't instantly return null because the root range may be SMALLER than // the range of children. This is really stupid IMO but thats how JavaParser is... boolean bounds = true; Position cursor = Position.pos(line, column); if (cursor.isBefore(root.getBegin().get()) || cursor.isAfter(root.getEnd().get())) bounds = false; // Iterate over children, return non-null child for (Node child : root.getChildNodes()) { Node ret = getNodeAt(line, column, child, filter); if (ret != null) return ret; } // If we're not in bounds and none of our children are THEN we assume this node is bad. if (!bounds) return null; // In bounds so we're good! return root; }
Example #9
Source File: JavaParserUtil.java From Recaf with MIT License | 6 votes |
/** * @param code * Code wrapper. * @param pos * Position of caret. * * @return Node of supported type at position. */ private static Node getSelectedNode(SourceCode code, TwoDimensional.Position pos) { // Abort if no analyzed code to parse if (code == null) return null; // Get node at row/column Node node = code.getVerboseNodeAt(pos.getMajor() + 1, pos.getMinor()); // Go up a level until node type is supported while(node != null) { if(node instanceof Resolvable || node instanceof InitializerDeclaration) break; Optional<Node> parent = node.getParentNode(); if(!parent.isPresent()) break; node = parent.get(); } return node; }
Example #10
Source File: SourceCodeTest.java From Recaf with MIT License | 6 votes |
@Test public void testFieldResolve() { // Enable advanced resolving workspace.analyzeSources(); // Line 7: Two tabs then this: // // Scanner scanner = new Scanner(System.in); // SourceCode code = resource.getClassSource("Start"); Node node = code.getNodeAt(7, 34); assertTrue(node instanceof FieldAccessExpr); FieldAccessExpr fieldExpr = (FieldAccessExpr) node; ResolvedFieldDeclaration dec = (ResolvedFieldDeclaration) fieldExpr.resolve(); assertEquals("java/lang/System", getOwner(dec)); assertEquals("in", dec.getName()); assertEquals("Ljava/io/InputStream;", getDescriptor(dec)); }
Example #11
Source File: SourceCodeTest.java From Recaf with MIT License | 6 votes |
@Test public void testMethodResolve() { // Enable advanced resolving workspace.analyzeSources(); // Line 18: Three tabs then this: // // return new Parenthesis(i).accept(expression); // SourceCode code = resource.getClassSource("calc/Calculator"); Node node = code.getNodeAt(18, 33); assertTrue(node instanceof MethodCallExpr); MethodCallExpr callExpr = (MethodCallExpr) node; ResolvedMethodDeclaration dec = callExpr.resolve(); assertEquals("calc/Parenthesis", getOwner(dec)); assertEquals("accept", dec.getName()); assertEquals("(Ljava/lang/String;)D", getDescriptor(dec)); // node = code.getNodeAt(44, 16); assertTrue(node instanceof MethodCallExpr); callExpr = (MethodCallExpr) node; dec = callExpr.resolve(); assertEquals("java/io/PrintStream", getOwner(dec)); assertEquals("println", dec.getName()); assertEquals("(Ljava/lang/String;)V", getDescriptor(dec)); }
Example #12
Source File: FinalRClassBuilder.java From Briefness with Apache License 2.0 | 6 votes |
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception { CompilationUnit compilationUnit = JavaParser.parse(rFile); TypeDeclaration resourceClass = compilationUnit.getTypes().get(0); TypeSpec.Builder result = TypeSpec.classBuilder(className) .addModifiers(PUBLIC, FINAL); for (Node node : resourceClass.getChildNodes()) { if (node instanceof ClassOrInterfaceDeclaration) { addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes); } } JavaFile finalR = JavaFile.builder(packageName, result.build()) .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!") .build(); finalR.writeTo(outputDir); }
Example #13
Source File: FinalRClassBuilder.java From Briefness with Apache License 2.0 | 6 votes |
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable, ClassName annotation) { String fieldName = variable.getNameAsString(); String fieldValue = variable.getInitializer() .map(Node::toString) .orElseThrow( () -> new IllegalStateException("Field " + fieldName + " missing initializer")); FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName) .addModifiers(PUBLIC, STATIC, FINAL) .initializer(fieldValue); if (annotation != null) { fieldSpecBuilder.addAnnotation(annotation); } resourceType.addField(fieldSpecBuilder.build()); }
Example #14
Source File: AnnotatedMember.java From jeddict with Apache License 2.0 | 6 votes |
static List<String> getClassNameAttributes(AnnotationExpr annotationExpr, String attributeName) { List<String> values = new ArrayList<>(); Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName); if (expOptional.isPresent()) { Expression expression = expOptional.get(); if (expression.isClassExpr()) { values.add(expression.asClassExpr().getTypeAsString()); } else if (expression.isArrayInitializerExpr()) { for (Node node : expression.asArrayInitializerExpr().getChildNodes()) { if (node instanceof ClassExpr) { values.add(((ClassExpr) node).getTypeAsString()); } else { throw new UnsupportedOperationException(); } } } else { throw new UnsupportedOperationException(); } } return values; }
Example #15
Source File: MemberExplorer.java From jeddict with Apache License 2.0 | 6 votes |
public String getDefaultValue() { String defaultValue = null; if (field != null && field.getVariables().get(0).getChildNodes().size() == 3) { Node node = field.getVariables().get(0).getChildNodes().get(2); if (node instanceof Expression) { //FieldAccessExpr, MethodCallExpr, ObjectCreationExpr defaultValue = node.toString(); Map<String, ImportDeclaration> imports = clazz.getImports(); String importList = imports.keySet() .stream() .filter(defaultValue::contains) .map(imports::get) .map(ImportDeclaration::getNameAsString) .collect(joining(" ,\n")); defaultValue = importList.isEmpty() ? defaultValue : "[\n" + importList + "\n]\n" + defaultValue; } else if (node instanceof NodeWithSimpleName) { defaultValue = ((NodeWithSimpleName) node).getNameAsString(); } else if (node instanceof LiteralStringValueExpr) { defaultValue = "'" + ((LiteralStringValueExpr) node).getValue() + "'"; } else { throw new UnsupportedOperationException(); } } return defaultValue; }
Example #16
Source File: AnnotatedMember.java From jeddict with Apache License 2.0 | 6 votes |
static List<String> getStringAttributes(AnnotationExpr annotationExpr, String attributeName) { List<String> values = new ArrayList<>(); Optional<Expression> expOptional = getAttribute(annotationExpr, attributeName); if (expOptional.isPresent()) { Expression expression = expOptional.get(); if (expression.isStringLiteralExpr()) { values.add(expression.asStringLiteralExpr().getValue()); } else if (expression.isArrayInitializerExpr()) { List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes(); for (Node node : nodes) { if (node instanceof StringLiteralExpr) { values.add(((StringLiteralExpr) node).getValue()); } else { values.add(node.toString()); } } } else { throw new UnsupportedOperationException(); } } return values; }
Example #17
Source File: MutationVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Node visit(DoStmt stmt, Void args) { if (!isValid) { return stmt; } super.visit(stmt, args); if (level.equals(CodeValidatorLevel.RELAXED)) { return stmt; } this.message = ValidationMessage.MUTATION_DO_STATEMENT; isValid = false; return stmt; }
Example #18
Source File: MutationVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Node visit(WhileStmt stmt, Void args) { if (!isValid) { return stmt; } super.visit(stmt, args); if (level.equals(CodeValidatorLevel.RELAXED)) { return stmt; } this.message = ValidationMessage.MUTATION_WHILE_STATEMENT; isValid = false; return stmt; }
Example #19
Source File: MutationVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Node visit(SwitchStmt stmt, Void args) { if (!isValid) { return stmt; } super.visit(stmt, args); if (level.equals(CodeValidatorLevel.RELAXED)) { return stmt; } this.message = ValidationMessage.MUTATION_SWITCH_STATEMENT; isValid = false; return stmt; }
Example #20
Source File: JavaParsingAtomicQueueGenerator.java From JCTools with Apache License 2.0 | 5 votes |
protected boolean isCommentPresent(Node node, String wanted) { Optional<Comment> maybeComment = node.getComment(); if (maybeComment.isPresent()) { Comment comment = maybeComment.get(); String content = comment.getContent().trim(); if (wanted.equals(content)) { return true; } } return false; }
Example #21
Source File: Nodes.java From deadcode4j with Apache License 2.0 | 5 votes |
@Nonnull public static CompilationUnit getCompilationUnit(@Nonnull Node node) { Node loopNode = node; for (; ; ) { if (CompilationUnit.class.isInstance(loopNode)) { return CompilationUnit.class.cast(loopNode); } loopNode = loopNode.getParentNode(); if (loopNode == null) { throw new RuntimeException("Couldn't locate CompilationUnit for [" + node + "]!"); } } }
Example #22
Source File: MutationVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Node visit(ClassOrInterfaceDeclaration stmt, Void args) { if (!isValid) { return stmt; } super.visit(stmt, args); this.message = ValidationMessage.MUTATION_CLASS_DECLARATION; isValid = false; return stmt; }
Example #23
Source File: Sources.java From sundrio with Apache License 2.0 | 5 votes |
public Set<ClassRef> apply(Node node) { Set<ClassRef> imports = new LinkedHashSet<ClassRef>(); if (node instanceof NamedNode) { String name = ((NamedNode)node).getName(); Node current = node; while (!(current instanceof CompilationUnit)) { current = current.getParentNode(); } CompilationUnit compilationUnit = (CompilationUnit) current; for (ImportDeclaration importDecl : compilationUnit.getImports()) { String className = null; String packageName = null; NameExpr importExpr = importDecl.getName(); if (importExpr instanceof QualifiedNameExpr) { QualifiedNameExpr qualifiedNameExpr = (QualifiedNameExpr) importExpr; className = qualifiedNameExpr.getName(); packageName = qualifiedNameExpr.getQualifier().toString(); } else if (importDecl.getName().getName().endsWith(SEPARATOR + name)) { String importName = importDecl.getName().getName(); packageName = importName.substring(0, importName.length() - name.length() -1); } if (className != null && !className.isEmpty()) { imports.add(new ClassRefBuilder().withNewDefinition().withName(className).withPackageName(packageName).and().build()); } } } return imports; }
Example #24
Source File: Sources.java From sundrio with Apache License 2.0 | 5 votes |
public String apply(Node node) { if (node instanceof NamedNode) { String name = ((NamedNode)node).getName(); Node current = node; while (!(current instanceof CompilationUnit)) { current = current.getParentNode(); } CompilationUnit compilationUnit = (CompilationUnit) current; for (ImportDeclaration importDecl : compilationUnit.getImports()) { NameExpr importExpr = importDecl.getName(); if (importExpr instanceof QualifiedNameExpr) { QualifiedNameExpr qualifiedNameExpr = (QualifiedNameExpr) importExpr; String className = qualifiedNameExpr.getName(); if (name.equals(className)) { return qualifiedNameExpr.getQualifier().toString(); } } else if (importDecl.getName().getName().endsWith(SEPARATOR + name)) { String importName = importDecl.getName().getName(); return importName.substring(0, importName.length() - name.length() -1); } } try { Class.forName(JAVA_LANG + "." + name); return JAVA_LANG; } catch (ClassNotFoundException ex) { return compilationUnit.getPackage().getPackageName(); } } return null; }
Example #25
Source File: AnnotatedMember.java From jeddict with Apache License 2.0 | 5 votes |
static Stream<AnnotationExplorer> getAnnotationAttributes(AnnotationExpr annotationExpr, String attributeName) { Stream<AnnotationExplorer> annotations = Stream.of(); Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName); if (expressionOpt.isPresent()) { Expression expression = expressionOpt.get(); if (expression.isAnnotationExpr()) { annotations = expressionOpt .map(exp -> exp.asAnnotationExpr()) .map(AnnotationExplorer::new) .map(exp -> Stream.of(exp)) .orElse(Stream.of()); } else if (expression.isArrayInitializerExpr()) { List<AnnotationExplorer> values = new ArrayList<>(); List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes(); for (Node node : nodes) { if (node instanceof AnnotationExpr) { AnnotationExplorer annotation = new AnnotationExplorer((AnnotationExpr) node); values.add(annotation); } else if (node instanceof Comment) { //ignore } else { throw new UnsupportedOperationException(); } } annotations = values.stream(); } else { throw new UnsupportedOperationException(); } } return annotations; }
Example #26
Source File: Nodes.java From deadcode4j with Apache License 2.0 | 5 votes |
@Nonnull public static String getTypeName(@Nonnull Node node) { List<Node> anonymousClasses = newArrayList(); StringBuilder buffy = new StringBuilder(); Node loopNode = node; for (; ; ) { if (ObjectCreationExpr.class.isInstance(loopNode)) { if (!isEmpty(ObjectCreationExpr.class.cast(loopNode).getAnonymousClassBody())) { anonymousClasses.add(loopNode); } } else if (TypeDeclarationStmt.class.isInstance(loopNode)) { anonymousClasses.add(loopNode); } else if (TypeDeclaration.class.isInstance(loopNode) && !TypeDeclarationStmt.class.isInstance(loopNode.getParentNode())) { TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode); prependSeparatorIfNecessary('$', buffy).insert(0, typeDeclaration.getName()); appendAnonymousClasses(anonymousClasses, typeDeclaration, buffy); } else if (CompilationUnit.class.isInstance(loopNode)) { if (buffy.length() == 0) { buffy.append("package-info"); } final CompilationUnit compilationUnit = CompilationUnit.class.cast(loopNode); if (compilationUnit.getPackage() != null) { prepend(compilationUnit.getPackage().getName(), buffy); } } loopNode = loopNode.getParentNode(); if (loopNode == null) { return buffy.toString(); } } }
Example #27
Source File: AnnotatedMember.java From jeddict with Apache License 2.0 | 5 votes |
static List<String> getEnumAttributes(AnnotationExpr annotationExpr, String attributeName) { List<String> values = emptyList(); Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName); if (expressionOpt.isPresent()) { Expression expression = expressionOpt.get(); if (expression.isFieldAccessExpr()) { values = expressionOpt .map(exp -> exp.asFieldAccessExpr()) .map(exp -> exp.getNameAsString()) .map(exp -> singletonList(exp)) .orElse(emptyList()); } else if (expression.isNameExpr()) { values = expressionOpt .map(exp -> exp.asNameExpr()) .map(exp -> exp.getNameAsString()) .map(exp -> singletonList(exp)) .orElse(emptyList()); } else if (expression.isArrayInitializerExpr()) { values = new ArrayList<>(); List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes(); for (Node node : nodes) { if (node instanceof NodeWithSimpleName) { values.add(((NodeWithSimpleName) node).getNameAsString()); } else { throw new UnsupportedOperationException(); } } } else { throw new UnsupportedOperationException(); } } return values; }
Example #28
Source File: JavaFileAnalyzer.java From deadcode4j with Apache License 2.0 | 5 votes |
@Nonnull protected final Iterable<? extends Qualifier> getTypeCandidates() { if (!allowsPartialResolving()) { return Collections.<Qualifier<? extends Node>>singleton(this); } List<Qualifier<?>> candidates = newArrayList(); for (Qualifier<?> loopQualifier = this; ; ) { candidates.add(loopQualifier); loopQualifier = loopQualifier.getScopeQualifier(); if (loopQualifier == null) { return candidates; } } }
Example #29
Source File: JavaFileAnalyzer.java From deadcode4j with Apache License 2.0 | 5 votes |
@Nonnull @Override public Optional<String> apply(@Nonnull Qualifier<?> typeReference) { Qualifier firstQualifier = typeReference.getFirstQualifier(); for (Node loopNode = typeReference.getNode(); ; ) { Optional<String> reference; if (TypeDeclaration.class.isInstance(loopNode)) { TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode); reference = resolveInnerReference(firstQualifier, singleton(typeDeclaration)); if (reference.isPresent()) { return reference; } reference = resolveInnerReference(firstQualifier, typeDeclaration.getMembers()); if (reference.isPresent()) { return reference; } } else if (CompilationUnit.class.isInstance(loopNode)) { reference = resolveInnerReference(firstQualifier, CompilationUnit.class.cast(loopNode).getTypes()); if (reference.isPresent()) { return reference; } } loopNode = loopNode.getParentNode(); if (loopNode == null) { return absent(); } } }
Example #30
Source File: ExtractUtil.java From wisdom with Apache License 2.0 | 5 votes |
/** * <p> * Extract the String value for each child of the <code>node</code> or the node itself if it does not * have children. * </p> * * <p>It removes the {@literal "}.</p> * @param node The java node which children or value to convert into a list of string. * @return list of the node children string value or singleton list with the value of the node if no children. */ public static Set<String> asStringSet(Node node){ if(node.getChildrenNodes() == null || node.getChildrenNodes().isEmpty()){ return singleton(asString(node)); } Set<String> list = new LinkedHashSet<>(node.getChildrenNodes().size()); for(Node child: node.getChildrenNodes()){ list.add(asString(child)); } return list; }