Example usage for org.eclipse.jdt.core IJavaProject findElement

List of usage examples for org.eclipse.jdt.core IJavaProject findElement

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject findElement.

Prototype

IJavaElement findElement(IPath path) throws JavaModelException;

Source Link

Document

Returns the IJavaElement corresponding to the given classpath-relative path, or null if no such IJavaElement is found.

Usage

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that tags updated on an inner type are updated in the workspace
 * description./*  w  w w .  ja  v a2 s .  c o m*/
 * 
 * This test adds a @noinstantiate tag to an inner class in TestClass3
 */
public void testWPUpdateSourceInnerTypeChanged() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestClass3"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass3.java")); //$NON-NLS-1$
    assertNotNull("TestClass3 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "InnerTestClass3", null, "@noinstantiate", false); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.typeDescriptor("a.b.c.TestClass3$InnerTestClass3")); //$NON-NLS-1$
    assertNotNull("the annotations for a.b.c.TestClass3$InnerTestClass3 cannot be null", annot); //$NON-NLS-1$
    assertFalse("there must not be a noinstantiate setting for TestClass3$InnerTestClass3", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_INSTANTIATE) != 0);
    assertFalse("there must not be a noextend setting for TestClass3$InnerTestClass3", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_EXTEND) != 0);
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that changing the javadoc for a method updates the workspace
 * baseline//from w  ww  .  j a va 2 s .co m
 * 
 * This test adds a @noextend tag to the method foo() in TestClass1
 */
public void testWPUpdateSourceMethodChanged() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestClass1"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass1.java")); //$NON-NLS-1$
    assertNotNull("TestClass1 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "foo", "()V", "@nooverride", false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.methodDescriptor("a.b.c.TestClass1", "foo", "()V")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertNotNull("the annotations for foo() cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a nooverride setting for foo()", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_OVERRIDE) != 0);
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that changing the javadoc for a field updates the workspace
 * baseline//from   w ww. j a v a2s  . c  om
 * 
 * This test adds a @noextend tag to the field 'field' in TestField9
 */
public void testWPUpdateSourceFieldChanged() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestField9"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestField9.java")); //$NON-NLS-1$
    assertNotNull("TestField9 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "field", null, "@noreference", false); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.fieldDescriptor("a.b.c.TestField9", "field")); //$NON-NLS-1$ //$NON-NLS-2$
    assertNotNull("the annotations for 'field' cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a noreference setting for 'field'", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_REFERENCE) != 0);
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that removing a tag from a method updates the workspace baseline
 * //from   w ww  . ja  va2 s  .c om
 * This test removes a @noextend tag to the method foo() in TestClass1
 */
public void testWPUpdateSourceMethodRemoveTag() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestClass1"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass1.java")); //$NON-NLS-1$
    assertNotNull("TestClass1 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "foo", "()V", "@nooverride", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.methodDescriptor("a.b.c.TestClass1", "foo", "()V")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    assertNotNull("the annotations for foo() cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be no restrictions for foo()", annot.getRestrictions() == 0); //$NON-NLS-1$
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that removing a tag from a type updates the workspace baseline
 * /* w  ww .  j  a  v a 2 s  . c o  m*/
 * This test removes a @noinstantiate tag to an inner class in TestClass3
 */
public void testWPUpdateSourceTypeRemoveTag() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestClass3"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestClass3.java")); //$NON-NLS-1$
    assertNotNull("TestClass3 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "InnerTestClass3", null, "@noextend", true); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.typeDescriptor("a.b.c.TestClass3$InnerTestClass3")); //$NON-NLS-1$
    assertNotNull("the annotations for 'InnerTestClass3' cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a no restrictions for 'InnerTestClass3'", //$NON-NLS-1$
            (annot.getRestrictions() & RestrictionModifiers.NO_INSTANTIATE) == 0);
}

From source file:org.eclipse.pde.api.tools.util.tests.ApiBaselineManagerTests.java

License:Open Source License

/**
 * Tests that removing a tag from a field updates the workspace baseline
 * /*from w  w  w.ja v a 2s. c  o m*/
 * This test adds a @noextend tag to the field 'field' in TestField9
 */
public void testWPUpdateSourceFieldRemoveTag() throws Exception {
    IJavaProject project = getTestingProject();
    assertNotNull("The testing project must exist", project); //$NON-NLS-1$
    IPackageFragmentRoot root = project.findPackageFragmentRoot(
            new Path(project.getElementName()).append(ProjectUtils.SRC_FOLDER).makeAbsolute());
    assertNotNull("the 'src' package fragment root must exist", root); //$NON-NLS-1$
    assertTestSource(root, TESTING_PACKAGE, "TestField9"); //$NON-NLS-1$
    ICompilationUnit element = (ICompilationUnit) project.findElement(new Path("a/b/c/TestField9.java")); //$NON-NLS-1$
    assertNotNull("TestField9 must exist in the test project", element); //$NON-NLS-1$
    updateTagInSource(element, "field1", null, "@noreference", true); //$NON-NLS-1$ //$NON-NLS-2$
    IApiDescription desc = getTestProjectApiDescription();
    assertNotNull("the testing project api description must exist", desc); //$NON-NLS-1$
    IApiAnnotations annot = desc.resolveAnnotations(Factory.fieldDescriptor("a.b.c.TestField9", "field")); //$NON-NLS-1$ //$NON-NLS-2$
    assertNotNull("the annotations for 'field' cannot be null", annot); //$NON-NLS-1$
    assertTrue("there must be a no restrictions for 'field'", annot.getRestrictions() == 0); //$NON-NLS-1$
}

From source file:org.eclipse.pde.ds.internal.annotations.DSAnnotationCompilationParticipant.java

License:Open Source License

@Override
public void buildFinished(IJavaProject project) {
    ProjectContext projectContext = processingContext.remove(project);
    if (projectContext != null) {
        ProjectState state = projectContext.getState();
        // check if unprocessed CUs still exist; if not, their mapped files are now abandoned
        HashSet<String> abandoned = new HashSet<>(projectContext.getAbandoned());
        for (String cuKey : projectContext.getUnprocessed()) {
            boolean exists = false;
            try {
                IJavaElement cu = project.findElement(new Path(cuKey));
                IResource file;/*from   ww w  . j av a  2 s  . c  om*/
                if (cu != null && cu.getElementType() == IJavaElement.COMPILATION_UNIT
                        && (file = cu.getResource()) != null && file.exists())
                    exists = true;
            } catch (JavaModelException e) {
                Activator.log(e);
            }

            if (!exists) {
                if (debug.isDebugging())
                    debug.trace(String.format("Mapped CU %s no longer exists.", cuKey)); //$NON-NLS-1$

                Collection<String> dsKeys = state.removeMappings(cuKey);
                if (dsKeys != null)
                    abandoned.addAll(dsKeys);
            }
        }

        // retain abandoned files that are still mapped elsewhere
        HashSet<String> retained = new HashSet<>();
        for (String cuKey : state.getCompilationUnits()) {
            Collection<String> dsKeys = state.getModelFiles(cuKey);
            if (dsKeys != null)
                retained.addAll(dsKeys);
        }

        abandoned.removeAll(retained);

        if (projectContext.isChanged()) {
            try {
                saveState(project.getProject(), state);
            } catch (IOException e) {
                Activator.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error saving file mappings.", e)); //$NON-NLS-1$
            }
        }

        // delete all abandoned files
        ArrayList<IStatus> deleteStatuses = new ArrayList<>(2);
        for (String dsKey : abandoned) {
            IPath path = Path.fromPortableString(dsKey);

            if (debug.isDebugging())
                debug.trace(String.format("Deleting %s", path)); //$NON-NLS-1$

            IFile file = PDEProject.getBundleRelativeFile(project.getProject(), path);
            if (file.exists()) {
                try {
                    file.delete(true, null);
                } catch (CoreException e) {
                    deleteStatuses.add(e.getStatus());
                }
            }
        }

        if (!deleteStatuses.isEmpty())
            Activator.log(new MultiStatus(Activator.PLUGIN_ID, 0,
                    deleteStatuses.toArray(new IStatus[deleteStatuses.size()]),
                    "Error deleting generated files.", null)); //$NON-NLS-1$

        if (!retained.isEmpty() || !abandoned.isEmpty())
            updateProject(project.getProject(), retained, abandoned);
    }

    if (debug.isDebugging())
        debug.trace(String.format("Build finished for project: %s", project.getElementName())); //$NON-NLS-1$
}

From source file:org.eclipse.pde.internal.ui.editor.plugin.JavaAttributeWizard.java

License:Open Source License

public boolean performFinish() {
    IRunnableWithProgress op = new WorkspaceModifyOperation() {
        protected void execute(IProgressMonitor monitor) throws CoreException, InterruptedException {
            fMainPage.createType(monitor);
        }//from   w  w w.jav a 2 s  .  com
    };
    try {
        PlatformUI.getWorkbench().getProgressService().runInUI(PDEPlugin.getActiveWorkbenchWindow(), op,
                PDEPlugin.getWorkspace().getRoot());
        IResource resource = fMainPage.getModifiedResource();
        if (resource != null) {
            selectAndReveal(resource);
            if (fProject.hasNature(JavaCore.NATURE_ID)) {
                IJavaProject jProject = JavaCore.create(fProject);
                IJavaElement jElement = jProject
                        .findElement(resource.getProjectRelativePath().removeFirstSegments(1));
                if (jElement != null)
                    JavaUI.openInEditor(jElement);
            } else if (resource instanceof IFile) {
                IWorkbenchPage page = PDEPlugin.getActivePage();
                IDE.openEditor(page, (IFile) resource, true);
            }
        }
    } catch (InvocationTargetException e) {
        PDEPlugin.logException(e);
    } catch (InterruptedException e) {
        PDEPlugin.logException(e);
    } catch (CoreException e) {
        PDEPlugin.logException(e);
    }
    return true;
}

From source file:org.eclipse.recommenders.testing.rcp.completion.rules.TemporaryFile.java

License:Open Source License

private ICompilationUnit createFile(final String content) throws CoreException {
    // get filename
    final String fileName = findClassName(content) + Constants.DOT_JAVA;

    // add the file name and get the file
    StringBuilder projectRelativeFilePath = new StringBuilder();
    projectRelativeFilePath.append(SRC_FOLDER_NAME);
    projectRelativeFilePath.append(separator);

    projectRelativeFilePath.append(fileName);
    final IPath projectRelativePath = new Path(projectRelativeFilePath.toString());

    final IFile file = tempProject.getProject().getFile(projectRelativePath);

    // delete file
    if (file.exists()) {
        file.delete(true, null);//from   w w  w .  j  a  v a  2 s  .co m
    }

    // create file
    final ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes());
    file.create(is, true, null);
    int attempts = 0;
    while (!file.exists()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        attempts++;
        if (attempts > 10) {
            throw new IllegalStateException("Failed to create file");
        }
    }

    IJavaProject javaProject = tempProject.getJavaProject();
    if (javaProject == null) {
        throw new IllegalStateException("The temporaryProject does not yet have an associated IJavaProject.");
    }

    // get the compilation unit
    Path srcRelativePath = new Path(fileName);
    ICompilationUnit cu = (ICompilationUnit) javaProject.findElement(srcRelativePath);
    while (cu == null) {
        cu = (ICompilationUnit) javaProject.findElement(srcRelativePath);
    }
    return cu;
}

From source file:org.granite.builder.util.ProjectUtil.java

License:Open Source License

public static JavaClassInfo getJavaClassInfo(IJavaProject project, IFile resource) throws CoreException {
    // classPath = "<project name>/<output folder>/<package>/<file>.class"
    IPath classPath = resource.getFullPath().makeRelative();

    // Find output folder: "<project name>/<output folder>".
    IPath outputFolder = null;//from   w  ww . j a  va  2  s .  c o m
    if (project.getOutputLocation() != null && project.getOutputLocation().isPrefixOf(classPath))
        outputFolder = project.getOutputLocation();
    else {
        for (IClasspathEntry cpe : project.getRawClasspath()) {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath output = cpe.getOutputLocation();
                if (output != null && output.isPrefixOf(classPath)) {
                    outputFolder = output;
                    break;
                }
            }
        }
    }

    if (outputFolder == null)
        return null;

    // Compute class name.
    IPath relativeClassPath = classPath.removeFirstSegments(outputFolder.segmentCount());
    IPath relativeClassName = relativeClassPath.removeFileExtension();
    String className = relativeClassName.toPortableString().replace('/', '.');

    // Compute java source path: "<package>/<class name>[$<inner class>].java".
    String javaFullPath = relativeClassName.addFileExtension("java").toPortableString();
    String javaFilePath = javaFullPath;
    int iDollar = javaFilePath.indexOf('$');
    if (iDollar != -1)
        javaFilePath = javaFilePath.substring(0, iDollar) + ".java";

    IJavaElement javaElement = project.findElement(new Path(javaFilePath));
    if (javaElement == null)
        return null;

    IJavaElement sourceFolder = javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (sourceFolder == null)
        return null;

    IPath folderPath = sourceFolder.getPath().makeRelative();
    if (folderPath.segmentCount() > 0)
        folderPath = folderPath.removeFirstSegments(1);

    // Fix issues with project not in the workspace directory.
    outputFolder = project.getProject().getWorkspace().getRoot().findMember(outputFolder).getLocation();

    return new JavaClassInfo(folderPath.toPortableString(), javaFullPath, className,
            new File(outputFolder.toPortableString(), relativeClassPath.toPortableString()));
}