Example usage for org.eclipse.jdt.core IPackageFragment getClassFile

List of usage examples for org.eclipse.jdt.core IPackageFragment getClassFile

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IPackageFragment getClassFile.

Prototype

IClassFile getClassFile(String name);

Source Link

Document

Returns the class file with the specified name in this package (for example, "Object.class").

Usage

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

License:Open Source License

/**
 * Returns the Javadoc for a package which could be present in package.html, package-info.java
 * or from an attached Javadoc./*from w  w w  .j  a  va  2  s .co  m*/
 *
 * @param packageFragment the package which is requesting for the document
 * @return the document content in HTML format or <code>null</code> if there is no associated
 *         Javadoc
 * @throws CoreException if the Java element does not exists or an exception occurs while
 *             accessing the file containing the package Javadoc
 * @since 3.9
 */
public static String getHTMLContent(IPackageFragment packageFragment) throws CoreException {
    IPackageFragmentRoot root = (IPackageFragmentRoot) packageFragment
            .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

    //1==> Handle the case when the documentation is present in package-info.java or package-info.class file
    ITypeRoot packageInfo;
    boolean isBinary = root.getKind() == IPackageFragmentRoot.K_BINARY;
    if (isBinary) {
        packageInfo = packageFragment.getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
    } else {
        packageInfo = packageFragment.getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
    }
    if (packageInfo != null && packageInfo.exists()) {
        String cuSource = packageInfo.getSource();
        //the source can be null for some of the class files
        if (cuSource != null) {
            Javadoc packageJavadocNode = getPackageJavadocNode(packageFragment, cuSource);
            if (packageJavadocNode != null) {
                IJavaElement element;
                if (isBinary) {
                    element = ((IClassFile) packageInfo).getType();
                } else {
                    element = packageInfo.getParent(); // parent is the IPackageFragment
                }
                return new JavadocContentAccess2(element, packageJavadocNode, cuSource).toHTML();
            }
        }
    }

    // 2==> Handle the case when the documentation is done in package.html file. The file can be either in normal source folder or coming from a jar file
    else {
        Object[] nonJavaResources = packageFragment.getNonJavaResources();
        // 2.1 ==>If the package.html file is present in the source or directly in the binary jar
        for (Object nonJavaResource : nonJavaResources) {
            if (nonJavaResource instanceof IFile) {
                IFile iFile = (IFile) nonJavaResource;
                if (iFile.exists() && JavaModelUtil.PACKAGE_HTML.equals(iFile.getName())) {
                    return getIFileContent(iFile);
                }
            }
        }

        // 2.2==>The file is present in a binary container
        if (isBinary) {
            for (Object nonJavaResource : nonJavaResources) {
                // The content is from an external binary class folder
                if (nonJavaResource instanceof IJarEntryResource) {
                    IJarEntryResource jarEntryResource = (IJarEntryResource) nonJavaResource;
                    String encoding = getSourceAttachmentEncoding(root);
                    if (JavaModelUtil.PACKAGE_HTML.equals(jarEntryResource.getName())
                            && jarEntryResource.isFile()) {
                        return getHTMLContent(jarEntryResource, encoding);
                    }
                }
            }
            //2.3 ==>The file is present in the source attachment path.
            String contents = getHTMLContentFromAttachedSource(root, packageFragment);
            if (contents != null)
                return contents;
        }
    }

    //3==> Handle the case when the documentation is coming from the attached Javadoc
    if ((root.isArchive() || root.isExternal())) {
        return packageFragment.getAttachedJavadoc(null);

    }

    return null;
}

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

License:Open Source License

/**
 * Creates the handles for the inner types of the given binary type.
 * Adds new handles to the given vector.
 *//* w  w w .j  a va 2 s .  c o m*/
private void generateInnerClassHandles(IType type, IBinaryType typeInfo, ArrayList childrenHandles) {
    // Add inner types
    // If the current type is an inner type, innerClasses returns
    // an extra entry for the current type.  This entry must be removed.
    // Can also return an entry for the enclosing type of an inner type.
    IBinaryNestedType[] innerTypes = typeInfo.getMemberTypes();
    if (innerTypes != null) {
        IPackageFragment pkg = (IPackageFragment) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        for (int i = 0, typeCount = innerTypes.length; i < typeCount; i++) {
            IBinaryNestedType binaryType = innerTypes[i];
            IClassFile parentClassFile = pkg.getClassFile(
                    new String(ClassFile.unqualifiedName(binaryType.getName())) + SUFFIX_STRING_class);
            IType innerType = new BinaryType((JavaElement) parentClassFile,
                    ((JavaElement) parentClassFile).manager, ClassFile.simpleName(binaryType.getName()));
            childrenHandles.add(innerType);
        }
    }
}

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

License:Open Source License

private Openable createElement(File resource, int elementType, RootInfo rootInfo) {
    if (resource == null)
        return null;

    IPath path = new Path(resource.getPath());
    IJavaElement element = null;//from  w w w.j  a  v  a  2s . c om
    switch (elementType) {
    //
    //         case IJavaElement.JAVA_PROJECT:
    //
    //            // note that non-java resources rooted at the project level will also enter this code with
    //            // an elementType JAVA_PROJECT (see #elementType(...)).
    //            if (resource instanceof IProject){
    //
    //               popUntilPrefixOf(path);
    //
    //               if (this.currentElement != null
    //                  && this.currentElement.getElementType() == IJavaElement.JAVA_PROJECT
    //                  && ((IJavaProject)this.currentElement).getProject().equals(resource)) {
    //                  return this.currentElement;
    //               }
    //               if  (rootInfo != null && rootInfo.project.getProject().equals(resource)){
    //                  element = rootInfo.project;
    //                  break;
    //               }
    //               IProject proj = (IProject)resource;
    //               if (JavaProject.hasJavaNature(proj)) {
    //                  element = JavaCore.create(proj);
    //               } else {
    //                  // java project may have been been closed or removed (look for
    //                  // element amongst old java project s list).
    //                  element =  this.state.findJavaProject(proj.getName());
    //               }
    //            }
    //            break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        element = rootInfo == null ? JavaModelManager.create(resource, manager.getJavaProject())
                : rootInfo.getPackageFragmentRoot(resource);
        break;
    case IJavaElement.PACKAGE_FRAGMENT:
        if (rootInfo != null) {
            if (rootInfo.project.contains(resource)) {
                PackageFragmentRoot root = (PackageFragmentRoot) rootInfo.getPackageFragmentRoot(null);
                // create package handle
                IPath pkgPath = path.removeFirstSegments(root.resource().toPath().getNameCount());
                String[] pkgName = pkgPath.segments();
                element = root.getPackageFragment(pkgName);
            }
        } else {
            // find the element that encloses the resource
            popUntilPrefixOf(path);

            if (this.currentElement == null) {
                element = JavaCore.create(resource);
            } else {
                // find the root
                PackageFragmentRoot root = this.currentElement.getPackageFragmentRoot();
                if (root == null) {
                    element = JavaCore.create(resource);
                } else if (((JavaProject) root.getJavaProject()).contains(resource)) {
                    // create package handle
                    IPath pkgPath = path.removeFirstSegments(root.getPath().segmentCount());
                    String[] pkgName = pkgPath.segments();
                    element = root.getPackageFragment(pkgName);
                }
            }
        }
        break;
    case IJavaElement.COMPILATION_UNIT:
    case IJavaElement.CLASS_FILE:
        // find the element that encloses the resource
        popUntilPrefixOf(path);

        if (this.currentElement == null) {
            element = rootInfo == null ? JavaModelManager.create(resource, manager.getJavaProject())
                    : JavaModelManager.create(resource, rootInfo.project);
        } else {
            // find the package
            IPackageFragment pkgFragment = null;
            switch (this.currentElement.getElementType()) {
            case IJavaElement.PACKAGE_FRAGMENT_ROOT:
                PackageFragmentRoot root = (PackageFragmentRoot) this.currentElement;
                IPath rootPath = root.getPath();
                IPath pkgPath = path.removeLastSegments(1);
                String[] pkgName = pkgPath.removeFirstSegments(rootPath.segmentCount()).segments();
                pkgFragment = root.getPackageFragment(pkgName);
                break;
            case IJavaElement.PACKAGE_FRAGMENT:
                Openable pkg = this.currentElement;
                if (pkg.getPath().equals(path.removeLastSegments(1))) {
                    pkgFragment = (IPackageFragment) pkg;
                } // else case of package x which is a prefix of x.y
                break;
            case IJavaElement.COMPILATION_UNIT:
            case IJavaElement.CLASS_FILE:
                pkgFragment = (IPackageFragment) this.currentElement.getParent();
                break;
            }
            if (pkgFragment == null) {
                element = rootInfo == null ? JavaCore.create(resource)
                        : JavaModelManager.create(resource, rootInfo.project);
            } else {
                if (elementType == IJavaElement.COMPILATION_UNIT) {
                    // create compilation unit handle
                    // fileName validation has been done in elementType(IResourceDelta, int, boolean)
                    String fileName = path.lastSegment();
                    element = pkgFragment.getCompilationUnit(fileName);
                } else {
                    // create class file handle
                    // fileName validation has been done in elementType(IResourceDelta, int, boolean)
                    String fileName = path.lastSegment();
                    element = pkgFragment.getClassFile(fileName);
                }
            }
        }
        break;
    }
    if (element == null)
        return null;
    this.currentElement = (Openable) element;
    return this.currentElement;
}

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

License:Open Source License

private void updateIndex(Openable element, IResourceDelta delta) {

    IndexManager indexManager = this.manager.indexManager;
    if (indexManager == null)
        return;/*from w  w w  .  ja va 2 s  .  co m*/

    switch (element.getElementType()) {
    case IJavaElement.JAVA_PROJECT:
        switch (delta.getKind()) {
        case IResourceDelta.ADDED:
            indexManager.indexAll((JavaProject) element.getJavaProject());
            break;
        case IResourceDelta.REMOVED:
            indexManager.removeIndexFamily(element.getJavaProject().getProject().getFullPath());
            // NB: Discarding index jobs belonging to this project was done during PRE_DELETE
            break;
        // NB: Update of index if project is opened, closed, or its java nature is added or removed
        //     is done in updateCurrentDeltaAndIndex
        }
        break;
    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        if (element instanceof JarPackageFragmentRoot) {
            JarPackageFragmentRoot root = (JarPackageFragmentRoot) element;
            // index jar file only once (if the root is in its declaring project)
            IPath jarPath = root.getPath();
            switch (delta.getKind()) {
            case IResourceDelta.ADDED:
                // index the new jar
                indexManager.indexLibrary(jarPath, root.getIndexPath());
                break;
            case IResourceDelta.CHANGED:
                // first remove the index so that it is forced to be re-indexed
                indexManager.removeIndex(jarPath);
                // then index the jar
                indexManager.indexLibrary(jarPath, root.getIndexPath());
                break;
            case IResourceDelta.REMOVED:
                // the jar was physically removed: remove the index
                indexManager.discardJobs(jarPath.toString());
                indexManager.removeIndex(jarPath);
                break;
            }
            break;
        }
        int kind = delta.getKind();
        if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED
                || (kind == IResourceDelta.CHANGED && (delta.getFlags() & IResourceDelta.LOCAL_CHANGED) != 0)) {
            PackageFragmentRoot root = (PackageFragmentRoot) element;
            updateRootIndex(root, CharOperation.NO_STRINGS, delta);
            break;
        }
        // don't break as packages of the package fragment root can be indexed below
        // $FALL-THROUGH$
    case IJavaElement.PACKAGE_FRAGMENT:
        switch (delta.getKind()) {
        case IResourceDelta.CHANGED:
            if ((delta.getFlags() & IResourceDelta.LOCAL_CHANGED) == 0)
                break;
            // $FALL-THROUGH$
        case IResourceDelta.ADDED:
        case IResourceDelta.REMOVED:
            IPackageFragment pkg = null;
            if (element instanceof IPackageFragmentRoot) {
                PackageFragmentRoot root = (PackageFragmentRoot) element;
                pkg = root.getPackageFragment(CharOperation.NO_STRINGS);
            } else {
                pkg = (IPackageFragment) element;
            }
            RootInfo rootInfo = rootInfo(pkg.getParent().getPath(), delta.getKind());
            boolean isSource = rootInfo == null // if null, defaults to source
                    || rootInfo.entryKind == IClasspathEntry.CPE_SOURCE;
            IResourceDelta[] children = (IResourceDelta[]) delta.getAffectedChildren();
            for (int i = 0, length = children.length; i < length; i++) {
                IResourceDelta child = children[i];
                IResource resource = child.getResource();
                // TODO (philippe) Why do this? Every child is added anyway as the delta is walked
                if (resource instanceof IFile) {
                    String name = resource.getName();
                    if (isSource) {
                        if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(name)) {
                            Openable cu = (Openable) pkg.getCompilationUnit(name);
                            updateIndex(cu, child);
                        }
                    } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(name)) {
                        Openable classFile = (Openable) pkg.getClassFile(name);
                        updateIndex(classFile, child);
                    }
                }
            }
            break;
        }
        break;
    case IJavaElement.CLASS_FILE:
        //            IFile file = (IFile) delta.getResource();
        //            IJavaProject project = element.getJavaProject();
        //            PackageFragmentRoot root = element.getPackageFragmentRoot();
        //            IPath binaryFolderPath = root.isExternal() && !root.isArchive() ? root.resource().getFullPath() : root.getPath();
        //            // if the class file is part of the binary output, it has been created by
        //            // the java builder -> ignore
        //            try {
        //               if (binaryFolderPath.equals(project.getOutputLocation())) {
        //                  break;
        //               }
        //            } catch (JavaModelException e) {
        //               // project doesn't exist: ignore
        //            }
        //            switch (delta.getKind()) {
        //               case IResourceDelta.CHANGED :
        //                  // no need to index if the content has not changed
        //                  int flags = delta.getFlags();
        //                  if ((flags & IResourceDelta.CONTENT) == 0 && (flags & IResourceDelta.ENCODING) == 0)
        //                     break;
        //                  // $FALL-THROUGH$
        //               case IResourceDelta.ADDED :
        //                  indexManager.addBinary(file, binaryFolderPath);
        //                  break;
        //               case IResourceDelta.REMOVED :
        //                  String containerRelativePath = Util.relativePath(file.getFullPath(), binaryFolderPath.segmentCount());
        //                  indexManager.remove(containerRelativePath, binaryFolderPath);
        //                  break;
        //            }
        break;
    case IJavaElement.COMPILATION_UNIT:
        File file = delta.getFile();
        switch (delta.getKind()) {
        case IResourceDelta.CHANGED:
            // no need to index if the content has not changed
            int flags = delta.getFlags();
            if ((flags & IResourceDelta.CONTENT) == 0 && (flags & IResourceDelta.ENCODING) == 0)
                break;
            // $FALL-THROUGH$
        case IResourceDelta.ADDED:
            indexManager.addSource(file.toPath(), element.getJavaProject().getPath(),
                    getSourceElementParser(element));
            // Clean file from secondary types cache but do not update indexing secondary type cache as it will be updated through indexing itself
            this.manager.secondaryTypesRemoving(file, false);
            break;
        case IResourceDelta.REMOVED:
            indexManager.remove(
                    file.getPath().substring(element.getJavaProject().getPath().toOSString().length()),
                    element.getJavaProject().getPath());
            // Clean file from secondary types cache and update indexing secondary type cache as indexing cannot remove secondary types from cache
            this.manager.secondaryTypesRemoving(file, true);
            break;
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.PackageReferenceLocator.java

License:Open Source License

public static boolean isDeclaringPackageFragment(IPackageFragment packageFragment,
        ReferenceBinding typeBinding) {//www . j  av  a  2  s.  c  om
    char[] fileName = typeBinding.getFileName();
    if (fileName != null) {
        // retrieve the actual file name from the full path (sources are generally only containing it already)
        fileName = CharOperation.replaceOnCopy(fileName, '/', '\\'); // ensure to not do any side effect on file name (see https://bugs.eclipse
        // .org/bugs/show_bug.cgi?id=136016)
        fileName = CharOperation.lastSegment(fileName, '\\');

        try {
            switch (packageFragment.getKind()) {
            case IPackageFragmentRoot.K_SOURCE:
                if (!org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(fileName)
                        || !packageFragment.getCompilationUnit(new String(fileName)).exists()) {
                    return false; // unit doesn't live in selected package
                }
                break;
            case IPackageFragmentRoot.K_BINARY:
                //               if (Util.isJavaFileName(fileName)) { // binary with attached source
                //                  int length = fileName.length;
                //                  System.arraycopy(fileName, 0, fileName = new char[length], 0, length - 4); // copy all but extension
                //                  System.arraycopy(SuffixConstants.SUFFIX_class, 0, fileName, length - 4, 4);
                //               }
                if (!Util.isClassFileName(fileName)
                        || !packageFragment.getClassFile(new String(fileName)).exists()) {
                    return false; // classfile doesn't live in selected package
                }
                break;
            }
        } catch (JavaModelException e) {
            // unable to determine kind; tolerate this match
        }
    }
    return true; // by default, do not eliminate
}

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

License:Open Source License

private IType createTypeFromJar(String resourcePath, int separatorIndex) throws JavaModelException {
    // path to a class file inside a jar
    // Optimization: cache package fragment root handle and package handles
    if (this.lastPkgFragmentRootPath == null || this.lastPkgFragmentRootPath.length() > resourcePath.length()
            || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) {
        String jarPath = resourcePath.substring(0, separatorIndex);
        IPackageFragmentRoot root = ((AbstractJavaSearchScope) this.scope).packageFragmentRoot(resourcePath,
                separatorIndex, jarPath);
        if (root == null)
            return null;
        this.lastPkgFragmentRootPath = jarPath;
        this.lastPkgFragmentRoot = root;
        this.packageHandles = new HashtableOfArrayToObject(5);
    }// w  ww .  j  a va2s  . co  m
    // create handle
    String classFilePath = resourcePath.substring(separatorIndex + 1);
    String[] simpleNames = new Path(classFilePath).segments();
    String[] pkgName;
    int length = simpleNames.length - 1;
    if (length > 0) {
        pkgName = new String[length];
        System.arraycopy(simpleNames, 0, pkgName, 0, length);
    } else {
        pkgName = CharOperation.NO_STRINGS;
    }
    IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
    if (pkgFragment == null) {
        pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
        // filter org.apache.commons.lang.enum package for projects above 1.5 
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264
        if (length == 5 && pkgName[4].equals("enum")) { //$NON-NLS-1$
            IJavaProject proj = (IJavaProject) pkgFragment.getAncestor(IJavaElement.JAVA_PROJECT);
            if (!proj.equals(this.lastProject)) {
                String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
                this.complianceValue = CompilerOptions.versionToJdkLevel(complianceStr);
                this.lastProject = proj;
            }
            if (this.complianceValue >= ClassFileConstants.JDK1_5)
                return null;
        }
        this.packageHandles.put(pkgName, pkgFragment);
    }
    return pkgFragment.getClassFile(simpleNames[length]).getType();
}

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

License:Open Source License

private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames)
        throws JavaModelException {
    // path to a file in a directory
    // Optimization: cache package fragment root handle and package handles
    int rootPathLength = -1;
    if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
            && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0
            && resourcePath.charAt(rootPathLength) == '/')) {
        PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) this.scope)
                .packageFragmentRoot(resourcePath, -1/*not a jar*/, null/*no jar path*/);
        if (root == null)
            return null;
        this.lastPkgFragmentRoot = root;
        this.lastPkgFragmentRootPath = root.internalPath().toString();
        this.packageHandles = new HashtableOfArrayToObject(5);
    }/*from w  w  w.j a  va 2  s. c  o  m*/
    // create handle
    resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
    String[] simpleNames = new Path(resourcePath).segments();
    String[] pkgName;
    int length = simpleNames.length - 1;
    if (length > 0) {
        pkgName = new String[length];
        System.arraycopy(simpleNames, 0, pkgName, 0, length);
    } else {
        pkgName = CharOperation.NO_STRINGS;
    }
    IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
    if (pkgFragment == null) {
        pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName);
        this.packageHandles.put(pkgName, pkgFragment);
    }
    String simpleName = simpleNames[length];
    if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) {
        ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName);
        int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length;
        IType type = (etnLength == 0) ? unit.getType(simpleTypeName)
                : unit.getType(new String(enclosingTypeNames[0]));
        if (etnLength > 0) {
            for (int i = 1; i < etnLength; i++) {
                type = type.getType(new String(enclosingTypeNames[i]));
            }
            type = type.getType(simpleTypeName);
        }
        return type;
    } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) {
        IClassFile classFile = pkgFragment.getClassFile(simpleName);
        return classFile.getType();
    }
    return null;
}

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

License:Open Source License

/**
 * Creates an Openable handle from the given resource path.
 * The resource path can be a path to a file in the workbench (e.g. /Proj/com/ibm/jdt/core/HandleFactory.java)
 * or a path to a file in a jar file - it then contains the path to the jar file and the path to the file in the jar
 * (e.g. c:/jdk1.2.2/jre/lib/rt.jar|java/lang/Object.class or /Proj/rt.jar|java/lang/Object.class)
 * NOTE: This assumes that the resource path is the toString() of an IPath,
 *       in other words, it uses the IPath.SEPARATOR for file path
 *            and it uses '/' for entries in a zip file.
 * If not null, uses the given scope as a hint for getting Java project handles.
 */// w  w  w. j a v a  2s  .co m
public Openable createOpenable(String resourcePath, IJavaSearchScope scope) {
    int separatorIndex;
    if ((separatorIndex = resourcePath.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR)) > -1) {
        // path to a class file inside a jar
        // Optimization: cache package fragment root handle and package handles
        int rootPathLength;
        if (this.lastPkgFragmentRootPath == null
                || (rootPathLength = this.lastPkgFragmentRootPath.length()) != resourcePath.length()
                || !resourcePath.regionMatches(0, this.lastPkgFragmentRootPath, 0, rootPathLength)) {
            String jarPath = resourcePath.substring(0, separatorIndex);
            PackageFragmentRoot root = getJarPkgFragmentRoot(resourcePath, separatorIndex, jarPath, scope);
            if (root == null)
                return null; // match is outside classpath
            this.lastPkgFragmentRootPath = jarPath;
            this.lastPkgFragmentRoot = root;
            this.packageHandles = new HashtableOfArrayToObject(5);
        }
        // create handle
        String classFilePath = resourcePath.substring(separatorIndex + 1);
        String[] simpleNames = new Path(classFilePath).segments();
        String[] pkgName;
        int length = simpleNames.length - 1;
        if (length > 0) {
            pkgName = new String[length];
            System.arraycopy(simpleNames, 0, pkgName, 0, length);
        } else {
            pkgName = CharOperation.NO_STRINGS;
        }
        IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
        if (pkgFragment == null) {
            pkgFragment = this.lastPkgFragmentRoot.getPackageFragment(pkgName);
            this.packageHandles.put(pkgName, pkgFragment);
        }
        IClassFile classFile = pkgFragment.getClassFile(simpleNames[length]);
        return (Openable) classFile;
    } else {
        // path to a file in a directory
        // Optimization: cache package fragment root handle and package handles
        int rootPathLength = -1;
        if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
                && !org.eclipse.jdt.internal.compiler.util.Util.isExcluded(resourcePath.toCharArray(),
                        this.lastPkgFragmentRoot.fullInclusionPatternChars(),
                        this.lastPkgFragmentRoot.fullExclusionPatternChars(), false)
                && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0
                && resourcePath.charAt(rootPathLength) == '/')) {
            PackageFragmentRoot root = getPkgFragmentRoot(resourcePath);
            if (root == null)
                return null; // match is outside classpath
            this.lastPkgFragmentRoot = root;
            this.lastPkgFragmentRootPath = this.lastPkgFragmentRoot.internalPath().toString();
            this.packageHandles = new HashtableOfArrayToObject(5);
        }
        // create handle
        resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1);
        String[] simpleNames = new Path(resourcePath).segments();
        String[] pkgName;
        int length = simpleNames.length - 1;
        if (length > 0) {
            pkgName = new String[length];
            System.arraycopy(simpleNames, 0, pkgName, 0, length);
        } else {
            pkgName = CharOperation.NO_STRINGS;
        }
        IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName);
        if (pkgFragment == null) {
            pkgFragment = this.lastPkgFragmentRoot.getPackageFragment(pkgName);
            this.packageHandles.put(pkgName, pkgFragment);
        }
        String simpleName = simpleNames[length];
        if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) {
            ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName);
            return (Openable) unit;
        } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) {
            IClassFile classFile = pkgFragment.getClassFile(simpleName);
            return (Openable) classFile;
        }
        return null;
    }
}

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

License:Open Source License

public void consumeLocalType(char[] uniqueKey) {
    if (this.element == null)
        return;/*from w  w w.j a  v a2  s.  c om*/
    if (this.element instanceof BinaryType) {
        int lastSlash = CharOperation.lastIndexOf('/', uniqueKey);
        int end = CharOperation.indexOf(';', uniqueKey, lastSlash + 1);
        char[] localName = CharOperation.subarray(uniqueKey, lastSlash + 1, end);
        IPackageFragment pkg = (IPackageFragment) this.element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        this.element = pkg.getClassFile(new String(localName) + SuffixConstants.SUFFIX_STRING_class);
    } else {
        int firstDollar = CharOperation.indexOf('$', uniqueKey);
        int end = CharOperation.indexOf('$', uniqueKey, firstDollar + 1);
        if (end == -1)
            end = CharOperation.indexOf(';', uniqueKey, firstDollar + 1);
        char[] sourceStart = CharOperation.subarray(uniqueKey, firstDollar + 1, end);
        int position = Integer.parseInt(new String(sourceStart));
        try {
            this.element = ((ITypeRoot) this.element.getOpenable()).getElementAt(position);
        } catch (JavaModelException e) {
            this.exception = e;
        }
    }
}

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

License:Apache License

/**
 * Starts an editor for the given nested or anonymous class 
 * of the current loaded class. The class name is a fully 
 * qualified name separated by '.'. For example: java.lang.String 
 * @param annonymousClassName/*from  w  w  w .  j  av a2 s .  co m*/
 */
protected IEditorPart startEditorForAnonymousClassAndReval(String annonymousClassName) {

    IEditorPart result = null;

    IClassFileEditorInput classFileEditorInput = (IClassFileEditorInput) getEditorInput();

    /* get main class file from the edtor input */
    IClassFile origFile = classFileEditorInput.getClassFile();

    /* get package element*/
    IJavaElement packageElement = origFile.getParent();
    if (packageElement instanceof IPackageFragment) {
        IPackageFragment packageFragment = (IPackageFragment) packageElement;

        /* calculate the anonymous class name */
        String packageString = packageFragment.getElementName();
        String className = annonymousClassName
                .subSequence(packageString.length() + 1, annonymousClassName.length()).toString() + ".class";

        /* get class from the package */
        IClassFile f = packageFragment.getClassFile(className);

        /* Open editor */
        try {

            if (fReuseEditor) {
                IWorkbenchPage page = getEditorSite().getPage();

                result = EditorUtility.isOpenInEditor(f);

                /* activate the editor we want to reuse */
                if (result != null) {
                    page.bringToTop(result);
                } else { /* no editor open*/
                    if (isDirty() || page.isEditorPinned(this)) {
                        /* open a new editor */
                        result = EditorUtility.openInEditor(f, true);
                    } else if (this instanceof IReusableEditor) {
                        /* re-use editor */
                        page.reuseEditor((IReusableEditor) this, new InternalClassFileEditorInput(f));
                        if (!page.isPartVisible(result)) {
                            page.bringToTop(result);
                        }

                        return this;

                    } else {
                        // close editor, open a new one
                        result = EditorUtility.openInEditor(f, true);
                        page.closeEditor(this, false);
                    }

                }
            } else {
                result = EditorUtility.openInEditor(f, true);
            }

        } catch (PartInitException e) {
            BytecodeVisualizerPlugin
                    .log(new Status(IStatus.ERROR, BytecodeVisualizerPlugin.PLUGIN_ID, e.getMessage(), e));
        }
    }

    return result;
}