Example usage for java.util.jar JarInputStream getNextJarEntry

List of usage examples for java.util.jar JarInputStream getNextJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarInputStream getNextJarEntry.

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java

/**
 * /*from w  w  w  . java 2 s  .  com*/
 * create one default index bean which based one the component zip file directly.
 * 
 * bundleId, version, mvn_uri are required
 */
public ComponentIndexBean create(File componentZipFile) {
    if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory()
            || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) {
        return null;
    }

    String name = null;
    String bundleId = null;
    String bundleVersion = null;
    String mvnUri = null;

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(componentZipFile);

        Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry zipEntry = enumeration.nextElement();
            String path = zipEntry.getName();
            if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar
                // if it's bundle, not from other folder, like lib, m2 repository.
                IPath p = new Path(path);
                // must be in plugins
                if (p.segmentCount() > 1
                        && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) {
                    if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) {
                        JarInputStream jarEntryStream = null;
                        try {
                            // must use another stream
                            jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry));
                            // find the bundleId and version
                            Manifest manifest = jarEntryStream.getManifest();
                            if (manifest != null) {
                                bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                            }
                            boolean checkManifest = StringUtils.isBlank(bundleId)
                                    || StringUtils.isBlank(bundleVersion);

                            // find the pom.properties
                            JarEntry jarEntry = null;
                            while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) {
                                final String entryPath = jarEntry.getName();
                                if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) {
                                    manifest = new Manifest();
                                    manifest.read(jarEntryStream);
                                    bundleId = JarMenifestUtil.getBundleSymbolicName(manifest);
                                    bundleVersion = JarMenifestUtil.getBundleVersion(manifest);
                                    checkManifest = false;
                                }
                                final Path fullPath = new Path(entryPath);
                                final String fileName = fullPath.lastSegment();

                                /*
                                 * for example,
                                 * META-INF/maven/org.talend.components/components-splunk/pom.properties
                                 */
                                if (fileName.equals("pom.properties") //$NON-NLS-1$
                                        && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$

                                    // FIXME, didn't find one way to read the inner jar
                                    // final InputStream propStream = jarFile.getInputStream(jarEntry);
                                    // if (propStream != null) {
                                    // Properties pomProp = new Properties();
                                    // pomProp.load(propStream);
                                    //
                                    // String version = pomProp.getProperty("version"); //$NON-NLS-1$
                                    // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$
                                    // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$
                                    // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version,
                                    // FileExtensions.ZIP_FILE_SUFFIX, null);
                                    //
                                    // propStream.close();
                                    // }

                                    // FIXME, try the path way
                                    // META-INF/maven/org.talend.components/components-splunk
                                    IPath tmpMavenPath = fullPath.removeLastSegments(1);
                                    String artifactId = tmpMavenPath.lastSegment(); // components-splunk
                                    // META-INF/maven/org.talend.components
                                    tmpMavenPath = tmpMavenPath.removeLastSegments(1);
                                    String groupId = tmpMavenPath.lastSegment(); // org.talend.components

                                    mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion,
                                            FileExtensions.ZIP_EXTENSION, null);

                                } else
                                /*
                                 * /OSGI-INF/installer$$splunk.xml
                                 */
                                if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX)
                                        && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                        && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) {
                                    name = fullPath.removeFileExtension().lastSegment();
                                    name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX)
                                            + UpdatesHelper.NEW_COMPONENT_PREFIX.length());
                                }
                            }
                        } catch (IOException e) {
                            //
                        } finally {
                            try {
                                if (jarEntryStream != null) {
                                    jarEntryStream.close();
                                }
                            } catch (IOException e) {
                                //
                            }
                        }

                    }
                }
            }
        }

    } catch (ZipException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } catch (IOException e) {
        if (CommonsPlugin.isDebugMode()) {
            ExceptionHandler.process(e);
        }
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                //
            }
        }
    }
    // set the required
    if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) {
        final ComponentIndexBean indexBean = new ComponentIndexBean();
        final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri);
        indexBean.setValue(ComponentIndexNames.types,
                PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0)));
        if (set) {
            return indexBean;
        }
    }
    return null;
}

From source file:org.webical.plugin.classloading.PluginClassLoader.java

/**
 * Reads in all classes in a jar file for later reference
 * @param name the full name and path of the jar file
 * @throws PluginException //from  w  ww .j a v a  2s  .  c  o  m
 */
public void readJarFile(File jarFile) throws PluginException {
    //Firstly check input
    if (jarFile == null) {
        log.error("Cannot load jar without a reference...");
        throw new PluginException("Cannot load jar without a reference...");
    }

    JarInputStream jis;
    JarEntry je;

    if (!jarFile.exists()) {
        log.error("Jar does not exist: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar does not exist: " + jarFile.getAbsolutePath());
    }
    if (!jarFile.canRead()) {
        log.error("Jar is not readable: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar is not readable: " + jarFile.getAbsolutePath());
    }
    if (log.isDebugEnabled())
        log.debug("Loading jar file " + jarFile);

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(jarFile);
        jis = new JarInputStream(fis);
    } catch (IOException ioe) {
        log.error("Can't open jar file " + jarFile, ioe);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
            }
        }
        throw new PluginException("Can't open jar file " + jarFile, ioe);
    }

    //Loop over the jarfile entries
    try {
        while ((je = jis.getNextJarEntry()) != null) {
            String jarEntryName = je.getName();
            //Skip the META-INF dir
            if (jarEntryName.startsWith(META_INF)) {
                continue;
            }

            if (jarEntryName.endsWith(FileUtils.CLASS_FILE_EXTENSION)) {
                //Extract java class
                loadClassBytes(jis, ClassUtils.fileToFullClassName(jarEntryName));
            } else if (je.isDirectory()) {
                //Extract directory
                unpackDirectory(jarEntryName, jarFile);
            } else {
                //it could be an image or audio file so let's extract it and store it somewhere for later reference
                try {
                    extractJarResource(jis, jarEntryName, jarFile);
                } catch (Exception e) {
                    log.error("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                    throw new PluginException("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                }
            }
            jis.closeEntry();
        }
    } catch (IOException ioe) {
        log.error("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
        throw new PluginException("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                log.error("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
            }
        }
    }
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;//from w ww  . j  a va2 s  . com
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the
 * entry represents another a JAR file. The files in the {@link JarEntry} will be
 * extracted using the contextDir as the base directory. 
 * /*  w  w w.  j a  va  2 s . c o  m*/
 * @param earFile The JarEntry for the JAR to read from the archive.
 * @param earEntry The JarFile to get the {@link InputStream} for the file from.
 * @param contextDir The directory to extract the JAR to.
 * @throws IOException If the extracting of data from the JarEntry fails.
 */
protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir)
        throws MojoFailureException {
    if (this.getLogger().isInfoEnabled()) {
        this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '"
                + contextDir + "'");
    }

    if (!contextDir.exists()) {
        if (this.getLogger().isDebugEnabled()) {
            this.getLogger().debug("Creating context directory entry '" + contextDir + "'");
        }

        try {
            FileUtils.forceMkdir(contextDir);
        } catch (IOException e) {
            throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '"
                    + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e);
        }
    }

    JarInputStream warInputStream = null;
    try {
        warInputStream = new JarInputStream(earFile.getInputStream(earEntry));

        // Write out the MANIFEST.MF file to the target directory
        Manifest manifest = warInputStream.getManifest();
        if (manifest != null) {
            FileOutputStream manifestFileOutputStream = null;
            try {
                final File manifestFile = new File(contextDir, MANIFEST_PATH);
                manifestFile.getParentFile().mkdirs();
                manifestFileOutputStream = new FileOutputStream(manifestFile);
                manifest.write(manifestFileOutputStream);
            } catch (Exception e) {
                this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
                throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '"
                        + earEntry.getName() + "' out of '" + earFile.getName() + "'", e);
            } finally {
                try {
                    if (manifestFileOutputStream != null) {
                        manifestFileOutputStream.close();
                    }
                } catch (Exception e) {
                    this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry:  "
                            + earEntry.getName());
                }
            }
        }

        JarEntry warEntry;
        while ((warEntry = warInputStream.getNextJarEntry()) != null) {
            final File warEntryFile = new File(contextDir, warEntry.getName());

            if (warEntry.isDirectory()) {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' as '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile);
            } else {
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!"
                            + warEntry.getName() + "' to '" + warEntryFile + "'");
                }

                FileUtils.forceMkdir(warEntryFile.getParentFile());

                final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile);
                try {
                    IOUtils.copy(warInputStream, jarEntryFileOutputStream);
                } finally {
                    IOUtils.closeQuietly(jarEntryFileOutputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '"
                + earFile.getName() + "' to '" + contextDir + "'", e);
    } finally {
        IOUtils.closeQuietly(warInputStream);
    }
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata,
        boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense,
        boolean processingSources) throws IOException {
    // if we don't need to find either a license or notice, don't process the jar at all
    if (!lookForLicense && !lookForNotice) {
        return;//w w w. ja v a  2 s. c  om
    }

    final String indent = getIndent(level);
    output(indent, "Processing JAR " + jarFilePath + "...", false, true);

    // JarFile realJarFile = new JarFile(jarFile);
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    String bundleLicense = null;
    Manifest manifest = jarInputStream.getManifest();
    if (manifest != null && manifest.getMainAttributes() != null) {
        bundleLicense = manifest.getMainAttributes().getValue("Bundle-License");
        if (bundleLicense != null) {
            output(indent, "Found Bundle-License attribute with value:" + bundleLicense);
            KnownLicense knownLicense = getKnowLicenseByName(bundleLicense);
            // this data is not reliable, especially on the ServiceMix repackaged bundles
        }
    }
    String pomFilePath = null;
    byte[] pomByteArray = null;

    final String jarFileName = getJarFileName(jarFilePath);
    if (contextJarMetadata == null) {
        contextJarMetadata = jarDatabase.get(jarFileName);
        if (contextJarMetadata == null) {
            // compute project name
            contextJarMetadata = new JarMetadata(jarFilePath, jarFileName);
        }
        jarDatabase.put(jarFileName, contextJarMetadata);
    }

    Notice notice;
    JarEntry curJarEntry = null;
    while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) {

        if (!curJarEntry.isDirectory()) {
            final String fileName = curJarEntry.getName();
            if (lookForNotice && isNotice(fileName, jarFilePath)) {

                output(indent, "Processing notice found in " + curJarEntry + "...");

                InputStream noticeInputStream = jarInputStream;
                List<String> noticeLines = IOUtils.readLines(noticeInputStream);
                notice = new Notice(noticeLines);

                Map<String, Notice> notices = contextJarMetadata.getNoticeFiles();
                if (notices == null) {
                    notices = new TreeMap<>();
                    notices.put(fileName, notice);
                    output(indent, "Found first notice " + curJarEntry);
                } else if (!notices.containsValue(notice)) {
                    output(indent, "Found additional notice " + curJarEntry);
                    notices.put(fileName, notice);
                } else {
                    output(indent, "Duplicated notice in " + curJarEntry);
                    notices.put(fileName, notice);
                    duplicatedNotices.add(jarFilePath);
                }

                // IOUtils.closeQuietly(noticeInputStream);
            } else if (processMavenPom && fileName.endsWith("pom.xml")) {
                // remember pom file path in case we need it
                pomFilePath = curJarEntry.getName();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarInputStream, byteArrayOutputStream);
                pomByteArray = byteArrayOutputStream.toByteArray();

            } else if (lookForLicense && isLicense(fileName, jarFilePath)) {

                output(indent, "Processing license found in " + curJarEntry + "...");
                InputStream licenseInputStream = jarInputStream;
                List<String> licenseLines = IOUtils.readLines(licenseInputStream);

                LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines);

                resolveKnownLicensesByText(licenseFile);

                if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText())
                        && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) {
                    KnownLicense knownLicense = new KnownLicense();
                    knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms");
                    knownLicense
                            .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath));
                    List<TextVariant> textVariants = new ArrayList<>();
                    TextVariant textVariant = new TextVariant();
                    textVariant.setId("default");
                    textVariant.setDefaultVariant(true);
                    textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText()));
                    textVariants.add(textVariant);
                    knownLicense.setTextVariants(textVariants);
                    knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText());
                    knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl"));
                    knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense);
                    licenseFile.getKnownLicenses().add(knownLicense);
                    licenseFile.getKnownLicenseKeys().add(knownLicense.getId());
                }

                for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) {
                    SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense);
                    if (licenseFiles != null) {
                        if (!licenseFiles.contains(licenseFile)) {
                            licenseFiles.add(licenseFile);
                        }
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    } else {
                        licenseFiles = new TreeSet<>();
                        licenseFiles.add(licenseFile);
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    }
                }

                Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles();
                if (licenseFiles == null) {
                    licenseFiles = new TreeMap<>();
                }
                if (licenseFiles.containsKey(fileName)) {
                    // warning we already have a license file here, what should we do ?
                    output(indent, "License file already exists for " + jarFilePath + " will override it !",
                            true, false);
                    licenseFiles.remove(fileName);
                }
                licenseFiles.put(fileName, licenseFile);

                // IOUtils.closeQuietly(licenseInputStream);

            } else if (fileName.endsWith(".jar")) {
                InputStream embeddedJarInputStream = jarInputStream;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream);
                final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName));

                if (embeddedJarMetadata != null) {
                    embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray());
                    contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata);
                }
            } else if (fileName.endsWith(".class")) {
                String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/",
                        ".");
                int lastPoint = className.lastIndexOf(".");
                String packageName = null;
                if (lastPoint > 0) {
                    packageName = className.substring(0, lastPoint);
                    SortedSet<String> currentJarPackages = jarDatabase
                            .get(FilenameUtils.getBaseName(jarFilePath)).getPackages();
                    if (currentJarPackages == null) {
                        currentJarPackages = new TreeSet<>();
                    }
                    currentJarPackages.add(packageName);
                }
            }

        }
        jarInputStream.closeEntry();
    }

    jarInputStream.close();
    jarInputStream = null;

    if (!contextJarMetadata.getEmbeddedJars().isEmpty()) {
        for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) {
            if (embeddedJarMetadata.getJarContents() != null) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                        embeddedJarMetadata.getJarContents());
                processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true,
                        true, processingSources);
            } else {
                output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false);
            }
        }
    }

    if (processMavenPom) {
        if (pomFilePath == null) {
            output(indent, "No POM found in " + jarFilePath);
        } else {
            output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "...");
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray);
            processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice,
                    lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources);
        }
    }

    if (lookForLicense || lookForNotice) {
        if (lookForLicense) {
            output(indent, "No license found in " + jarFilePath);
        }
        if (lookForNotice) {
            output(indent, "No notice found in " + jarFilePath);
        }

        if (pomFilePath == null && lookForLicense && lookForNotice) {
            if (StringUtils.isBlank(contextJarMetadata.getVersion())) {
                output(indent, "Couldn't resolve version for JAR " + contextJarMetadata
                        + ", can't query Maven Central repository without version !");
            } else {
                List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(),
                        contextJarMetadata.getVersion(), contextJarMetadata.getClassifier());
                if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) {
                    Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0);
                    Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level);
                    if (resolvedArtifact != null) {
                        // we have a copy of the local artifact, let's request the sources for it.
                        if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) {
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), "sources", "jar",
                                    resolvedArtifact.getVersion());
                            File sourceJar = getArtifactFile(artifact, level);
                            if (sourceJar != null && sourceJar.exists()) {
                                FileInputStream sourceJarInputStream = new FileInputStream(sourceJar);
                                processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata,
                                        false, level + 1, lookForNotice, lookForLicense, true);
                                IOUtils.closeQuietly(sourceJarInputStream);
                            }
                        } else {
                            // we are already processing a sources artifact, we need to load the pom artifact to extract information from there
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), null, "pom",
                                    resolvedArtifact.getVersion());
                            File artifactPom = getArtifactFile(artifact, level);
                            if (artifactPom != null && artifactPom.exists()) {
                                output(indent, "Processing POM for " + artifact + "...");
                                processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata,
                                        contextJarMetadata.getEmbeddedJars(), level + 1,
                                        new FileInputStream(artifactPom), processingSources);
                            }
                        }
                    } else {
                        output(indent, "===>  Couldn't resolve artifact " + mavenCentralArtifact
                                + " in Maven Central. Please resolve license and notice files manually!", false,
                                true);
                    }
                } else {
                    output(indent, "===>  Couldn't find nor POM, license or notice. Please check manually!",
                            false, true);
                }
            }
        }
    }

    output(indent, "Done processing JAR " + jarFilePath + ".", false, true);

}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * analyse the content of the given jar file
 * //from   w w w. j  a  v  a 2 s  .c  o  m
 * @param jarFile
 *            the jar to analise
 */
private final void readDirectories(final URL jarFile) {
    JarInputStream jarIn = null;

    try {
        if (!jarFile.getPath().endsWith(".jar")) {
            return;
        }
        if (CClassLoader.sl(CClassLoader.DEBUG)) {
            CClassLoader.log("opening jar : " + jarFile.toExternalForm(), CClassLoader.DEBUG);
        }
        jarIn = new JarInputStream(jarFile.openStream());
        JarEntry jarEntry = null;

        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            if (jarEntry.isDirectory()) {
                continue;
            }

            final URL url = new URL("yahpjarloader://"
                    + CBASE64Codec.encode(jarFile.toExternalForm().getBytes("utf-8")).replaceAll("\n", "") + "/"
                    + jarEntry.getName());

            if (CClassLoader.sl(CClassLoader.DEBUG)) {
                CClassLoader.log("found entry : " + url.toString(), CClassLoader.DEBUG);
            }

            if (jarEntry.getName().endsWith(".class")) {
                if (!this.classesMap.containsKey(jarEntry.getName())) {
                    if (!this.booResourceOnly) {
                        this.classesMap.put(jarEntry.getName(), url);
                    }
                }

                if (this.resourcesMap.containsKey(jarEntry.getName())) {
                    final Object to = this.resourcesMap.get(jarEntry.getName());
                    if (to instanceof URL) {
                        final URL uo = (URL) to;
                        final List l = new ArrayList();
                        l.add(uo);
                        l.add(url);
                        this.resourcesMap.put(jarEntry.getName(), l);
                    } else if (to instanceof List) {
                        final List uo = (List) to;
                        uo.add(url);
                        this.resourcesMap.put(jarEntry.getName(), uo);
                    }
                } else {
                    this.resourcesMap.put(jarEntry.getName(), url);
                }
            } else if (jarEntry.getName().startsWith("native/")) {
                String system = jarEntry.getName().substring(7);
                system = system.substring(0, system.indexOf('/'));
                if (!this.dllMap.containsKey(system)) {
                    this.dllMap.put(system, url);
                }
                if (this.resourcesMap.containsKey(jarEntry.getName())) {
                    final Object to = this.resourcesMap.get(jarEntry.getName());
                    if (to instanceof URL) {
                        final URL uo = (URL) to;
                        final List l = new ArrayList();
                        l.add(uo);
                        l.add(url);
                        this.resourcesMap.put(jarEntry.getName(), l);
                    } else if (to instanceof List) {
                        final List uo = (List) to;
                        uo.add(url);
                        this.resourcesMap.put(jarEntry.getName(), uo);
                    }
                } else {
                    this.resourcesMap.put(jarEntry.getName(), url);
                }
            } else {
                if (this.resourcesMap.containsKey(jarEntry.getName())) {
                    final Object to = this.resourcesMap.get(jarEntry.getName());
                    if (to instanceof URL) {
                        final URL uo = (URL) to;
                        final List l = new ArrayList();
                        l.add(uo);
                        l.add(url);
                        this.resourcesMap.put(jarEntry.getName(), l);
                    } else if (to instanceof List) {
                        final List uo = (List) to;
                        uo.add(url);
                        this.resourcesMap.put(jarEntry.getName(), uo);
                    }
                } else {
                    this.resourcesMap.put(jarEntry.getName(), url);
                }
            }
        }

        if (CClassLoader.sl(CClassLoader.DEBUG)) {
            CClassLoader.log("opening jar : " + jarFile.getFile().toString() + " done.", CClassLoader.DEBUG);
        }
    } catch (final MalformedURLException mue) {
        mue.printStackTrace();

        if (CClassLoader.sl(CClassLoader.FATAL)) {
            CClassLoader.log(mue.getMessage(), CClassLoader.FATAL);
        }
    } catch (final IOException ioe) {
        ioe.printStackTrace();

        if (CClassLoader.sl(CClassLoader.FATAL)) {
            CClassLoader.log(ioe.getMessage(), CClassLoader.FATAL);
        }
    } catch (final Exception e) {
        e.printStackTrace();

        if (CClassLoader.sl(CClassLoader.FATAL)) {
            CClassLoader.log(e.getMessage(), CClassLoader.FATAL);
        }
    } finally {
        try {
            jarIn.close();
            jarIn = null;
        } catch (final Exception e) {
        }
    }
}

From source file:com.amalto.workbench.utils.Util.java

public static ByteArrayOutputStream retrieveJarEntryAsBytes(File barFile, String entryName) {
    JarInputStream jarIn = null;
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();

    try {//  w w w.ja v  a 2  s . com
        jarIn = new JarInputStream(new FileInputStream(barFile));
        JarEntry entry;
        byte[] buf = new byte[4096];
        while ((entry = jarIn.getNextJarEntry()) != null) {
            if (entry.toString().equals(entryName)) {
                int read;
                while ((read = jarIn.read(buf, 0, 4096)) != -1) {
                    outBytes.write(buf, 0, read);
                }
                if (outBytes.toByteArray().length > 0) {
                    return outBytes;
                }
            }
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java

private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile,
        String defaultVersion) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
    Manifest jarManifest = jarInputStream.getManifest();
    // Map<String, String> manifestVersions = new HashMap<String,String>();
    String specificationVersion = null;
    if (jarManifest == null) {
        getLog().warn("No MANIFEST.MF file found for dependency " + jarFile);
    } else {// ww  w  . j a v  a2  s.c o  m
        if (jarManifest.getMainAttributes() == null) {
            getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile);
        } else {
            specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version");
            if (defaultVersion == null) {
                if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) {
                } else if (specificationVersion != null) {
                    defaultVersion = specificationVersion;
                } else {
                    defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version");
                }
            }
            String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package");
            if (exportPackageHeaderValue != null) {
                ManifestElement[] manifestElements = new ManifestElement[0];
                try {
                    manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue);
                } catch (BundleException e) {
                    getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e);
                }
                for (ManifestElement manifestElement : manifestElements) {
                    String[] packageNames = manifestElement.getValueComponents();
                    String version = manifestElement.getAttribute("version");
                    for (String packageName : packageNames) {
                        updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version,
                                version, packageName);
                    }
                }
            }
            for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) {
                String packageName = manifestEntries.getKey().replaceAll("/", ".");
                if (packageName.endsWith(".class")) {
                    continue;
                }
                if (packageName.endsWith(".")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                if (packageName.endsWith(".*")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                int lastDotPos = packageName.lastIndexOf(".");
                String lastPackage = packageName;
                if (lastDotPos > -1) {
                    lastPackage = packageName.substring(lastDotPos + 1);
                }
                if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) {
                    // ignore non package version
                    continue;
                }
                if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF")
                        || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT")
                        || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) {
                    // ignore private package names
                    continue;
                }
                String packageVersion = null;
                if (manifestEntries.getValue().getValue("Specification-Version") != null) {
                    packageVersion = manifestEntries.getValue().getValue("Specification-Version");
                } else {
                    packageVersion = manifestEntries.getValue().getValue("Implementation-Version");
                }
                if (packageVersion != null) {
                    getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName
                            + " v" + packageVersion);
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            packageVersion, specificationVersion, packageName);
                    // manifestVersions.put(packageName, packageVersion);
                }
            }
        }
    }
    JarEntry jarEntry = null;
    // getLog().debug("Processing file " + artifact.getFile() + "...");
    while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();
            String entryPackage = "";
            int lastSlash = entryName.lastIndexOf("/");
            if (lastSlash > -1) {
                entryPackage = entryName.substring(0, lastSlash);
                entryPackage = entryPackage.replaceAll("/", ".");
                if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF")
                        && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT")
                        && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) {
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            defaultVersion, specificationVersion, entryPackage);
                }
            }
        }
    }
    jarInputStream.close();
}