Example usage for org.eclipse.jdt.core.dom ASTParser setProject

List of usage examples for org.eclipse.jdt.core.dom ASTParser setProject

Introduction

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

Prototype

public void setProject(IJavaProject project) 

Source Link

Document

Sets the Java project used when resolving bindings.

Usage

From source file:at.bestsolution.fxide.jdt.editor.JDTJavaDocSupport.java

License:Open Source License

private static CompilationUnit createAST(IJavaElement element, String cuSource) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);

    IJavaProject javaProject = element.getJavaProject();
    parser.setProject(javaProject);
    Map<String, String> options = javaProject.getOptions(true);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround
    // for/*from w  w w.j  a  va  2  s .  c o  m*/
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
    parser.setCompilerOptions(options);

    parser.setSource(cuSource.toCharArray());
    return (CompilationUnit) parser.createAST(null);
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private static CompilationUnit createAST(IJavaElement element, String cuSource) {
    Assert.isNotNull(element);/*w  w w. j a v  a 2  s. co m*/
    ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);

    IJavaProject javaProject = element.getJavaProject();
    parser.setProject(javaProject);
    Map<String, String> options = javaProject.getOptions(true);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
    parser.setCompilerOptions(options);

    parser.setSource(cuSource.toCharArray());
    return (CompilationUnit) parser.createAST(null);
}

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

private void processAnnotations(IJavaProject javaProject, Map<ICompilationUnit, BuildContext> fileMap) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setResolveBindings(true);/*from   ww w  . j  a va 2s. co  m*/
    parser.setBindingsRecovery(true);
    parser.setProject(javaProject);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    ProjectContext projectContext = processingContext.get(javaProject);
    ProjectState state = projectContext.getState();

    parser.setIgnoreMethodBodies(state.getErrorLevel() == ValidationErrorLevel.none);

    ICompilationUnit[] cuArr = fileMap.keySet().toArray(new ICompilationUnit[fileMap.size()]);
    Map<ICompilationUnit, Collection<IDSModel>> models = new HashMap<ICompilationUnit, Collection<IDSModel>>();
    parser.createASTs(cuArr, new String[0], new AnnotationProcessor(models, fileMap, state.getErrorLevel()),
            null);

    Map<String, Collection<String>> cuMap = state.getMappings();
    Collection<String> unprocessed = projectContext.getUnprocessed();
    Collection<String> abandoned = projectContext.getAbandoned();

    IPath outputPath = new Path(state.getPath()).addTrailingSeparator();

    // save each model to a file; track changes to mappings
    for (Map.Entry<ICompilationUnit, Collection<IDSModel>> entry : models.entrySet()) {
        ICompilationUnit cu = entry.getKey();
        IType cuType = cu.findPrimaryType();
        if (cuType == null) {
            if (debug.isDebugging())
                debug.trace(String.format("CU %s has no primary type!", cu.getElementName())); //$NON-NLS-1$

            continue; // should never happen
        }

        String cuKey = cuType.getFullyQualifiedName();

        unprocessed.remove(cuKey);
        Collection<String> oldDSKeys = cuMap.remove(cuKey);
        Collection<String> dsKeys = new HashSet<String>();
        cuMap.put(cuKey, dsKeys);

        for (IDSModel model : entry.getValue()) {
            String compName = model.getDSComponent().getAttributeName();
            IPath filePath = outputPath.append(compName).addFileExtension("xml"); //$NON-NLS-1$
            String dsKey = filePath.toPortableString();

            // exclude file from garbage collection
            if (oldDSKeys != null)
                oldDSKeys.remove(dsKey);

            // add file to CU mapping
            dsKeys.add(dsKey);

            // actually save the file
            IFile compFile = PDEProject.getBundleRelativeFile(javaProject.getProject(), filePath);
            model.setUnderlyingResource(compFile);

            try {
                ensureDSProject(compFile.getProject());
            } catch (CoreException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }

            IPath parentPath = compFile.getParent().getProjectRelativePath();
            if (!parentPath.isEmpty()) {
                IFolder folder = javaProject.getProject().getFolder(parentPath);
                try {
                    ensureExists(folder);
                } catch (CoreException e) {
                    Activator.getDefault().getLog().log(e.getStatus());
                    model.dispose();
                    continue;
                }
            }

            if (debug.isDebugging())
                debug.trace(String.format("Saving model: %s", compFile.getFullPath())); //$NON-NLS-1$

            model.save();
            model.dispose();
        }

        // track abandoned files (may be garbage)
        if (oldDSKeys != null)
            abandoned.addAll(oldDSKeys);
    }
}

From source file:ch.uzh.ifi.seal.permo.lib.core.eclipse.AstUtil.java

License:Apache License

/**
 * Uses an {@link ASTParser} to create the {@link IMethodBinding} of the given {@link IMethod}.
 * /* www  . j  av  a  2  s  . c o m*/
 * Further info: http://wiki.eclipse.org/JDT/FAQ#From_an_IJavaElement_to_an_IBinding
 * 
 * @param method
 *          the {@link IMethod}
 * @return the create {@link IMethodBinding}.
 */
public static IMethodBinding createBinding(final IMethod method) {
    final ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setProject(method.getJavaProject());
    final IBinding[] bindings = parser.createBindings(new IJavaElement[] { method }, new NullProgressMonitor());
    if (bindings.length > 0 && bindings[0] instanceof IMethodBinding) {
        return (IMethodBinding) bindings[0];
    }
    return null;
}

From source file:cideplus.ui.astview.ASTView.java

License:Open Source License

protected void performParseBindingFromKey() {
    String msg = "Parse Binding from Key";
    String key = askForKey(msg);/*from   ww  w  .j a va 2 s  . co m*/
    if (key == null)
        return;
    ASTParser parser = ASTParser.newParser(fCurrentASTLevel);
    parser.setResolveBindings(true);
    parser.setProject(fTypeRoot.getJavaProject());
    class MyASTRequestor extends ASTRequestor {
        String fBindingKey;
        IBinding fBinding;

        @Override
        public void acceptBinding(String bindingKey, IBinding binding) {
            fBindingKey = bindingKey;
            fBinding = binding;
        }
    }
    MyASTRequestor requestor = new MyASTRequestor();
    ASTAttribute item;
    Object viewerInput = fViewer.getInput();
    try {
        parser.createASTs(new ICompilationUnit[0], new String[] { key }, requestor, null);
        if (requestor.fBindingKey != null) {
            String name = requestor.fBindingKey + ": " + Binding.getBindingLabel(requestor.fBinding);
            item = new Binding(viewerInput, name, requestor.fBinding, true);
        } else {
            item = new Error(viewerInput, "Key not resolved: " + key, null);
        }
    } catch (RuntimeException e) {
        item = new Error(viewerInput, "Error resolving key: " + key, e);
    }
    fViewer.add(viewerInput, item);
    fViewer.setSelection(new StructuredSelection(item), true);
}

From source file:cideplus.ui.astview.ASTView.java

License:Open Source License

protected void performParseBindingFromElement() {
    InputDialog dialog = new InputDialog(getSite().getShell(), "Parse Binding from Java Element",
            "IJavaElement#getHandleIdentifier():", "", null);
    if (dialog.open() != Window.OK)
        return;//from  ww  w . j a v  a 2s .c om

    String handleIdentifier = dialog.getValue();
    IJavaElement handle = JavaCore.create(handleIdentifier);

    Object viewerInput = fViewer.getInput();
    ASTAttribute item;
    if (handle == null) {
        item = new Error(viewerInput, "handleIdentifier not resolved: " + handleIdentifier, null);
    } else if (!handle.exists()) {
        item = new Error(viewerInput, "element does not exist: " + handleIdentifier, null);
    } else if (handle.getJavaProject() == null) {
        item = new Error(viewerInput, "getJavaProject() is null: " + handleIdentifier, null);
    } else {
        IJavaProject project = handle.getJavaProject();
        ASTParser parser = ASTParser.newParser(fCurrentASTLevel);
        parser.setProject(project);
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { handle }, null);
        String name = handleIdentifier + ": " + Binding.getBindingLabel(bindings[0]);
        item = new Binding(viewerInput, name, bindings[0], true);
    }
    fViewer.add(viewerInput, item);
    fViewer.setSelection(new StructuredSelection(item), true);
}

From source file:coloredide.astview.ASTView.java

License:Open Source License

protected void performCreateBindingFromElement() {
    InputDialog dialog = new InputDialog(getSite().getShell(), "Create Binding from Java Element",
            "IJavaElement#getHandleIdentifier():", "", null);
    if (dialog.open() != Window.OK)
        return;/*from ww  w.  j a  v  a  2  s.c o  m*/

    String handleIdentifier = dialog.getValue();
    IJavaElement handle = JavaCore.create(handleIdentifier);

    Object viewerInput = fViewer.getInput();
    ASTAttribute item;
    if (handle == null) {
        item = new Error(viewerInput, "handleIdentifier not resolved: " + handleIdentifier, null);
    } else if (!handle.exists()) {
        item = new Error(viewerInput, "element does not exist: " + handleIdentifier, null);
    } else if (handle.getJavaProject() == null) {
        item = new Error(viewerInput, "getJavaProject() is null: " + handleIdentifier, null);
    } else {
        IJavaProject project = handle.getJavaProject();
        ASTParser parser = ASTParser.newParser(ColoredIDEPlugin.AST_VERSION);
        parser.setProject(project);
        IBinding[] bindings = parser.createBindings(new IJavaElement[] { handle }, null);
        item = new Binding(viewerInput, handleIdentifier, bindings[0], true);
    }
    fViewer.add(viewerInput, item);
    fViewer.setSelection(new StructuredSelection(item), true);
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Computes the changes to be made to Java file(s) and returns a list of {@link Change}.
 * <p/>/*from  ww  w.ja va 2s .  c om*/
 * This function scans a Java compilation unit using {@link ReplaceStringsVisitor}, looking
 * for a string literal equals to <code>tokenString</code>.
 * If found, a change is made to replace each occurrence of <code>tokenString</code> by
 * a piece of Java code that somehow accesses R.string.<code>xmlStringId</code>.
 *
 * @param unit The compilated unit to process. Must not be null.
 * @param tokenString The string to find. Must not be null or empty.
 * @param status Status used to report fatal errors.
 * @param monitor Used to log progress.
 */
private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString,
        RefactoringStatus status, SubMonitor monitor) {

    // We shouldn't be trying to replace a null or empty string.
    assert tokenString != null && tokenString.length() > 0;
    if (tokenString == null || tokenString.length() == 0) {
        return null;
    }

    // Get the Android package name from the Android Manifest. We need it to create
    // the FQCN of the R class.
    String packageName = null;
    String error = null;
    IResource manifestFile = mProject.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML);
    if (manifestFile == null || manifestFile.getType() != IResource.FILE) {
        error = "File not found";
    } else {
        ManifestData manifestData = AndroidManifestHelper.parseForData((IFile) manifestFile);
        if (manifestData == null) {
            error = "Invalid content";
        } else {
            packageName = manifestData.getPackage();
            if (packageName == null) {
                error = "Missing package definition";
            }
        }
    }

    if (error != null) {
        status.addFatalError(String.format("Failed to parse file %1$s: %2$s.",
                manifestFile == null ? "" : manifestFile.getFullPath(), //$NON-NLS-1$
                error));
        return null;
    }

    // Right now the changes array will contain one TextFileChange at most.
    ArrayList<Change> changes = new ArrayList<Change>();

    // This is the unit that will be modified.
    TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource());
    change.setTextType("java"); //$NON-NLS-1$

    // Create an AST for this compilation unit
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(unit.getJavaProject());
    parser.setSource(unit);
    parser.setResolveBindings(true);
    ASTNode node = parser.createAST(monitor.newChild(1));

    // The ASTNode must be a CompilationUnit, by design
    if (!(node instanceof CompilationUnit)) {
        status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$
                node.getClass()));
        return null;
    }

    // ImportRewrite will allow us to add the new type to the imports and will resolve
    // what the Java source must reference, e.g. the FQCN or just the simple name.
    ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true);
    String Rqualifier = packageName + ".R"; //$NON-NLS-1$
    Rqualifier = importRewrite.addImport(Rqualifier);

    // Rewrite the AST itself via an ASTVisitor
    AST ast = node.getAST();
    ASTRewrite astRewrite = ASTRewrite.create(ast);
    ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>();
    ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString,
            Rqualifier, xmlStringId);
    node.accept(visitor);

    // Finally prepare the change set
    try {
        MultiTextEdit edit = new MultiTextEdit();

        // Create the edit to change the imports, only if anything changed
        TextEdit subEdit = importRewrite.rewriteImports(monitor.newChild(1));
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Create the edit to change the Java source, only if anything changed
        subEdit = astRewrite.rewriteAST();
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Only create a change set if any edit was collected
        if (edit.hasChildren()) {
            change.setEdit(edit);

            // Create TextEditChangeGroups which let the user turn changes on or off
            // individually. This must be done after the change.setEdit() call above.
            for (TextEditGroup editGroup : astEditGroups) {
                TextEditChangeGroup group = new TextEditChangeGroup(change, editGroup);
                if (editGroup instanceof EnabledTextEditGroup) {
                    group.setEnabled(((EnabledTextEditGroup) editGroup).isEnabled());
                }
                change.addTextEditChangeGroup(group);
            }

            changes.add(change);
        }

        monitor.worked(1);

        if (changes.size() > 0) {
            return changes;
        }

    } catch (CoreException e) {
        // ImportRewrite.rewriteImports failed.
        status.addFatalError(e.getMessage());
    }
    return null;
}

From source file:com.android.ide.eclipse.adt.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Computes the changes to be made to Java file(s) and returns a list of {@link Change}.
 *//*from ww  w.j av a  2 s .co m*/
private List<Change> computeJavaChanges(ICompilationUnit unit, String xmlStringId, String tokenString,
        RefactoringStatus status, SubMonitor subMonitor) {

    // Get the Android package name from the Android Manifest. We need it to create
    // the FQCN of the R class.
    String packageName = null;
    String error = null;
    IResource manifestFile = mProject.findMember(AndroidConstants.FN_ANDROID_MANIFEST);
    if (manifestFile == null || manifestFile.getType() != IResource.FILE) {
        error = "File not found";
    } else {
        try {
            AndroidManifestParser manifest = AndroidManifestParser.parseForData((IFile) manifestFile);
            if (manifest == null) {
                error = "Invalid content";
            } else {
                packageName = manifest.getPackage();
                if (packageName == null) {
                    error = "Missing package definition";
                }
            }
        } catch (CoreException e) {
            error = e.getLocalizedMessage();
        }
    }

    if (error != null) {
        status.addFatalError(
                String.format("Failed to parse file %1$s: %2$s.", manifestFile.getFullPath(), error));
        return null;
    }

    // TODO in a future version we might want to collect various Java files that
    // need to be updated in the same project and process them all together.
    // To do that we need to use an ASTRequestor and parser.createASTs, kind of
    // like this:
    //
    // ASTRequestor requestor = new ASTRequestor() {
    //    @Override
    //    public void acceptAST(ICompilationUnit sourceUnit, CompilationUnit astNode) {
    //        super.acceptAST(sourceUnit, astNode);
    //        // TODO process astNode
    //    }  
    // };
    // ...
    // parser.createASTs(compilationUnits, bindingKeys, requestor, monitor)
    // 
    // and then add multiple TextFileChange to the changes arraylist.

    // Right now the changes array will contain one TextFileChange at most.
    ArrayList<Change> changes = new ArrayList<Change>();

    // This is the unit that will be modified.
    TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource());
    change.setTextType("java"); //$NON-NLS-1$

    // Create an AST for this compilation unit
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setProject(unit.getJavaProject());
    parser.setSource(unit);
    parser.setResolveBindings(true);
    ASTNode node = parser.createAST(subMonitor.newChild(1));

    // The ASTNode must be a CompilationUnit, by design
    if (!(node instanceof CompilationUnit)) {
        status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$
                node.getClass()));
        return null;
    }

    // ImportRewrite will allow us to add the new type to the imports and will resolve
    // what the Java source must reference, e.g. the FQCN or just the simple name.
    ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true);
    String Rqualifier = packageName + ".R"; //$NON-NLS-1$
    Rqualifier = importRewrite.addImport(Rqualifier);

    // Rewrite the AST itself via an ASTVisitor
    AST ast = node.getAST();
    ASTRewrite astRewrite = ASTRewrite.create(ast);
    ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>();
    ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(ast, astRewrite, astEditGroups, tokenString,
            Rqualifier, xmlStringId);
    node.accept(visitor);

    // Finally prepare the change set
    try {
        MultiTextEdit edit = new MultiTextEdit();

        // Create the edit to change the imports, only if anything changed
        TextEdit subEdit = importRewrite.rewriteImports(subMonitor.newChild(1));
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Create the edit to change the Java source, only if anything changed
        subEdit = astRewrite.rewriteAST();
        if (subEdit.hasChildren()) {
            edit.addChild(subEdit);
        }

        // Only create a change set if any edit was collected
        if (edit.hasChildren()) {
            change.setEdit(edit);

            // Create TextEditChangeGroups which let the user turn changes on or off
            // individually. This must be done after the change.setEdit() call above.
            for (TextEditGroup editGroup : astEditGroups) {
                change.addTextEditChangeGroup(new TextEditChangeGroup(change, editGroup));
            }

            changes.add(change);
        }

        // TODO to modify another Java source, loop back to the creation of the
        // TextFileChange and accumulate in changes. Right now only one source is
        // modified.

        if (changes.size() > 0) {
            return changes;
        }

        subMonitor.worked(1);

    } catch (CoreException e) {
        // ImportRewrite.rewriteImports failed.
        status.addFatalError(e.getMessage());
    }
    return null;
}

From source file:com.codenvy.ide.ext.java.server.javadoc.JavadocContentAccess2.java

License:Open Source License

private static CompilationUnit createAST(IJavaElement element, String cuSource) {
    Assert.isNotNull(element);//  www. ja v  a 2 s .  c om
    ASTParser parser = ASTParser.newParser(AST.JLS8);

    IJavaProject javaProject = element.getJavaProject();
    parser.setProject(javaProject);
    Map<String, String> options = javaProject.getOptions(true);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
    parser.setCompilerOptions(options);

    parser.setSource(cuSource.toCharArray());
    return (CompilationUnit) parser.createAST(null);
}