Example usage for java.util.jar JarInputStream JarInputStream

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

Introduction

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

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:org.jahia.services.modulemanager.persistence.PersistentBundleInfoBuilder.java

/**
 * Parses the supplied resource and builds the information for the bundle.
 *
 * @param resource The bundle resource/*from   ww w  . ja va 2s. com*/
 * @param calculateChecksum should we calculate the resource checksum?
 * @param checkTransformationRequired should we check if the module dependency capability headers has to be added
 * @return The information about the supplied bundle
 * @throws IOException In case of resource read errors
 */
public static PersistentBundle build(Resource resource, boolean calculateChecksum,
        boolean checkTransformationRequired) throws IOException {

    // populate data from manifest
    String groupId = null;
    String symbolicName = null;
    String version = null;
    String displayName = null;
    try (JarInputStream jarIs = new JarInputStream(resource.getInputStream())) {
        Manifest mf = jarIs.getManifest();
        if (mf != null) {
            Attributes attrs = mf.getMainAttributes();
            groupId = attrs.getValue(ATTR_NAME_GROUP_ID);
            symbolicName = attrs.getValue(ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
            version = StringUtils.defaultIfBlank(attrs.getValue(ATTR_NAME_BUNDLE_VERSION),
                    attrs.getValue(ATTR_NAME_IMPL_VERSION));
            displayName = StringUtils.defaultIfBlank(attrs.getValue(ATTR_NAME_IMPL_TITLE),
                    attrs.getValue(ATTR_NAME_BUNDLE_NAME));
        }
    }

    if (StringUtils.isBlank(symbolicName) || StringUtils.isBlank(version)) {
        // not a valid JAR or bundle information is missing -> we stop here
        logger.warn("Not a valid JAR or bundle information is missing for resource " + resource);
        return null;
    }

    PersistentBundle bundleInfo = new PersistentBundle(groupId, symbolicName, version);
    bundleInfo.setDisplayName(displayName);
    if (calculateChecksum) {
        bundleInfo.setChecksum(calculateDigest(resource));
    }
    if (checkTransformationRequired) {
        bundleInfo.setTransformationRequired(isTransformationRequired(resource));
    }
    bundleInfo.setResource(resource);
    return bundleInfo;
}

From source file:org.talend.designer.maven.utils.ClasspathsJarGenerator.java

public static String getClasspathFromManifest(Property property) throws Exception {
    String jarLocation = getJarLocation(property);
    JarInputStream stream = null;
    try {/*from   www. j a  v  a2 s.  c o m*/
        stream = new JarInputStream(new FileInputStream(jarLocation));
        Manifest manifest = stream.getManifest();
        String classpath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
        return classpath;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (jarBundles == null || jarBundles.size() == 0) {
        jarBundles = new ArrayList<String>();
        String extension = project.getPackaging();
        if ("bundle".equals(extension)) {
            extension = "jar";
        }//from   w w w  .  j ava  2s.  com
        jarBundles.add(
                project.getBuild().getDirectory() + "/" + project.getBuild().getFinalName() + "." + extension);
    }
    for (String jarBundle : jarBundles) {
        JarInputStream jarInputStream = null;
        File jarFile = new File(jarBundle);
        if (!jarFile.exists()) {
            getLog().error(jarFile + " does not exist, skipping !");
            continue;
        }
        try {
            jarInputStream = new JarInputStream(new FileInputStream(jarBundle));
            StringWriter stringWriter = new StringWriter();
            PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
            BundleUtils.dumpManifestHeaders(jarInputStream, stringPrintWriter);
            getLog().info(jarBundle + " header dump:\n" + stringWriter.getBuffer().toString());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } finally {
            IOUtils.closeQuietly(jarInputStream);
        }
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.hadoopbackport.TestJarFinder.java

@Test
public void testExistingManifest() throws Exception {
    File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
            TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);/*from w  w w .  j a v  a 2 s  .c o m*/
    dir.mkdirs();

    File metaInfDir = new File(dir, "META-INF");
    metaInfDir.mkdirs();
    File manifestFile = new File(metaInfDir, "MANIFEST.MF");
    Manifest manifest = new Manifest();
    OutputStream os = new FileOutputStream(manifestFile);
    manifest.write(os);
    os.close();

    File propsFile = new File(dir, "props.properties");
    Writer writer = new FileWriter(propsFile);
    new Properties().store(writer, "");
    writer.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream zos = new JarOutputStream(baos);
    JarFinder.jarDir(dir, "", zos);
    JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Assert.assertNotNull(jis.getManifest());
    jis.close();
}

From source file:org.apache.pluto.util.assemble.ear.EarAssemblerTest.java

protected void validateEarAssembly(File earFile) throws Exception {
    assertTrue("EAR archive [" + earFile.getAbsolutePath() + "] cannot be found or cannot be read",
            earFile.exists() && earFile.canRead());

    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    PortletApplicationDefinition portletApp = null;

    PlutoWebXmlRewriter webXmlRewriter = null;

    int earEntryCount = 0;
    int warEntryCount = 0;

    JarInputStream earIn = new JarInputStream(new FileInputStream(earFile));

    JarEntry earEntry;//from  w  w  w.  j a v a 2  s .  c  o m
    JarEntry warEntry;

    while ((earEntry = earIn.getNextJarEntry()) != null) {
        earEntryCount++;
        if (earEntry.getName().endsWith(".war")) {
            warEntryCount++;
            JarInputStream warIn = new JarInputStream(earIn);
            while ((warEntry = warIn.getNextJarEntry()) != null) {
                if (Assembler.PORTLET_XML.equals(warEntry.getName())) {
                    portletApp = portletSvc.read("test", "/test",
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
                if (Assembler.SERVLET_XML.equals(warEntry.getName())) {
                    webXmlRewriter = new PlutoWebXmlRewriter(
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
            }
        }
    }

    assertTrue("EAR archive did not contain any entries", earEntryCount > 0);
    assertTrue("WAR archive did not contain any entries", warEntryCount > 0);
    assertNotNull("WAR archive did not contain a portlet.xml", portletApp);
    assertNotNull("WAR archive did not contain a servlet.xml", webXmlRewriter);
    assertTrue("WAR archive did not contain any servlets", webXmlRewriter.hasServlets());
    assertTrue("WAR archive did not contain any servlet mappings", webXmlRewriter.hasServletMappings());
    assertTrue("WAR archive did not contain any portlets", portletApp.getPortlets().size() > 0);

    PortletDefinition portlet = (PortletDefinition) portletApp.getPortlets().iterator().next();
    assertEquals("Unexpected test portlet name.", testPortletName, portlet.getPortletName());

    String servletClassName = webXmlRewriter.getServletClass(portlet.getPortletName());
    assertNotNull("web.xml does not contain assembly for test portlet", servletClassName);
    assertEquals("web.xml does not contain correct dispatch servet", Assembler.DISPATCH_SERVLET_CLASS,
            servletClassName);
}

From source file:org.apache.brooklyn.rt.felix.EmbeddedFelixFrameworkTest.java

@Test
public void testReadKnownManifest() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    InputStream in = this.getClass().getResourceAsStream(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    JarInputStream jarIn = new JarInputStream(in);
    ManifestHelper helper = ManifestHelper.forManifest(jarIn.getManifest());
    jarIn.close();/*w ww .  j a v a  2  s.  c om*/
    Assert.assertEquals(helper.getVersion().toString(), "0.1.0");
    Assert.assertTrue(helper.getExportedPackages().contains("org.apache.brooklyn.test.osgi.entities"));
}

From source file:com.asual.summer.onejar.OneJarMojo.java

public void execute() throws MojoExecutionException {

    JarOutputStream out = null;//from   w  w  w. j  a v a 2 s. com
    JarInputStream in = null;

    try {

        File jarFile = new File(buildDirectory, jarName);
        File warFile = new File(buildDirectory, warName);

        Manifest manifest = new Manifest(new ByteArrayInputStream("Manifest-Version: 1.0\n".getBytes("UTF-8")));
        manifest.getMainAttributes().putValue("Main-Class", JAR_MAIN_CLASS);
        manifest.getMainAttributes().putValue("One-Jar-Main-Class", ONE_JAR_MAIN_CLASS);

        out = new JarOutputStream(new FileOutputStream(jarFile, false), manifest);
        in = new JarInputStream(getClass().getClassLoader().getResourceAsStream(ONE_JAR_DIST));

        putEntry(out, new FileInputStream(warFile), new ZipEntry(JAR_CLASSPATH + warFile.getName()));

        for (Artifact artifact : pluginArtifacts) {
            if (artifact.getArtifactId().equalsIgnoreCase("summer-onejar")) {
                artifact.updateVersion(artifact.getVersion(), localRepository);
                putEntry(out, new FileInputStream(artifact.getFile()),
                        new ZipEntry(JAR_CLASSPATH + artifact.getFile().getName()));
                MavenProject project = mavenProjectBuilder.buildFromRepository(artifact,
                        remoteArtifactRepositories, localRepository);
                List<Dependency> dependencies = project.getDependencies();
                for (Dependency dependency : dependencies) {
                    if (!"provided".equals(dependency.getScope())) {
                        Artifact dependencyArtifact = artifactFactory.createArtifact(dependency.getGroupId(),
                                dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(),
                                dependency.getType());
                        dependencyArtifact.updateVersion(dependencyArtifact.getVersion(), localRepository);
                        putEntry(out, new FileInputStream(dependencyArtifact.getFile()),
                                new ZipEntry(JAR_CLASSPATH + dependencyArtifact.getFile().getName()));
                    }
                }
            }
        }

        while (true) {
            ZipEntry entry = in.getNextEntry();
            if (entry != null) {
                putEntry(out, in, entry);
            } else {
                break;
            }
        }

        projectHelper.attachArtifact(project, "jar", jarFile);

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java

private static void compareJarContents(File orgJar, File actualJar) throws IOException {
    try (JarInputStream jis1 = new JarInputStream(new FileInputStream(orgJar));
            JarInputStream jis2 = new JarInputStream(new FileInputStream(actualJar))) {
        JarEntry je1 = null;/*from   w ww.  ja v a2 s . c  o  m*/
        while ((je1 = jis1.getNextJarEntry()) != null) {
            if (je1.isDirectory())
                continue;

            JarEntry je2 = null;
            while ((je2 = jis2.getNextJarEntry()) != null) {
                if (!je2.isDirectory())
                    break;
            }

            assertEquals(je1.getName(), je2.getName());
            assertEquals(je1.getSize(), je2.getSize());

            try {
                byte[] buf1 = IOUtils.toByteArray(jis1);
                byte[] buf2 = IOUtils.toByteArray(jis2);

                assertArrayEquals("Contents not equal: " + je1.getName(), buf1, buf2);
            } finally {
                jis1.closeEntry();
                jis2.closeEntry();
            }
        }
    }
}

From source file:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }// www .  ja va  2s  .c  om
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:org.jahia.admin.components.AssemblerTask.java

private boolean needRewriting(File source) throws FileNotFoundException, IOException {
    final JarInputStream jarIn = new JarInputStream(new FileInputStream(source));
    String webXml = null;//from w  w w. j  av  a2 s. co  m
    JarEntry jarEntry;
    try {
        // Read the source archive entry by entry
        while ((jarEntry = jarIn.getNextJarEntry()) != null) {
            if (Assembler.SERVLET_XML.equals(jarEntry.getName())) {
                webXml = IOUtils.toString(jarIn);
            }
            jarIn.closeEntry();
        }
    } finally {
        jarIn.close();
    }

    return webXml == null || !webXml.contains(Assembler.DISPATCH_SERVLET_CLASS);
}