Example usage for org.eclipse.jdt.core.dom ASTNode getStructuralProperty

List of usage examples for org.eclipse.jdt.core.dom ASTNode getStructuralProperty

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom ASTNode getStructuralProperty.

Prototype

public final Object getStructuralProperty(StructuralPropertyDescriptor property) 

Source Link

Document

Returns the value of the given structural property for this node.

Usage

From source file:ast.AstNodeLocationMapper.java

License:Apache License

private static ASTNode findNearestPreviousChild(ASTNode node, int position) {
    int childAt = -1;
    ASTNode childNode = null;// ww  w . j  a  v  a 2  s .c  om
    for (Object o : node.structuralPropertiesForType()) {
        if (o instanceof ChildPropertyDescriptor) {
            ASTNode n = (ASTNode) node.getStructuralProperty((StructuralPropertyDescriptor) o);
            if (n != null) {
                int start = n.getStartPosition();
                if (start >= 0 && childAt < start && start <= position) {
                    childAt = start;
                    childNode = n;
                }
            }
        } else if (o instanceof ChildListPropertyDescriptor) {
            List<?> list = (List<?>) node.getStructuralProperty((StructuralPropertyDescriptor) o);
            for (Object e : list) {
                ASTNode n = (ASTNode) e;
                assert n != null;
                int start = n.getStartPosition();
                if (start >= 0 && childAt < start && start <= position) {
                    childAt = start;
                    childNode = n;
                }
            }
        }
    }
    return childNode;
}

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTUtil.java

License:Open Source License

/**
 * Replaces a node in an AST with another node. If the replacement is successful the original node is deleted.
 *
 * @param node The node to replace./*from  ww w  . j a  va  2  s. co  m*/
 * @param replacement The replacement node.
 * @return <code>true</code> if the node was successfully replaced.
 */
public static boolean replace(final ASTNode node, final ASTNode replacement) {
    final ASTNode parent = node.getParent();
    final StructuralPropertyDescriptor descriptor = node.getLocationInParent();
    if (descriptor != null) {
        if (descriptor.isChildProperty()) {
            parent.setStructuralProperty(descriptor, replacement);
            node.delete();
            return true;
        } else if (descriptor.isChildListProperty()) {
            @SuppressWarnings("unchecked")
            final List<ASTNode> children = (List<ASTNode>) parent.getStructuralProperty(descriptor);
            children.set(children.indexOf(node), replacement);
            node.delete();
            return true;
        }
    }
    return false;
}

From source file:ch.acanda.eclipse.pmd.java.resolution.ASTUtil.java

License:Open Source License

/**
 * Replaces a node in an AST with other nodes. If the replacement is successful the original node is deleted.
 *
 * @param node The node to replace.//w  w w .j a v a2s.c  o  m
 * @param replacement The replacement nodes.
 * @return <code>true</code> if the node was successfully replaced.
 */
public static boolean replace(final ASTNode node, final List<? extends ASTNode> replacement) {
    final ASTNode parent = node.getParent();
    final StructuralPropertyDescriptor descriptor = node.getLocationInParent();
    if (descriptor != null && descriptor.isChildListProperty()) {
        @SuppressWarnings("unchecked")
        final List<ASTNode> children = (List<ASTNode>) parent.getStructuralProperty(descriptor);
        children.addAll(children.indexOf(node), replacement);
        node.delete();
        return true;
    }
    return false;
}

From source file:changenodes.matching.BestLeafTreeMatcher.java

License:Apache License

@SuppressWarnings("unchecked")
private void markMatchedNode(ASTNode left, ASTNode right) {
    if (left.getNodeType() != right.getNodeType()) {
        return;/*from  w w w. j a  v a 2  s .  c om*/
    }
    if (!(leftMatching.containsKey(left) || rightMatching.containsKey(right))) {
        leftMatching.put(left, right);
        rightMatching.put(right, left);
        List<StructuralPropertyDescriptor> props = (List<StructuralPropertyDescriptor>) left
                .structuralPropertiesForType();
        for (StructuralPropertyDescriptor prop : props) {
            if (prop.isChildProperty()) {
                ASTNode newLeft, newRight;
                newLeft = (ASTNode) left.getStructuralProperty(prop);
                newRight = (ASTNode) right.getStructuralProperty(prop);
                if (newLeft != null && newRight != null) {
                    markMatchedNode(newLeft, newRight);
                }
            } else if (prop.isChildListProperty()) {
                List<ASTNode> lefts, rights;
                lefts = (List<ASTNode>) left.getStructuralProperty(prop);
                rights = (List<ASTNode>) right.getStructuralProperty(prop);
                int times = lefts.size();
                if (lefts.size() > rights.size()) {
                    times = rights.size();
                }
                Iterator<ASTNode> leftIt = lefts.iterator();
                Iterator<ASTNode> rightIt = rights.iterator();
                for (int i = 0; i < times; ++i) {
                    ASTNode rNode = rightIt.next();
                    ASTNode lNode = leftIt.next();
                    if (lNode != null && rNode != null) {
                        markMatchedNode(lNode, rNode);
                    }
                }
            }
            //we dont handle simple props as they point to objects
        }
    }
}

From source file:com.halware.nakedide.eclipse.ext.annot.utils.AstUtils.java

License:Open Source License

/**
 * Returns (as a list) all those child properties of the supplied type.
 * /* w  ww .  j a  va2s.  c o m*/
 * @param <T>
 * @param node
 * @param requiredType
 * @return
 */
public static <T> List<T> getChildProperties(ASTNode node, Class<T> requiredType) {
    List<T> children = new ArrayList<T>();
    for (ChildListPropertyDescriptor clpd : getChildListPropertyDescriptors(node)) {
        List<ASTNode> childProperties = Generics.asT(node.getStructuralProperty(clpd));
        for (ASTNode childNode : childProperties) {
            if (requiredType.isAssignableFrom(childNode.getClass())) {
                T t = Generics.asT(childNode);
                children.add(t);
            }
        }
    }
    return children;
}

From source file:com.worldline.awltech.i18ntools.wizard.core.modules.ResourceBundleWrapper.java

License:Open Source License

/**
 * Refactors the source code to replace selected source by literal.
 * /*from   w ww  .  j a v a2  s  .  c  om*/
 * @param nodeFinder
 * @param literalName
 * @param resolver
 * @return
 */
@SuppressWarnings("unchecked")
private boolean effectiveAddLiteral(final ASTNodeFinder nodeFinder, final String literalName,
        final ASTExpressionResolver resolver) {

    final ASTNode parent = nodeFinder.getParentNode();
    final AST ast = parent.getAST();

    final MethodInvocation replacement = ast.newMethodInvocation();
    replacement.setExpression(ast.newName(this.resourceBundleName + "." + literalName));
    replacement.setName(ast.newSimpleName("value"));

    final EnumDeclaration enumDeclaration = (EnumDeclaration) this.enumDomCompilationUnit.types().get(0);

    final EnumConstantDeclaration enumConstantDeclaration = enumDeclaration.getAST()
            .newEnumConstantDeclaration();
    enumConstantDeclaration.setName(enumDeclaration.getAST().newSimpleName(literalName));

    enumDeclaration.enumConstants().add(enumConstantDeclaration);

    boolean hasMessageKeyConstructor = false;
    for (final Iterator<Object> iterator = enumDeclaration.bodyDeclarations().iterator(); iterator.hasNext()
            && !hasMessageKeyConstructor;) {
        final Object next = iterator.next();
        if (next instanceof MethodDeclaration) {
            final MethodDeclaration methodDeclaration = (MethodDeclaration) next;
            if (methodDeclaration.isConstructor() && methodDeclaration.parameters().size() > 0) {
                hasMessageKeyConstructor = true;
            }
        }
    }

    if (hasMessageKeyConstructor) {
        final StringLiteral literal = enumDeclaration.getAST().newStringLiteral();
        literal.setLiteralValue(literalName);
        enumConstantDeclaration.arguments().add(literal);
    }

    StructuralPropertyDescriptor locationInParent = null;
    if (nodeFinder.getFoundNode() != null) {
        locationInParent = nodeFinder.getFoundNode().getLocationInParent();
    } else {
        // TODO
        return false;
    }

    ResourceBundleWrapper.addImportToCompilationUnitIfMissing(nodeFinder.getParentNode(),
            this.packageName + "." + this.resourceBundleName);

    if (locationInParent.isChildListProperty()) {
        final List<Object> list = (List<Object>) parent.getStructuralProperty(locationInParent);
        final int index = list.indexOf(nodeFinder.getFoundNode());
        list.remove(nodeFinder.getFoundNode());
        list.add(index, replacement);
    } else {
        parent.setStructuralProperty(locationInParent, replacement);
    }

    for (final Expression parameter : resolver.getMessageParameters()) {
        final Expression newParameter = ASTTreeCloner.clone(parameter);
        replacement.arguments().add(newParameter);
    }

    String messagePattern = resolver.getMessagePattern();
    if (this.prefixMessageByKey) {
        messagePattern = String.format("[%s] %s", literalName, messagePattern);
    }

    this.properties.put(literalName, messagePattern);
    return true;
}

From source file:de.ovgu.cide.export.physical.ahead.RefactoringUtils.java

License:Open Source License

public static void replaceASTNode(ASTNode target, ASTNode replacement) {
    ASTNode parent = target.getParent();
    if (target.getLocationInParent().isChildListProperty()) {
        List<ASTNode> list = (List<ASTNode>) parent.getStructuralProperty(target.getLocationInParent());
        int p = list.indexOf(target);
        list.set(p, replacement);//from  w  ww  .ja  v a 2  s .c  om
    } else
        parent.setStructuralProperty(target.getLocationInParent(), replacement);
}

From source file:edu.buffalo.cse.Sapphire.JavaModelListener.java

License:Open Source License

/**
 * This method traverses the root ASTNode in the parameter and calls
 * printStatement to store the information of the child node.
 * /*from  w w w.  java  2s.  c  o m*/
 * @author Chern Yee Chua
 */

public static void print(ASTNode node) {

    List properties = node.structuralPropertiesForType();
    for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
        Object descriptor = iterator.next();
        if (descriptor instanceof SimplePropertyDescriptor) {
            SimplePropertyDescriptor simple = (SimplePropertyDescriptor) descriptor;
            Object value = node.getStructuralProperty(simple);
            int lineNumber;
            if (isTempLarger) {
                lineNumber = astRootTemp.getLineNumber(node.getStartPosition());
            } else {
                lineNumber = astRoot.getLineNumber(node.getStartPosition());
            }

            lastLineNumber = lineNumber;
            printStatement(lineNumber, simple, value, node);

        } else if (descriptor instanceof ChildPropertyDescriptor) {
            ChildPropertyDescriptor child = (ChildPropertyDescriptor) descriptor;
            ASTNode childNode = (ASTNode) node.getStructuralProperty(child);
            if (childNode != null) {

                print(childNode);
            }
        } else {
            ChildListPropertyDescriptor list = (ChildListPropertyDescriptor) descriptor;
            print((List) node.getStructuralProperty(list));
        }
    }
}

From source file:edu.buffalo.cse.Sapphire.JavaModelListenerNew.java

License:Open Source License

/**
 * This method traverses the root ASTNode in the parameter and calls
 * printStatement to store the information of the child node.
 * //from  www.  j  a  v  a 2s.c o m
 * @author Chern Yee Chua
 */

public static void print(ASTNode node) {

    List properties = node.structuralPropertiesForType();
    for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
        Object descriptor = iterator.next();
        if (descriptor instanceof SimplePropertyDescriptor) {
            SimplePropertyDescriptor simple = (SimplePropertyDescriptor) descriptor;
            Object value = node.getStructuralProperty(simple);
            int lineNumber = astRoot.getLineNumber(node.getStartPosition());

            lastLineNumber = lineNumber;
            printStatement(lineNumber, node);

        } else if (descriptor instanceof ChildPropertyDescriptor) {
            ChildPropertyDescriptor child = (ChildPropertyDescriptor) descriptor;
            ASTNode childNode = (ASTNode) node.getStructuralProperty(child);
            if (childNode != null) {

                print(childNode);
            }
        } else {
            ChildListPropertyDescriptor list = (ChildListPropertyDescriptor) descriptor;
            print((List) node.getStructuralProperty(list));
        }
    }
}

From source file:edu.illinois.compositerefactorings.refactorings.NewClassCreator.java

License:Open Source License

public List<ResourceChange> createTopLevelParameterObject() throws CoreException {
    List<ResourceChange> changes = new ArrayList<ResourceChange>();
    ICompilationUnit unit = getPackageFragment()
            .getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
    Assert.isTrue(!unit.exists());//from  ww  w. j a  v  a 2  s.  c  om
    IJavaProject javaProject = unit.getJavaProject();
    ICompilationUnit workingCopy = unit.getWorkingCopy(null);

    try {
        // create stub with comments and dummy type
        String lineDelimiter = StubUtility.getLineDelimiterUsed(javaProject);
        String fileComment = getFileComment(workingCopy, lineDelimiter);
        String typeComment = getTypeComment(workingCopy, lineDelimiter);
        String content = CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment,
                "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
        workingCopy.getBuffer().setContents(content);

        CompilationUnitRewrite cuRewrite = new CompilationUnitRewrite(workingCopy);
        ASTRewrite rewriter = cuRewrite.getASTRewrite();
        CompilationUnit root = cuRewrite.getRoot();
        AST ast = cuRewrite.getAST();
        ImportRewrite importRewrite = cuRewrite.getImportRewrite();

        if (fSuperclassType != null) {
            importRewrite.addImport(fSuperclassType.resolveBinding());
        }

        // retrieve&replace dummy type with real class
        ListRewrite types = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
        ASTNode dummyType = (ASTNode) types.getOriginalList().get(0);
        TypeDeclaration classDeclaration = createClassDeclaration(getClassName(), cuRewrite);
        classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
        Javadoc javadoc = (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
        rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
        types.replace(dummyType, classDeclaration, null);

        // Apply rewrites and discard workingcopy
        // Using CompilationUnitRewrite.createChange() leads to strange
        // results
        String charset = ResourceUtil.getFile(unit).getCharset(false);
        Document document = new Document(content);
        try {
            rewriter.rewriteAST().apply(document);
            TextEdit rewriteImports = importRewrite.rewriteImports(null);
            rewriteImports.apply(document);
        } catch (BadLocationException e) {
            throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                    RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error,
                    e));
        }
        String docContent = document.get();
        CreateCompilationUnitChange compilationUnitChange = new CreateCompilationUnitChange(unit, docContent,
                charset);
        changes.add(compilationUnitChange);
    } finally {
        workingCopy.discardWorkingCopy();
    }
    return changes;
}