Example usage for org.eclipse.jdt.internal.compiler.util Util isClassFileName

List of usage examples for org.eclipse.jdt.internal.compiler.util Util isClassFileName

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.util Util isClassFileName.

Prototype

public final static boolean isClassFileName(String name) 

Source Link

Document

Returns true iff str.toLowerCase().endsWith(".class") implementation is not creating extra strings.

Usage

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

License:Open Source License

public char[] getMainTypeName() {
    if (this.mainTypeName == null) {
        int start = CharOperation.lastIndexOf('/', this.fileName) + 1;
        if (start == 0 || start < CharOperation.lastIndexOf('\\', this.fileName))
            start = CharOperation.lastIndexOf('\\', this.fileName) + 1;
        int separator = CharOperation.indexOf('|', this.fileName) + 1;
        if (separator > start) // case of a .class file in a default package in a jar
            start = separator;/*from   w w w .  j  a v  a 2  s.c  o  m*/

        int end = CharOperation.lastIndexOf('$', this.fileName);
        if (end == -1 || !Util.isClassFileName(this.fileName)) {
            end = CharOperation.lastIndexOf('.', this.fileName);
            if (end == -1)
                end = this.fileName.length;
        }

        this.mainTypeName = CharOperation.subarray(this.fileName, start, end);
    }
    return this.mainTypeName;
}

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

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;

    if (hasPreBuiltIndex()) {
        boolean added = this.manager.addIndex(this.containerPath, this.indexFileURL);
        if (added)
            return true;
        this.indexFileURL = null;
    }//from w  ww  .j  av a 2s  . co m

    try {
        // if index is already cached, then do not perform any check
        // MUST reset the IndexManager if a jar file is changed
        Index index = this.manager.getIndexForUpdate(this.containerPath, false,
                /*do not reuse index file*/ false /*do not create if none*/);
        if (index != null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> no indexing required (index already exists) for " + this.containerPath); //$NON-NLS-1$
            return true;
        }

        index = this.manager.getIndexForUpdate(this.containerPath, true,
                /*reuse index file*/ true /*create if none*/);
        if (index == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index could not be created for " + this.containerPath); //$NON-NLS-1$
            return true;
        }
        ReadWriteMonitor monitor = index.monitor;
        if (monitor == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index for " + this.containerPath + " just got deleted"); //$NON-NLS-1$//$NON-NLS-2$
            return true; // index got deleted since acquired
        }
        index.separator = JAR_SEPARATOR;
        ZipFile zip = null;
        try {
            // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
            // local file system
            Path zipFilePath = null;

            monitor.enterWrite(); // ask permission to write
            if (this.resource != null) {
                URI location = this.resource.getLocationURI();
                if (location == null)
                    return false;
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + location.getPath()); //$NON-NLS-1$
                File file = null;
                try {
                    file = org.eclipse.jdt.internal.core.util.Util.toLocalFile(location, progressMonitor);
                } catch (CoreException e) {
                    if (JobManager.VERBOSE) {
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because of the following exception:"); //$NON-NLS-1$
                        e.printStackTrace();
                    }
                }
                if (file == null) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because the file could not be fetched"); //$NON-NLS-1$
                    return false;
                }
                zip = new ZipFile(file);
                zipFilePath = (Path) this.resource.getFullPath().makeRelative();
                // absolute path relative to the workspace
            } else {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + this.containerPath); //$NON-NLS-1$
                // external file -> it is ok to use toFile()
                zip = new ZipFile(this.containerPath.toFile());
                zipFilePath = (Path) this.containerPath;
                // path is already canonical since coming from a library classpath entry
            }

            if (this.isCancelled) {
                if (JobManager.VERBOSE)
                    org.eclipse.jdt.internal.core.util.Util
                            .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                return false;
            }

            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> indexing " + zip.getName()); //$NON-NLS-1$
            long initialTime = System.currentTimeMillis();

            String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
            if (paths != null) {
                int max = paths.length;
                /* check integrity of the existing index file
                 * if the length is equal to 0, we want to index the whole jar again
                 * If not, then we want to check that there is no missing entry, if
                 * one entry is missing then we recreate the index
                 */
                String EXISTS = "OK"; //$NON-NLS-1$
                String DELETED = "DELETED"; //$NON-NLS-1$
                SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
                for (int i = 0; i < max; i++)
                    indexedFileNames.put(paths[i], DELETED);
                for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                    // iterate each entry to index it
                    ZipEntry ze = (ZipEntry) e.nextElement();
                    String zipEntryName = ze.getName();
                    if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName))
                        // the class file may not be there if the package name is not valid
                        indexedFileNames.put(zipEntryName, EXISTS);
                }
                boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added
                if (!needToReindex) {
                    Object[] valueTable = indexedFileNames.valueTable;
                    for (int i = 0, l = valueTable.length; i < l; i++) {
                        if (valueTable[i] == DELETED) {
                            needToReindex = true; // a file was deleted so re-index
                            break;
                        }
                    }
                    if (!needToReindex) {
                        if (JobManager.VERBOSE)
                            org.eclipse.jdt.internal.core.util.Util
                                    .verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$
                                            + zip.getName() + " (" //$NON-NLS-1$
                                            + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
                        this.manager.saveIndex(index); // to ensure its placed into the saved state
                        return true;
                    }
                }
            }

            // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
            // index already existed: recreate it so that we forget about previous entries
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(manager);
            if (!this.manager.resetIndex(this.containerPath)) {
                // failed to recreate index, see 73330
                this.manager.removeIndex(this.containerPath);
                return false;
            }
            index.separator = JAR_SEPARATOR;
            IPath indexPath = null;
            IndexLocation indexLocation;
            if ((indexLocation = index.getIndexLocation()) != null) {
                indexPath = new Path(indexLocation.getCanonicalFilePath());
            }
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                if (this.isCancelled) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util
                                .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                    return false;
                }

                // iterate each entry to index it
                ZipEntry ze = (ZipEntry) e.nextElement();
                String zipEntryName = ze.getName();
                if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName)) {
                    // index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
                    final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util
                            .getZipEntryByteContent(ze, zip);
                    JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes,
                            participant);
                    this.manager.indexDocument(entryDocument, participant, index, indexPath);
                }
            }
            this.manager.saveIndex(index);
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$
                        + zip.getName() + " (" //$NON-NLS-1$
                        + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
        } finally {
            if (zip != null) {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$
                zip.close();
            }
            monitor.exitWrite(); // free write lock
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            org.eclipse.jdt.internal.core.util.Util.verbose(
                    "-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    }
    return true;
}

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) {//from   w  ww .  j a  va2 s .co m
    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:org.eclipse.che.jdt.internal.core.search.indexing.AddJarFileToIndex.java

License:Open Source License

public boolean execute(IProgressMonitor progressMonitor) {

    if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled())
        return true;

    if (hasPreBuiltIndex()) {
        boolean added = this.manager.addIndex(this.containerPath, this.indexFileURL);
        if (added)
            return true;
        this.indexFileURL = null;
    }//from   w  w  w . j av  a 2s .  c om

    try {
        // if index is already cached, then do not perform any check
        // MUST reset the IndexManager if a jar file is changed
        Index index = this.manager.getIndexForUpdate(this.containerPath, false,
                /*do not reuse index file*/ false /*do not create if
                                                  none*/);
        if (index != null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> no indexing required (index already exists) for " + this.containerPath); //$NON-NLS-1$
            return true;
        }

        index = this.manager.getIndexForUpdate(this.containerPath, true,
                /*reuse index file*/ true /*create if none*/);
        if (index == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index could not be created for " + this.containerPath); //$NON-NLS-1$
            return true;
        }
        ReadWriteMonitor monitor = index.monitor;
        if (monitor == null) {
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util
                        .verbose("-> index for " + this.containerPath + " just got deleted"); //$NON-NLS-1$//$NON-NLS-2$
            return true; // index got deleted since acquired
        }
        index.separator = JAR_SEPARATOR;
        ZipFile zip = null;
        try {
            // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
            // local file system
            Path zipFilePath = null;

            monitor.enterWrite(); // ask permission to write
            if (this.resource != null) {
                URI location = this.resource.getLocationURI();
                if (location == null)
                    return false;
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + location.getPath()); //$NON-NLS-1$
                File file = null;
                try {
                    file = org.eclipse.jdt.internal.core.util.Util.toLocalFile(location, progressMonitor);
                } catch (CoreException e) {
                    if (JobManager.VERBOSE) {
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because of the following exception:"); //$NON-NLS-1$
                        e.printStackTrace();
                    }
                }
                if (file == null) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util.verbose("-> failed to index " //$NON-NLS-1$
                                + location.getPath() + " because the file could not be fetched"); //$NON-NLS-1$
                    return false;
                }
                zip = new ZipFile(file);
                zipFilePath = (Path) this.resource.getFullPath().makeRelative();
                // absolute path relative to the workspace
            } else {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + this.containerPath); //$NON-NLS-1$
                // external file -> it is ok to use toFile()
                zip = new ZipFile(this.containerPath.toFile());
                zipFilePath = (Path) this.containerPath;
                // path is already canonical since coming from a library classpath entry
            }

            if (this.isCancelled) {
                if (JobManager.VERBOSE)
                    org.eclipse.jdt.internal.core.util.Util
                            .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                return false;
            }

            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> indexing " + zip.getName()); //$NON-NLS-1$
            long initialTime = System.currentTimeMillis();

            String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$
            if (paths != null) {
                int max = paths.length;
                /* check integrity of the existing index file
                 * if the length is equal to 0, we want to index the whole jar again
                 * If not, then we want to check that there is no missing entry, if
                 * one entry is missing then we recreate the index
                 */
                String EXISTS = "OK"; //$NON-NLS-1$
                String DELETED = "DELETED"; //$NON-NLS-1$
                SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11);
                for (int i = 0; i < max; i++)
                    indexedFileNames.put(paths[i], DELETED);
                for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                    // iterate each entry to index it
                    ZipEntry ze = (ZipEntry) e.nextElement();
                    String zipEntryName = ze.getName();
                    if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName))
                        // the class file may not be there if the package name is not valid
                        indexedFileNames.put(zipEntryName, EXISTS);
                }
                boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added
                if (!needToReindex) {
                    Object[] valueTable = indexedFileNames.valueTable;
                    for (int i = 0, l = valueTable.length; i < l; i++) {
                        if (valueTable[i] == DELETED) {
                            needToReindex = true; // a file was deleted so re-index
                            break;
                        }
                    }
                    if (!needToReindex) {
                        if (JobManager.VERBOSE)
                            org.eclipse.jdt.internal.core.util.Util
                                    .verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$
                                            + zip.getName() + " (" //$NON-NLS-1$
                                            + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
                        this.manager.saveIndex(index); // to ensure its placed into the saved state
                        return true;
                    }
                }
            }

            // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
            // index already existed: recreate it so that we forget about previous entries
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(manager, javaProject);
            if (!this.manager.resetIndex(this.containerPath)) {
                // failed to recreate index, see 73330
                this.manager.removeIndex(this.containerPath);
                return false;
            }
            index.separator = JAR_SEPARATOR;
            IPath indexPath = null;
            IndexLocation indexLocation;
            if ((indexLocation = index.getIndexLocation()) != null) {
                indexPath = new Path(indexLocation.getCanonicalFilePath());
            }
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                if (this.isCancelled) {
                    if (JobManager.VERBOSE)
                        org.eclipse.jdt.internal.core.util.Util
                                .verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$
                    return false;
                }

                // iterate each entry to index it
                ZipEntry ze = (ZipEntry) e.nextElement();
                String zipEntryName = ze.getName();
                if (Util.isClassFileName(zipEntryName) && isValidPackageNameForClass(zipEntryName)) {
                    // index only classes coming from valid packages - https://bugs.eclipse.org/bugs/show_bug.cgi?id=293861
                    final byte[] classFileBytes = org.eclipse.jdt.internal.compiler.util.Util
                            .getZipEntryByteContent(ze, zip);
                    JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileBytes,
                            participant);
                    this.manager.indexDocument(entryDocument, participant, index, indexPath);
                }
            }
            this.manager.saveIndex(index);
            if (JobManager.VERBOSE)
                org.eclipse.jdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$
                        + zip.getName() + " (" //$NON-NLS-1$
                        + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$
        } finally {
            if (zip != null) {
                if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                    System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                            + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$
                zip.close();
            }
            monitor.exitWrite(); // free write lock
        }
    } catch (IOException e) {
        if (JobManager.VERBOSE) {
            org.eclipse.jdt.internal.core.util.Util.verbose(
                    "-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$
            e.printStackTrace();
        }
        this.manager.removeIndex(this.containerPath);
        return false;
    }
    return true;
}

From source file:org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding.java

License:Open Source License

public char[] computeUniqueKey(boolean isLeaf) {
    char[] uniqueKey = super.computeUniqueKey(isLeaf);
    if (uniqueKey.length == 2)
        return uniqueKey; // problem type's unique key is "L;"
    if (Util.isClassFileName(this.fileName))
        return uniqueKey; // no need to insert compilation unit name for a .class file

    // insert compilation unit name if the type name is not the main type name
    int end = CharOperation.lastIndexOf('.', this.fileName);
    if (end != -1) {
        int start = CharOperation.lastIndexOf('/', this.fileName) + 1;
        char[] mainTypeName = CharOperation.subarray(this.fileName, start, end);
        start = CharOperation.lastIndexOf('/', uniqueKey) + 1;
        if (start == 0)
            start = 1; // start after L
        if (this.isMemberType()) {
            end = CharOperation.indexOf('$', uniqueKey, start);
        } else {/*  w  w w  .  ja va2  s  . c om*/
            // '$' is part of the type name
            end = -1;
        }
        if (end == -1)
            end = CharOperation.indexOf('<', uniqueKey, start);
        if (end == -1)
            end = CharOperation.indexOf(';', uniqueKey, start);
        char[] topLevelType = CharOperation.subarray(uniqueKey, start, end);
        if (!CharOperation.equals(topLevelType, mainTypeName)) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(uniqueKey, 0, start);
            buffer.append(mainTypeName);
            buffer.append('~');
            buffer.append(topLevelType);
            buffer.append(uniqueKey, end, uniqueKey.length - end);
            int length = buffer.length();
            uniqueKey = new char[length];
            buffer.getChars(0, length, uniqueKey, 0);
            return uniqueKey;
        }
    }
    return uniqueKey;
}

From source file:org.eclipse.jdt.internal.core.SourceMapper.java

License:Open Source License

private synchronized void computeAllRootPaths(IType type) {
    if (this.areRootPathsComputed) {
        return;/*from   w ww .  ja  va2s  .  c om*/
    }
    IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
    IPath pkgFragmentRootPath = root.getPath();
    final HashSet tempRoots = new HashSet();
    long time = 0;
    if (VERBOSE) {
        System.out.println("compute all root paths for " + root.getElementName()); //$NON-NLS-1$
        time = System.currentTimeMillis();
    }
    final HashSet firstLevelPackageNames = new HashSet();
    boolean containsADefaultPackage = false;
    boolean containsJavaSource = !pkgFragmentRootPath.equals(this.sourcePath); // used to optimize zip file reading only if source path and root path are equals, otherwise assume that attachment contains Java source

    String sourceLevel = null;
    String complianceLevel = null;
    if (root.isArchive()) {
        JavaModelManager manager = JavaModelManager.getJavaModelManager();
        ZipFile zip = null;
        try {
            zip = manager.getZipFile(pkgFragmentRootPath);
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (!entry.isDirectory()) {
                    if (Util.isClassFileName(entryName)) {
                        int index = entryName.indexOf('/');
                        if (index != -1) {
                            String firstLevelPackageName = entryName.substring(0, index);
                            if (!firstLevelPackageNames.contains(firstLevelPackageName)) {
                                if (sourceLevel == null) {
                                    IJavaProject project = root.getJavaProject();
                                    sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                                    complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                                }
                                IStatus status = JavaConventions.validatePackageName(firstLevelPackageName,
                                        sourceLevel, complianceLevel);
                                if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                                    firstLevelPackageNames.add(firstLevelPackageName);
                                }
                            }
                        } else {
                            containsADefaultPackage = true;
                        }
                    } else if (!containsJavaSource
                            && org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(entryName)) {
                        containsJavaSource = true;
                    }
                }
            }
        } catch (CoreException e) {
            // ignore
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
    } else {
        Object target = JavaModel.getTarget(root.getPath(), true);
        if (target instanceof IResource) {
            IResource resource = (IResource) target;
            if (resource instanceof IContainer) {
                try {
                    IResource[] members = ((IContainer) resource).members();
                    for (int i = 0, max = members.length; i < max; i++) {
                        IResource member = members[i];
                        String resourceName = member.getName();
                        if (member.getType() == IResource.FOLDER) {
                            if (sourceLevel == null) {
                                IJavaProject project = root.getJavaProject();
                                sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                                complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                            }
                            IStatus status = JavaConventions.validatePackageName(resourceName, sourceLevel,
                                    complianceLevel);
                            if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                                firstLevelPackageNames.add(resourceName);
                            }
                        } else if (Util.isClassFileName(resourceName)) {
                            containsADefaultPackage = true;
                        } else if (!containsJavaSource
                                && org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) {
                            containsJavaSource = true;
                        }
                    }
                } catch (CoreException e) {
                    // ignore
                }
            }
        }
    }

    if (containsJavaSource) { // no need to read source attachment if it contains no Java source (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=190840 )
        Object target = JavaModel.getTarget(this.sourcePath, true);
        if (target instanceof IContainer) {
            IContainer folder = (IContainer) target;
            computeRootPath(folder, firstLevelPackageNames, containsADefaultPackage, tempRoots,
                    folder.getFullPath().segmentCount()/*if external folder, this is the linked folder path*/);
        } else {
            JavaModelManager manager = JavaModelManager.getJavaModelManager();
            ZipFile zip = null;
            try {
                zip = manager.getZipFile(this.sourcePath);
                for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    String entryName;
                    if (!entry.isDirectory() && org.eclipse.jdt.internal.core.util.Util
                            .isJavaLikeFileName(entryName = entry.getName())) {
                        IPath path = new Path(entryName);
                        int segmentCount = path.segmentCount();
                        if (segmentCount > 1) {
                            for (int i = 0, max = path.segmentCount() - 1; i < max; i++) {
                                if (firstLevelPackageNames.contains(path.segment(i))) {
                                    tempRoots.add(path.uptoSegment(i));
                                    // don't break here as this path could contain other first level package names (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=74014)
                                }
                                if (i == max - 1 && containsADefaultPackage) {
                                    tempRoots.add(path.uptoSegment(max));
                                }
                            }
                        } else if (containsADefaultPackage) {
                            tempRoots.add(new Path("")); //$NON-NLS-1$
                        }
                    }
                }
            } catch (CoreException e) {
                // ignore
            } finally {
                manager.closeZipFile(zip); // handle null case
            }
        }
    }
    int size = tempRoots.size();
    if (this.rootPaths != null) {
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            tempRoots.add(new Path((String) iterator.next()));
        }
        this.rootPaths.clear();
    } else {
        this.rootPaths = new ArrayList(size);
    }
    size = tempRoots.size();
    if (size > 0) {
        ArrayList sortedRoots = new ArrayList(tempRoots);
        if (size > 1) {
            Collections.sort(sortedRoots, new Comparator() {
                public int compare(Object o1, Object o2) {
                    IPath path1 = (IPath) o1;
                    IPath path2 = (IPath) o2;
                    return path1.segmentCount() - path2.segmentCount();
                }
            });
        }
        for (Iterator iter = sortedRoots.iterator(); iter.hasNext();) {
            IPath path = (IPath) iter.next();
            this.rootPaths.add(path.toString());
        }
    }
    this.areRootPathsComputed = true;
    if (VERBOSE) {
        System.out.println("Spent " + (System.currentTimeMillis() - time) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.println("Found " + size + " root paths"); //$NON-NLS-1$ //$NON-NLS-2$
        int i = 0;
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            System.out.println("root[" + i + "]=" + ((String) iterator.next()));//$NON-NLS-1$ //$NON-NLS-2$
            i++;
        }
    }
}

From source file:spoon.support.util.BasicCompilationUnit.java

License:Open Source License

public char[] getMainTypeName() {
    if (this.mainTypeName == null) {
        int start = CharOperation.lastIndexOf('/', this.fileName) + 1;
        if (start == 0 || start < CharOperation.lastIndexOf('\\', this.fileName))
            start = CharOperation.lastIndexOf('\\', this.fileName) + 1;
        int separator = CharOperation.indexOf('|', this.fileName) + 1;
        if (separator > start) // case of a .class file in a default
            // package in a jar
            start = separator;/* ww w .  j a v a2 s . com*/

        int end = CharOperation.lastIndexOf('$', this.fileName);
        if (end == -1 || !Util.isClassFileName(this.fileName)) {
            end = CharOperation.lastIndexOf('.', this.fileName);
            if (end == -1)
                end = this.fileName.length;
        }

        this.mainTypeName = CharOperation.subarray(this.fileName, start, end);
    }
    return this.mainTypeName;
}