Example usage for org.eclipse.jdt.internal.core JavaModelManager getZipFile

List of usage examples for org.eclipse.jdt.internal.core JavaModelManager getZipFile

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaModelManager getZipFile.

Prototype

public ZipFile getZipFile(IPath path) throws CoreException 

Source Link

Document

Returns the open ZipFile at the given path.

Usage

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

License:Open Source License

private static List getCalledFileNames(IPath jarPath) {
    Object target = JavaModel.getTarget(jarPath,
            true/*check existence, otherwise the manifest cannot be read*/);
    if (!(target instanceof IFile || target instanceof File))
        return null;
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    ZipFile zip = null;//from  w  w w. j  a va2  s.  c o m
    InputStream inputStream = null;
    List calledFileNames = null;
    try {
        zip = manager.getZipFile(jarPath);
        ZipEntry manifest = zip.getEntry("META-INF/MANIFEST.MF"); //$NON-NLS-1$
        if (manifest == null)
            return null;
        // non-null implies regular file
        ManifestAnalyzer analyzer = new ManifestAnalyzer();
        inputStream = zip.getInputStream(manifest);
        boolean success = analyzer.analyzeManifestContents(inputStream);
        calledFileNames = analyzer.getCalledFileNames();
        if (!success || analyzer.getClasspathSectionsCount() == 1 && calledFileNames == null) {
            if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                Util.verbose("Invalid Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            }
            return null;
        } else if (analyzer.getClasspathSectionsCount() > 1) {
            if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
                Util.verbose("Multiple Class-Path headers in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            }
            return null;
        }
    } catch (CoreException e) {
        // not a zip file
        if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
            Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    } catch (IOException e) {
        // not a zip file
        if (JavaModelManager.CP_RESOLVE_VERBOSE_FAILURE) {
            Util.verbose("Could not read Class-Path header in manifest of jar file: " + jarPath.toOSString()); //$NON-NLS-1$
            e.printStackTrace();
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // best effort
            }
        }
        manager.closeZipFile(zip);
    }
    return calledFileNames;
}

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

License:Open Source License

public static ClassFileReader classFileReader(IType type) {
    IClassFile classFile = type.getClassFile();
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    if (classFile.isOpen())
        return (ClassFileReader) manager.getInfo(type);

    PackageFragment pkg = (PackageFragment) type.getPackageFragment();
    IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent();
    try {/*  w  ww . j  a  va2s  .  c om*/
        if (!root.isArchive())
            return Util.newClassFileReader(((JavaElement) type).resource());

        ZipFile zipFile = null;
        try {
            IPath zipPath = root.getPath();
            if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                System.out.println("(" + Thread.currentThread()
                        + ") [MatchLocator.classFileReader()] Creating ZipFile on " + zipPath); //$NON-NLS-1$   //$NON-NLS-2$
            zipFile = manager.getZipFile(zipPath);
            String classFileName = classFile.getElementName();
            String path = Util.concatWith(pkg.names, classFileName, '/');
            return ClassFileReader.read(zipFile, path);
        } finally {
            manager.closeZipFile(zipFile);
        }
    } catch (ClassFormatException e) {
        // invalid class file: return null
    } catch (CoreException e) {
        // cannot read class file: return null
    } catch (IOException e) {
        // cannot read class file: return null
    }
    return null;
}

From source file:org.eclipse.jdt.internal.core.search.matching.MatchLocator.java

License:Open Source License

public static ClassFileReader classFileReader(IType type) {
    IClassFile classFile = type.getClassFile();
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    if (classFile.isOpen())
        return (ClassFileReader) manager.getInfo(type);

    PackageFragment pkg = (PackageFragment) type.getPackageFragment();
    IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent();
    try {//from w w w .  j ava 2s. c o m
        if (!root.isArchive())
            return Util.newClassFileReader(((JavaElement) type).resource());

        ZipFile zipFile = null;
        try {
            IPath zipPath = root.getPath();
            if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                System.out.println("(" + Thread.currentThread() //$NON-NLS-1$
                        + ") [MatchLocator.classFileReader()] Creating ZipFile on " + zipPath); //$NON-NLS-1$
            zipFile = manager.getZipFile(zipPath);
            String classFileName = classFile.getElementName();
            String path = Util.concatWith(pkg.names, classFileName, '/');
            return ClassFileReader.read(zipFile, path);
        } finally {
            manager.closeZipFile(zipFile);
        }
    } catch (ClassFormatException e) {
        // invalid class file: return null
    } catch (CoreException e) {
        // cannot read class file: return null
    } catch (IOException e) {
        // cannot read class file: return null
    }
    return null;
}

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  ww  w.  j  ava 2 s .c  o m*/
    }
    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:org.eclipse.jdt.internal.core.SourceMapper.java

License:Open Source License

public char[] findSource(String fullName) {
    char[] source = null;
    Object target = JavaModel.getTarget(this.sourcePath, true);
    String charSet = null;/*from   ww w  .  j a  va2s . c  om*/
    if (target instanceof IContainer) {
        IResource res = ((IContainer) target).findMember(fullName);
        if (res instanceof IFile) {
            try {
                source = org.eclipse.jdt.internal.core.util.Util.getResourceContentsAsCharArray((IFile) res);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    } else {
        try {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=303511
            // For a resource inside the workspace, use the encoding set on the resource
            if (target instanceof IFile)
                charSet = ((IFile) target).getCharset();
        } catch (CoreException e) {
            // Ignore
        }

        // try to get the entry
        ZipEntry entry = null;
        ZipFile zip = null;
        JavaModelManager manager = JavaModelManager.getJavaModelManager();
        try {
            zip = manager.getZipFile(this.sourcePath);
            entry = zip.getEntry(fullName);
            if (entry != null) {
                // now read the source code
                source = readSource(entry, zip, charSet);
            }
        } catch (CoreException e) {
            return null;
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
    }
    return source;
}

From source file:org.eclipse.xtext.common.types.ui.trace.ZipFileAwareTrace.java

License:Open Source License

@Override
public InputStream getContents(SourceRelativeURI uri, IProject project) {
    // inspired by org.eclipse.jdt.internal.core.JarEntryFile.getContents()
    JavaModelManager modelManager = JavaModelManager.getJavaModelManager();
    ZipFile zipFile = null;//from  w w w  .  j  av a 2 s .c om
    try {
        zipFile = modelManager.getZipFile(zipFilePath);
        ZipEntry zipEntry = zipFile.getEntry(uri.getURI().toString());
        if (zipEntry != null) {
            byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile);
            return new ByteArrayInputStream(contents);
        }
    } catch (IOException e) {
        log.debug("Could not read zip file " + uri, e);
    } catch (CoreException e) {
        log.debug("Could not read zip file " + uri, e);
    } finally {
        if (zipFile != null) {
            modelManager.closeZipFile(zipFile);
        }
    }
    return null;
}

From source file:org.summer.dsl.builder.trace.ZipFileAwareTrace.java

License:Open Source License

@Override
protected InputStream getContents(URI uri, IProject project) throws CoreException {
    // inspired by org.eclipse.jdt.internal.core.JarEntryFile.getContents()
    JavaModelManager modelManager = JavaModelManager.getJavaModelManager();
    ZipFile zipFile = modelManager.getZipFile(zipFilePath);
    try {/*from  w  w  w .j  a  va 2  s .  co m*/
        ZipEntry zipEntry = zipFile.getEntry(uri.toString());
        if (zipEntry != null) {
            byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile);
            return new ByteArrayInputStream(contents);
        }
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, "", e.getMessage(), e));
    } finally {
        modelManager.closeZipFile(zipFile);
    }
    return null;
}