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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.jst.jsp.core.internal.java.search.JSPIndexManager.java

License:Open Source License

/**
 * @see indexer.internal.indexing.AbstractIndexManager#performAction(byte, byte, org.eclipse.core.resources.IResource, org.eclipse.core.runtime.IPath)
 *///w  w w. java 2 s. c  o  m
protected void performAction(byte source, byte action, IResource resource, IPath movePath) {

    //inform the persister of the action unless it come from a full workspace scan
    if (JSPTranslatorPersister.ACTIVATED && source != AbstractIndexManager.SOURCE_WORKSPACE_SCAN) {
        switch (action) {
        case AbstractIndexManager.ACTION_ADD: {
            JSPTranslatorPersister.persistTranslation(resource);
            break;
        }
        case AbstractIndexManager.ACTION_REMOVE: {
            JSPTranslatorPersister.removePersistedTranslation(resource);
            break;
        }
        case AbstractIndexManager.ACTION_ADD_MOVE_FROM: {
            JSPTranslatorPersister.movePersistedTranslation(resource, movePath);
            break;
        }
        case AbstractIndexManager.ACTION_REMOVE_MOVE_TO: {
            //do nothing, taken care of by AbstractIndexManager.ACTION_ADD_MOVE_FROM
            break;
        }
        }
    }

    //add any new JSP files to the JDT index using the JSPSearchSupport
    if (action == AbstractIndexManager.ACTION_ADD || action == AbstractIndexManager.ACTION_ADD_MOVE_FROM) {

        IFile file = (IFile) resource; //this assumption can be made because of #isResourceToIndex
        JSPSearchSupport ss = JSPSearchSupport.getInstance();
        try {
            IProject project = file.getProject();
            if (project != null) {
                IJavaProject jproject = JavaCore.create(project);
                if (jproject.exists()) {
                    ss.addJspFile(file);
                }
            }
        } catch (Exception e) {
            String filename = file != null ? file.getFullPath().toString() : ""; //$NON-NLS-1$
            Logger.logException("JPSIndexManger: problem indexing:" + filename, e); //$NON-NLS-1$
        }
    }
}

From source file:org.eclipse.jst.jsp.core.internal.taglib.TaglibHelper.java

License:Open Source License

/**
 * @param file/*  w ww.j  ava2  s  . c o m*/
 *            The fFile to set.
 */
public void setProject(IProject p) {
    fProject = p;
    IJavaProject javaProject = JavaCore.create(p);
    if (javaProject.exists()) {
        fJavaProject = javaProject;
    }
}

From source file:org.eclipse.jst.jsp.core.internal.validation.TLDValidator.java

License:Open Source License

public ValidationResult validate(IResource resource, int kind, ValidationState state,
        IProgressMonitor monitor) {//  w w  w .  ja v  a 2 s.c o m
    if (resource.getType() != IResource.FILE)
        return null;
    ValidationResult result = new ValidationResult();

    IFile file = (IFile) resource;
    if (file.isAccessible()) {
        // TAGX
        if (fTagXexts.contains(file.getFileExtension()) || fTagXnames.contains(file.getName())) {
            monitor.beginTask("", 4);
            org.eclipse.wst.xml.core.internal.validation.eclipse.Validator xmlValidator = new org.eclipse.wst.xml.core.internal.validation.eclipse.Validator();
            ValidationResult result3 = new MarkupValidator().validate(resource, kind, state,
                    new SubProgressMonitor(monitor, 1));
            if (monitor.isCanceled())
                return result;
            ValidationResult result2 = xmlValidator.validate(resource, kind, state,
                    new SubProgressMonitor(monitor, 1));
            if (monitor.isCanceled())
                return result;
            ValidationResult result1 = new JSPActionValidator().validate(resource, kind, state,
                    new SubProgressMonitor(monitor, 1));
            List messages = new ArrayList(result1.getReporter(new NullProgressMonitor()).getMessages());
            messages.addAll(result2.getReporter(new NullProgressMonitor()).getMessages());
            messages.addAll(result3.getReporter(new NullProgressMonitor()).getMessages());
            messages.addAll(new JSPDirectiveValidator()
                    .validate(resource, kind, state, new SubProgressMonitor(monitor, 1))
                    .getReporter(new NullProgressMonitor()).getMessages());
            for (int i = 0; i < messages.size(); i++) {
                IMessage message = (IMessage) messages.get(i);
                if (message.getText() != null && message.getText().length() > 0) {
                    ValidatorMessage vmessage = ValidatorMessage.create(message.getText(), resource);
                    if (message.getAttributes() != null) {
                        Map attrs = message.getAttributes();
                        Iterator it = attrs.entrySet().iterator();
                        while (it.hasNext()) {
                            Map.Entry entry = (Map.Entry) it.next();
                            if (!(entry.getValue() instanceof String || entry.getValue() instanceof Integer
                                    || entry.getValue() instanceof Boolean)) {
                                it.remove();
                            }
                        }
                        vmessage.setAttributes(attrs);
                    }
                    vmessage.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber());
                    vmessage.setAttribute(IMarker.MESSAGE, message.getText());
                    if (message.getOffset() > -1) {
                        vmessage.setAttribute(IMarker.CHAR_START, message.getOffset());
                        vmessage.setAttribute(IMarker.CHAR_END, message.getOffset() + message.getLength());
                    }
                    int severity = 0;
                    switch (message.getSeverity()) {
                    case IMessage.HIGH_SEVERITY:
                        severity = IMarker.SEVERITY_ERROR;
                        break;
                    case IMessage.NORMAL_SEVERITY:
                        severity = IMarker.SEVERITY_WARNING;
                        break;
                    case IMessage.LOW_SEVERITY:
                        severity = IMarker.SEVERITY_INFO;
                        break;
                    }
                    vmessage.setAttribute(IMarker.SEVERITY, severity);
                    vmessage.setType(MARKER_TYPE);
                    result.add(vmessage);
                }
            }
            monitor.done();
        }
        // TLD
        else {
            try {
                final IJavaProject javaProject = JavaCore.create(file.getProject());
                if (javaProject.exists()) {
                    IScopeContext[] scopes = new IScopeContext[] { new InstanceScope(), new DefaultScope() };
                    ProjectScope projectScope = new ProjectScope(file.getProject());
                    if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER)
                            .getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) {
                        scopes = new IScopeContext[] { projectScope, new InstanceScope(), new DefaultScope() };
                    }
                    Map[] problems = detectProblems(javaProject, file, scopes);
                    for (int i = 0; i < problems.length; i++) {
                        ValidatorMessage message = ValidatorMessage
                                .create(problems[i].get(IMarker.MESSAGE).toString(), resource);
                        message.setType(MARKER_TYPE);
                        message.setAttributes(problems[i]);
                        result.add(message);
                    }
                }
            } catch (Exception e) {
                Logger.logException(e);
            }
        }
    }

    return result;
}

From source file:org.eclipse.jst.jsp.core.taglib.ProjectDescription.java

License:Open Source License

private void ensureUpTodate() {
    IClasspathEntry[] entries = null;/* ww w  .j a  v  a 2  s. co  m*/
    try {
        /*
         * If the Java nature isn't present (or something else is
         * wrong), don't check the build path.
         */
        IJavaProject jproject = JavaCore.create(fProject);
        if (jproject != null && jproject.exists()) {
            entries = jproject.getResolvedClasspath(true);
        }
    } catch (JavaModelException e) {
        Logger.logException(e);
    }
    if (entries != null) {
        try {
            LOCK.acquire();
            /*
             * Double-check that the number of build path entries has not
             * changed. This should cover most cases such as when a
             * library is added into or removed from a container.
             */
            fBuildPathIsDirty = fBuildPathIsDirty || (fBuildPathEntryCount != entries.length);

            if (fBuildPathIsDirty) {
                indexClasspath(entries);
                fBuildPathIsDirty = false;
            } else {
                PackageFragmentRootDelta[] removes = (PackageFragmentRootDelta[]) fPackageFragmentRootsRemoved
                        .values().toArray(new PackageFragmentRootDelta[fPackageFragmentRootsRemoved.size()]);
                for (int i = 0; i < removes.length; i++) {
                    handleElementChanged(removes[i].elementPath, removes[i].deltaKind, removes[i].isExported);
                }
                PackageFragmentRootDelta[] changes = (PackageFragmentRootDelta[]) fPackageFragmentRootsChanged
                        .values().toArray(new PackageFragmentRootDelta[fPackageFragmentRootsChanged.size()]);
                for (int i = 0; i < changes.length; i++) {
                    handleElementChanged(changes[i].elementPath, changes[i].deltaKind, changes[i].isExported);
                }
                PackageFragmentRootDelta[] adds = (PackageFragmentRootDelta[]) fPackageFragmentRootsAdded
                        .values().toArray(new PackageFragmentRootDelta[fPackageFragmentRootsAdded.size()]);
                for (int i = 0; i < adds.length; i++) {
                    handleElementChanged(adds[i].elementPath, adds[i].deltaKind, adds[i].isExported);
                }
                fPackageFragmentRootsRemoved.clear();
                fPackageFragmentRootsChanged.clear();
                fPackageFragmentRootsAdded.clear();
            }
        } finally {
            LOCK.release();
        }
    }
}

From source file:org.eclipse.jst.jsp.core.tests.taglibindex.TestIndex.java

License:Open Source License

public void testAvailableFromExportedOnBuildpathFromAnotherProject() throws Exception {
    TaglibIndex.shutdown();/*from  w ww .  ja va  2s .  co  m*/

    // Create project 1
    IProject project = BundleResourceUtil.createSimpleProject("testavailable1", null, null);
    assertTrue(project.isAccessible());
    BundleResourceUtil.copyBundleEntriesIntoWorkspace("/testfiles/testavailable1", "/testavailable1");

    // Create project 2
    IProject project2 = BundleResourceUtil.createSimpleProject("testavailable2", null, null);
    assertTrue(project2.isAccessible());
    BundleResourceUtil.copyBundleEntriesIntoWorkspace("/testfiles/testavailable2", "/testavailable2");
    BundleResourceUtil.copyBundleEntryIntoWorkspace("/testfiles/bug_118251-sample/sample_tld.jar",
            "/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar");

    TaglibIndex.startup();

    // make sure project 1 sees no taglibs
    ITaglibRecord[] records = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable1/WebContent"));
    assertEquals("ITaglibRecords were found", 0, records.length);
    // make sure project 2 sees two taglibs
    ITaglibRecord[] records2 = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable2/WebContent"));
    if (records2.length != 2) {
        for (int i = 0; i < records2.length; i++) {
            System.err.println(records2[i]);
        }
    }
    assertEquals("total ITaglibRecord count doesn't match", 2, records2.length);

    TaglibIndex.shutdown();
    TaglibIndex.startup();

    records2 = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable2/WebContent"));
    assertEquals("total ITaglibRecord count doesn't match after restart", 2, records2.length);

    IJavaProject created = JavaCore.create(project2);
    assertTrue("/availabletest2 not a Java project", created.exists());

    // export the jar from project 2
    IClasspathEntry[] entries = created.getRawClasspath();
    boolean found = false;
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        if (entry.getPath().equals(new Path("/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar"))) {
            found = true;
            assertFalse("was exported", entry.isExported());
            ((ClasspathEntry) entry).isExported = true;
        }
    }
    assertTrue("/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar was not found in build path", found);
    IClasspathEntry[] entries2 = new IClasspathEntry[entries.length];
    System.arraycopy(entries, 1, entries2, 0, entries.length - 1);
    entries2[entries.length - 1] = entries[0];
    created.setRawClasspath(entries2, new NullProgressMonitor());

    entries = created.getRawClasspath();
    found = false;
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        if (entry.getPath().equals(new Path("/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar"))) {
            found = true;
            assertTrue("/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar was not exported",
                    ((ClasspathEntry) entry).isExported);
        }
    }
    assertTrue(
            "/testavailable2/WebContent/WEB-INF/lib/sample_tld.jar was not found (and exported) in build path",
            found);

    // project 2 should still have just two taglibs
    records = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable2/WebContent"));
    assertEquals("total ITaglibRecord count doesn't match (after exporting jar)", 2, records.length);

    // now one taglib should be visible from project 1
    records = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable1/WebContent"));
    assertEquals("total ITaglibRecord count doesn't match (after exporting jar), classpath provider problem?",
            1, records.length);

    TaglibIndex.shutdown();
    TaglibIndex.startup();

    // project 2 should still have just two taglibs
    records = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable2/WebContent"));
    assertEquals("total ITaglibRecord count doesn't match (after exporting jar and restarting)", 2,
            records.length);

    // and one taglib should still be visible from project 1
    records = TaglibIndex.getAvailableTaglibRecords(new Path("/testavailable1/WebContent"));
    assertEquals("total ITaglibRecord count doesn't match (after exporting jar and restarting)", 1,
            records.length);
}

From source file:org.eclipse.jst.jsp.ui.internal.hyperlink.XMLJavaHyperlinkDetector.java

License:Open Source License

private IHyperlink createHyperlink(String elementName, IRegion region, IDocument document) {
    // try file buffers
    ITextFileBuffer textFileBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
    if (textFileBuffer != null) {
        IPath basePath = textFileBuffer.getLocation();
        if (basePath != null && !basePath.isEmpty()) {
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0));
            try {
                if (basePath.segmentCount() > 1 && project.isAccessible()
                        && project.hasNature(JavaCore.NATURE_ID)) {
                    return createJavaElementHyperlink(JavaCore.create(project), elementName, region);
                }//w ww  .ja v a2 s .c  o  m
            } catch (CoreException e) {
                Logger.logException(e);
            }
        }
    }

    // fallback to SSE-specific knowledge
    IStructuredModel model = null;
    try {
        model = StructuredModelManager.getModelManager().getExistingModelForRead(document);
        if (model != null) {
            String baseLocation = model.getBaseLocation();
            // URL fixup from the taglib index record
            if (baseLocation.startsWith("jar:/file:")) { //$NON-NLS-1$
                baseLocation = StringUtils.replace(baseLocation, "jar:/", "jar:"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            /*
             * Handle opened TLD files from JARs on the Java Build Path by
             * finding a package fragment root for the same .jar file and
             * opening the class from there. Note that this might be from
             * a different Java project's build path than the TLD.
             */
            if (baseLocation.startsWith(JAR_FILE_PROTOCOL)
                    && baseLocation.indexOf('!') > JAR_FILE_PROTOCOL.length()) {
                String baseFile = baseLocation.substring(JAR_FILE_PROTOCOL.length(), baseLocation.indexOf('!'));
                IPath basePath = new Path(baseFile);
                IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
                for (int i = 0; i < projects.length; i++) {
                    try {
                        if (projects[i].isAccessible() && projects[i].hasNature(JavaCore.NATURE_ID)) {
                            IJavaProject javaProject = JavaCore.create(projects[i]);
                            if (javaProject.exists()) {
                                IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(basePath);
                                if (root != null) {
                                    return createJavaElementHyperlink(javaProject, elementName, region);
                                }
                            }
                        }
                    } catch (CoreException e) {
                        Logger.logException(e);
                    }
                }
            } else {
                IPath basePath = new Path(baseLocation);
                if (basePath.segmentCount() > 1) {
                    return createJavaElementHyperlink(
                            JavaCore.create(
                                    ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0))),
                            elementName, region);
                }
            }
        }
    } finally {
        if (model != null)
            model.releaseFromRead();
    }
    return null;
}

From source file:org.eclipse.jst.jsp.ui.internal.hyperlink.XMLJavaHyperlinkDetector.java

License:Open Source License

private IHyperlink createJavaElementHyperlink(IJavaProject javaProject, String elementName, IRegion region) {
    if (javaProject != null && javaProject.exists()) {
        try {/*from  w  w w  . ja v  a  2s.co  m*/
            IJavaElement element = javaProject.findType(elementName);
            if (element != null && element.exists()) {
                return new JavaElementHyperlink(region, element);
            }
        } catch (JavaModelException e) {
            // bad name, no link
        }
    }
    return null;
}

From source file:org.eclipse.jst.jsp.ui.internal.taginfo.XMLJavadocHoverProcessor.java

License:Open Source License

public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    String elementName = null;/*from   w w w.jav  a  2  s  .  c  o  m*/
    try {
        elementName = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
    } catch (BadLocationException e) {
        return null;
    }

    IStructuredModel model = null;
    try {
        model = StructuredModelManager.getModelManager().getExistingModelForRead(textViewer.getDocument());
        if (model != null) {
            String baseLocation = model.getBaseLocation();
            // URL fixup from the taglib index record
            if (baseLocation.startsWith("jar:/file:")) {
                baseLocation = StringUtils.replace(baseLocation, "jar:/", "jar:");
            }
            /*
             * Handle opened TLD files from JARs on the Java Build Path by
             * finding a package fragment root for the same .jar file and
             * opening the class from there. Note that this might be from
             * a different Java project's build path than the TLD.
             */
            if (baseLocation.startsWith("jar:file:") && baseLocation.indexOf('!') > 9) {
                String baseFile = baseLocation.substring(9, baseLocation.indexOf('!'));
                IPath basePath = new Path(baseFile);
                IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
                for (int i = 0; i < projects.length; i++) {
                    try {
                        if (projects[i].isAccessible() && projects[i].hasNature(JavaCore.NATURE_ID)) {
                            IJavaProject javaProject = JavaCore.create(projects[i]);
                            if (javaProject.exists()) {
                                IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(basePath);
                                if (root != null) {
                                    // TLDs don't reference method names
                                    IType type = javaProject.findType(elementName);
                                    if (type != null) {
                                        return getHoverInfo(new IJavaElement[] { type });
                                    }
                                }
                            }
                        }
                    } catch (CoreException e) {
                        Logger.logException(e);
                    }
                }
            } else {
                IPath basePath = new Path(baseLocation);
                if (basePath.segmentCount() > 1) {
                    IJavaProject javaProject = JavaCore
                            .create(ResourcesPlugin.getWorkspace().getRoot().getProject(basePath.segment(0)));
                    if (javaProject.exists()) {
                        try {
                            // TLDs don't reference method names
                            IType type = javaProject.findType(elementName);
                            if (type != null) {
                                return getHoverInfo(new IJavaElement[] { type });
                            }
                        } catch (JavaModelException e) {
                            Logger.logException(e);
                        }
                    }
                }
            }
        }

    } finally {
        if (model != null)
            model.releaseFromRead();
    }
    return null;
}

From source file:org.eclipse.jst.jsp.ui.tests.contentassist.BeanInfoProviderTest.java

License:Open Source License

private void openPath(IJavaProject javaProj) {
    try {/*from ww w.  ja  va2s. c om*/
        if (javaProj.exists() && !javaProj.isOpen()) {
            javaProj.open(null);
        }
        IPackageFragmentRoot root = javaProj.getPackageFragmentRoot(fResource.getProject());
        if (!root.isOpen())
            root.open(null);
        IPackageFragment frag = getPackageFragment(root, "BEAN_TESTS");
        openAll(frag);
        frag = getPackageFragment(root, "org");
        if (frag != null && !frag.isOpen())
            openAll(frag);
        frag = getPackageFragment(root, "org.eclipse");
        if (frag != null && !frag.isOpen())
            openAll(frag);
        frag = getPackageFragment(root, "org.eclipse.jst");
        if (frag != null && !frag.isOpen())
            openAll(frag);
        frag = getPackageFragment(root, "org.eclipse.jst.jsp");
        if (frag != null && !frag.isOpen())
            openAll(frag);
        frag = getPackageFragment(root, "org.eclipse.jst.jsp.ui");
        if (frag != null && !frag.isOpen())
            openAll(frag);
        frag = getPackageFragment(root, "org.eclipse.jst.jsp.ui.tests");
        if (frag != null && !frag.isOpen())
            openAll(frag);
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.m2e.jdt.internal.InternalModuleSupport.java

License:Open Source License

/**
 * Sets <code>module</code flag to <code>true</code> to classpath dependencies declared in module-info.java
 * //  ww w .j av  a2s .  c  o  m
 * @param facade a Maven facade project
 * @param classpath a classpath descriptor
 * @param monitor a progress monitor
 */
public static void configureClasspath(IMavenProjectFacade facade, IClasspathDescriptor classpath,
        IProgressMonitor monitor) throws CoreException {
    IJavaProject javaProject = JavaCore.create(facade.getProject());
    if (javaProject == null || !javaProject.exists()) {
        return;
    }
    IModuleDescription moduleDescription = javaProject.getModuleDescription();
    if (!(moduleDescription instanceof AbstractModule)) {
        return;
    }
    AbstractModule module = (AbstractModule) moduleDescription;
    Set<String> requiredModules = Stream.of(module.getRequiredModules()).map(m -> new String(m.name()))
            .collect(Collectors.toSet());
    for (IClasspathEntryDescriptor entry : classpath.getEntryDescriptors()) {
        String moduleName = getModuleName(entry, monitor);
        if (requiredModules.contains(moduleName)) {
            entry.setClasspathAttribute(IClasspathAttribute.MODULE, Boolean.TRUE.toString());
        }
    }
}