Example usage for org.eclipse.jdt.core IPackageFragmentRoot getRawClasspathEntry

List of usage examples for org.eclipse.jdt.core IPackageFragmentRoot getRawClasspathEntry

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragmentRoot getRawClasspathEntry.

Prototype

IClasspathEntry getRawClasspathEntry() throws JavaModelException;

Source Link

Document

Returns the first raw classpath entry that corresponds to this package fragment root.

Usage

From source file:at.bestsolution.fxide.jdt.corext.javadoc.JavaDocLocations.java

License:Open Source License

public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
    if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
        return getProjectJavadocLocation((IJavaProject) element);
    }//  w  ww  .  j ava2s  . c  om

    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root == null) {
        return null;
    }

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
        IClasspathEntry entry = root.getResolvedClasspathEntry();
        URL javadocLocation = getLibraryJavadocLocation(entry);
        if (javadocLocation != null) {
            return getLibraryJavadocLocation(entry);
        }
        entry = root.getRawClasspathEntry();
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
            return getLibraryJavadocLocation(entry);
        default:
            return null;
        }
    } else {
        return getProjectJavadocLocation(root.getJavaProject());
    }
}

From source file:at.bestsolution.fxide.jdt.corext.util.JavaModelUtil.java

License:Open Source License

/**
 * Returns the classpath entry of the given package fragment root. This is the raw entry, except
 * if the root is a referenced library, in which case it's the resolved entry.
 *
 * @param root a package fragment root//from  w w  w . j a  v  a  2  s .c  om
 * @return the corresponding classpath entry
 * @throws JavaModelException if accessing the entry failed
 * @since 3.6
 */
public static IClasspathEntry getClasspathEntry(IPackageFragmentRoot root) throws JavaModelException {
    IClasspathEntry rawEntry = root.getRawClasspathEntry();
    int rawEntryKind = rawEntry.getEntryKind();
    switch (rawEntryKind) {
    case IClasspathEntry.CPE_LIBRARY:
    case IClasspathEntry.CPE_VARIABLE:
    case IClasspathEntry.CPE_CONTAINER: // should not happen, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037
        if (root.isArchive() && root.getKind() == IPackageFragmentRoot.K_BINARY) {
            IClasspathEntry resolvedEntry = root.getResolvedClasspathEntry();
            if (resolvedEntry.getReferencingEntry() != null)
                return resolvedEntry;
            else
                return rawEntry;
        }
    }
    return rawEntry;
}

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

License:Open Source License

private static String getSourceAttachmentEncoding(IPackageFragmentRoot root) throws JavaModelException {
    String encoding = ResourcesPlugin.getEncoding();
    IClasspathEntry entry = root.getRawClasspathEntry();

    if (entry != null) {
        int kind = entry.getEntryKind();
        if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) {
            IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
            for (int i = 0; i < extraAttributes.length; i++) {
                IClasspathAttribute attrib = extraAttributes[i];
                if (IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING.equals(attrib.getName())) {
                    return attrib.getValue();
                }//w ww .j  a  va 2s  .c  om
            }
        }
    }

    return encoding;
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

private boolean appendVariableLabel(IPackageFragmentRoot root, long flags) {
    try {//w  ww .  ja v  a  2s .c  o  m
        IClasspathEntry rawEntry = root.getRawClasspathEntry();
        if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
            IClasspathEntry entry = JavaModelUtil.getClasspathEntry(root);
            if (entry.getReferencingEntry() != null) {
                return false; // not the variable entry itself, but a referenced entry
            }
            IPath path = rawEntry.getPath().makeRelative();

            if (getFlag(flags, JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED)) {
                int segements = path.segmentCount();
                if (segements > 0) {
                    fBuffer.append(path.segment(segements - 1));
                    if (segements > 1) {
                        int offset = fBuffer.length();
                        fBuffer.append(JavaElementLabels.CONCAT_STRING);
                        fBuffer.append(path.removeLastSegments(1).toOSString());
                        //                     if (getFlag(flags, JavaElementLabels.COLORIZE)) {
                        //                        fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
                        //                     }
                    }
                } else {
                    fBuffer.append(path.toString());
                }
            } else {
                fBuffer.append(path.toString());
            }
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            if (root.isExternal())
                fBuffer.append(root.getPath().toOSString());
            else
                fBuffer.append(root.getPath().makeRelative().toString());

            //            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            //               fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
            //            }
            return true;
        }
    } catch (JavaModelException e) {
        // problems with class path, ignore (bug 202792)
        return false;
    }
    return false;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.JavaElement.java

License:Open Source License

protected URL getJavadocBaseLocation() throws JavaModelException {
    IPackageFragmentRoot root = (IPackageFragmentRoot) getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (root == null) {
        return null;
    }//  w  w w  .  ja  v a 2  s.  c  o  m

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
        IClasspathEntry entry = null;
        try {
            entry = root.getResolvedClasspathEntry();
            URL url = getLibraryJavadocLocation(entry);
            if (url != null) {
                return url;
            }
        } catch (JavaModelException jme) {
            // Proceed with raw classpath
        }

        entry = root.getRawClasspathEntry();
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
            return getLibraryJavadocLocation(entry);
        default:
            return null;
        }
    }
    return null;
}

From source file:com.drgarbage.bytecodevisualizer.editors.NoSourceViewer.java

License:Apache License

private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root)
        throws JavaModelException {
    IClasspathEntry entry;/* ww w  . j  a v  a  2 s  . co  m*/
    try {
        entry = root.getRawClasspathEntry();
    } catch (JavaModelException ex) {
        if (ex.isDoesNotExist())
            entry = null;
        else
            throw ex;
    }
    IPath containerPath = null;

    if (entry == null || root.getKind() != IPackageFragmentRoot.K_BINARY) {
        String s = CoreMessages.SourceAttachmentForm_message_noSource;
        createLabel(composite, MessageFormat.format(s, new Object[] { fFile.getElementName() }));
        return;
    }

    IJavaProject jproject = root.getJavaProject();
    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
        containerPath = entry.getPath();
        ClasspathContainerInitializer initializer = JavaCore
                .getClasspathContainerInitializer(containerPath.segment(0));
        IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, jproject);
        if (initializer == null || container == null) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_cannotconfigure,
                    new Object[] { containerPath.toString() }));
            return;
        }
        String containerName = container.getDescription();
        IStatus status = initializer.getSourceAttachmentStatus(containerPath, jproject);
        if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_notsupported,
                    new Object[] { containerName }));
            return;
        }
        if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_readonly,
                    new Object[] { containerName }));
            return;
        }
        entry = JavaModelUtil.findEntryInContainer(container, root.getPath());
        Assert.isNotNull(entry);
    }

    Button button;

    String msg = null;
    String btnText = null;

    IPath path = entry.getSourceAttachmentPath();
    if (path == null || path.isEmpty()) {
        msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceAttachment,
                new Object[] { root.getElementName() });
        btnText = CoreMessages.SourceAttachmentForm_button_attachSource;
    } else {
        msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceInAttachment,
                new Object[] { fFile.getElementName() });
        btnText = CoreMessages.SourceAttachmentForm_button_changeAttachedSource;
    }

    createLabel(composite, msg);
    createLabel(composite, CoreMessages.SourceAttachmentForm_message_pressButtonToAttach);
    createLabel(composite, null);

    button = createButton(composite, btnText);
    button.addSelectionListener(createButtonListener(entry, containerPath, jproject));
}

From source file:com.google.gdt.eclipse.core.ClasspathUtilities.java

License:Open Source License

/**
 * Return the raw classpath entry on the project's classpath that contributes
 * the given type to the project.//from w  ww  .j  a va  2s  . com
 * 
 * @param javaProject The java project
 * @param fullyQualifiedName The fully-qualified type name
 * @return The raw classpath entry that contributes the type to the project,
 *         or <code>null</code> if no such classpath entry can be found.
 * @throws JavaModelException
 */
public static IClasspathEntry findRawClasspathEntryFor(IJavaProject javaProject, String fullyQualifiedName)
        throws JavaModelException {
    IType type = javaProject.findType(fullyQualifiedName);
    if (type != null) {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
                .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

        JavaProject jProject = (JavaProject) javaProject;

        IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
        for (IClasspathEntry rawClasspathEntry : rawClasspath) {
            IClasspathEntry[] resolvedClasspath = jProject
                    .resolveClasspath(new IClasspathEntry[] { rawClasspathEntry });
            IPackageFragmentRoot[] computePackageFragmentRoots = jProject
                    .computePackageFragmentRoots(resolvedClasspath, true, null);
            if (Arrays.asList(computePackageFragmentRoots).contains(packageFragmentRoot)) {
                return rawClasspathEntry;
            }
        }

        return packageFragmentRoot.getRawClasspathEntry();
    }

    return null;
}

From source file:com.google.gdt.eclipse.designer.actions.deploy.DeployModuleAction.java

License:Open Source License

/**
 * Returns ANT code for creating jar's for given project itself, coping its jar's from classpath
 * and calls itself for required projects.
 *///w ww.  j a v  a2  s . c om
private static String prepareJars(IProject project, String targetModulePath, boolean addRuntimeJars)
        throws Exception {
    String script = "";
    //
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    // add <jar> task for creating jar from project source and output folders
    {
        List<String> sourceLocations = Lists.newArrayList();
        List<String> binaryLocations = Lists.newArrayList();
        for (IPackageFragmentRoot packageFragmentRoot : roots) {
            if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                // add source location
                sourceLocations.add(packageFragmentRoot.getResource().getLocation().toPortableString());
                // add output location
                {
                    // prepare output location
                    IPath location;
                    {
                        IClasspathEntry cpEntry = packageFragmentRoot.getRawClasspathEntry();
                        location = cpEntry.getOutputLocation();
                        if (location == null) {
                            location = javaProject.getOutputLocation();
                        }
                    }
                    // add absolute location
                    {
                        // remove first segment (project)
                        location = location.removeFirstSegments(1);
                        // prepare absolute location
                        IPath absoluteLocation = project.getLocation().append(location);
                        binaryLocations.add(absoluteLocation.toPortableString());
                    }
                }
            }
        }
        //
        script += "\t\t<!--=== " + project.getName() + " ===-->\n";
        script += "\t\t<jar destfile='" + targetModulePath + "/WEB-INF/lib/" + project.getName() + ".jar'>\n";
        script += prepareFileSets(sourceLocations, "**");
        script += prepareFileSets(binaryLocations, "**/*.class");
        script += "\t\t</jar>\n";
    }
    // add <copy> task for coping required runtime jar's
    if (addRuntimeJars) {
        String jars = "";
        IRuntimeClasspathEntry[] classpathEntries = JavaRuntime.computeUnresolvedRuntimeClasspath(javaProject);
        for (int entryIndex = 0; entryIndex < classpathEntries.length; entryIndex++) {
            IRuntimeClasspathEntry entry = classpathEntries[entryIndex];
            IRuntimeClasspathEntry[] resolvedEntries = JavaRuntime.resolveRuntimeClasspathEntry(entry,
                    javaProject);
            for (int resolvedEntryIndex = 0; resolvedEntryIndex < resolvedEntries.length; resolvedEntryIndex++) {
                IRuntimeClasspathEntry resolvedEntry = resolvedEntries[resolvedEntryIndex];
                if (resolvedEntry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES
                        && resolvedEntry.getType() == IRuntimeClasspathEntry.ARCHIVE) {
                    String location = resolvedEntry.getLocation();
                    // exclude gwt-user.jar, it is in classpath, but it has Servlet class, so can not be in application
                    if (location.endsWith("gwt-user.jar")) {
                        continue;
                    }
                    // add jar file in fileset
                    jars += "\t\t\t<fileset file=\"" + location + "\"/>\n";
                }
            }
        }
        //
        if (jars.length() != 0) {
            script += "\t\t<copy todir='" + targetModulePath + "/WEB-INF/lib'>\n";
            script += jars;
            script += "\t\t</copy>\n";
        }
    }
    // add required projects
    {
        IProject[] referencedProjects = project.getReferencedProjects();
        for (int i = 0; i < referencedProjects.length; i++) {
            IProject referencedProject = referencedProjects[i];
            script += prepareJars(referencedProject, targetModulePath, false);
        }
    }
    //
    return script;
}

From source file:com.google.gwt.eclipse.core.validators.java.JsniJavaRef.java

License:Open Source License

public IJavaElement resolveJavaElement(IJavaProject project) throws UnresolvedJsniJavaRefException {
    IJavaElement element = null;/*from   w  w w . j  ava 2  s . c o  m*/

    // 0. Ignore the magic null reference
    if (className().equals("null")) {
        throw new UnresolvedJsniJavaRefException(null, this);
    }

    // 1. Try to find the type in the project's classpath
    IType type = JavaModelSearch.findType(project, dottedClassName());
    if (type == null) {
        throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, this);
    }

    // TODO: remove this check once we can validate against super source

    // 1A. Do not validate JRE types (they could contain references to members
    // which are only defined in the emulated versions in super source)
    if (type.isBinary()) {
        IPackageFragmentRoot pkgRoot = (IPackageFragmentRoot) type
                .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        try {
            IClasspathEntry cpEntry = pkgRoot.getRawClasspathEntry();
            if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER
                    && cpEntry.getPath().segment(0).equals(JavaRuntime.JRE_CONTAINER)) {
                throw new UnresolvedJsniJavaRefException(null, this);
            }
        } catch (JavaModelException e) {
            GWTPluginLog.logError(e);
            throw new UnresolvedJsniJavaRefException(null, this);
        }
    }

    // 2. Create a super-type hierarchy for the type, which we'll use for
    // finding its super classes and implemented interfaces
    ITypeHierarchy hierarchy;
    try {
        hierarchy = type.newSupertypeHierarchy(null);
    } catch (JavaModelException e) {
        GWTPluginLog.logError(e, "Error creating type hierarchy for " + className());
        throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_UNRESOLVED_TYPE, this);
    }

    if (isMethod()) {
        if (isConstructor()) {
            if (matchesAnyOverload()) {
                element = JavaModelSearch.findFirstCtor(type);
            } else {
                String[] ctorParamTypes = paramTypes();
                try {
                    /*
                     * If the constructor is on a non-static inner class, the reference
                     * will have an extra parameter that specifies the enclosing type.
                     * We'll need to check that type and then remove the parameter
                     * before using JavaModelSearch to find the constructor.
                     */
                    IJavaElement typeParent = type.getParent();
                    if (typeParent.getElementType() == IJavaElement.TYPE && !Flags.isStatic(type.getFlags())) {

                        // Make sure we do have the enclosing type as the first parameter
                        if (ctorParamTypes.length == 0) {
                            throw new UnresolvedJsniJavaRefException(
                                    GWTProblemType.JSNI_JAVA_REF_NO_MATCHING_CTOR, this);
                        }

                        // Now verify that the type of the first parameter is actually the
                        // the same type as the enclosing type
                        IType parentType = (IType) typeParent;
                        String enclosingTypeName = parentType.getFullyQualifiedName('.');
                        String enclosingTypeParam = JavaModelSearch.getQualifiedTypeName(ctorParamTypes[0]);
                        if (!enclosingTypeName.equals(enclosingTypeParam)) {
                            throw new UnresolvedJsniJavaRefException(
                                    GWTProblemType.JSNI_JAVA_REF_NO_MATCHING_CTOR, this);
                        }

                        // Drop the first parameter (the enclosing type)
                        ctorParamTypes = new String[paramTypes().length - 1];
                        System.arraycopy(paramTypes(), 1, ctorParamTypes, 0, ctorParamTypes.length);
                    }
                } catch (JavaModelException e) {
                    GWTPluginLog.logError(e);
                    // Continue on and try to resolve the reference anyway
                }

                // 3A. Find a constructor for this type with matching parameter types
                element = JavaModelSearch.findCtorInHierarchy(hierarchy, type, ctorParamTypes);
                if (element == null) {
                    throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_NO_MATCHING_CTOR,
                            this);
                }
            }
        } else {
            // 3B. Find a method for this type with the same name
            element = JavaModelSearch.findMethodInHierarchy(hierarchy, type, memberName());
            if (element == null) {
                try {
                    if (type.isEnum()) {
                        // Ignore the magic Enum::values() method
                        if (memberName().equals("values") && !matchesAnyOverload()
                                && paramTypes().length == 0) {
                            // Throwing this exception with a null GWTProblemType indicates
                            // that the ref doesn't resolve, but can be ignored anyway.
                            throw new UnresolvedJsniJavaRefException(null, this);
                        }
                    }
                } catch (JavaModelException e) {
                    GWTPluginLog.logError(e);
                }

                throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_MISSING_METHOD, this);
            }

            if (!matchesAnyOverload()) {
                // Now try to match the method's parameter types
                element = JavaModelSearch.findMethodInHierarchy(hierarchy, type, memberName(), paramTypes());
                if (element == null) {
                    try {
                        if (type.isEnum()) {
                            // Ignore the synthetic Enum::valueOf(String) method.
                            // Note that valueOf(Class,String) is not synthetic.
                            if (memberName().equals("valueOf") && paramTypes().length == 1
                                    && paramTypes()[0].equals("Ljava/lang/String;")) {
                                // Throwing this exception with a null GWTProblemType
                                // indicates that the ref doesn't resolve, but can be ignored
                                // anyway.
                                throw new UnresolvedJsniJavaRefException(null, this);
                            }
                        }
                    } catch (JavaModelException e) {
                        GWTPluginLog.logError(e);
                    }

                    throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_NO_MATCHING_METHOD,
                            this);
                }
            }
        }

    } else {
        // 3C. Find a field with the same name
        assert (isField());
        element = JavaModelSearch.findFieldInHierarchy(hierarchy, type, memberName());
        if (element == null) {
            throw new UnresolvedJsniJavaRefException(GWTProblemType.JSNI_JAVA_REF_MISSING_FIELD, this);
        }
    }

    assert (element != null);
    return element;
}

From source file:com.ibm.research.tours.content.url.delegates.ClassFileTextRegionURLTourElementDelegate.java

License:Open Source License

private void init() {
    IPackageFragmentRoot root = null;
    root = JavaModelUtil.getPackageFragmentRoot(fFile);

    IClasspathEntry entry = null;/*w  w w.ja  v a2 s.c o  m*/
    try {
        entry = root.getRawClasspathEntry();
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
        IPath path = entry.getPath().makeRelative();
    }
}