Example usage for java.util.jar JarFile JarFile

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

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:com.photon.phresco.service.util.ServerUtil.java

public static InputStream getArtifactPomStream(File artifactFile) throws PhrescoException {
    String pomFile = null;/*from   w w w  . ja v  a 2  s  .  co m*/
    if (getFileExtension(artifactFile.getName()).equals(ServerConstants.JAR_FILE)) {
        try {
            JarFile jarfile = new JarFile(artifactFile);
            for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) {
                JarEntry jarEntry = em.nextElement();
                if (jarEntry.getName().endsWith("pom.xml")) {
                    pomFile = jarEntry.getName();
                }
            }
            if (pomFile != null) {
                ZipEntry entry = jarfile.getEntry(pomFile);
                return jarfile.getInputStream(entry);
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
    return null;
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//w  ww .j  a va  2s  .  co  m
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:org.apache.hadoop.streaming.StreamUtil.java

static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {//from   w w  w  .  ja  v  a  2  s.  co  m
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    file.getParentFile().mkdirs();
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.apache.geode.BundledJarsJUnitTest.java

/**
 * Find of of the jar files embedded within a war
 *//*from   ww  w. j  a v  a2 s  . c  om*/
private static Stream<File> extractJarNames(File war) {
    try (JarFile warContents = new JarFile(war)) {
        return warContents.stream()
                // Look for jars in the war
                .filter(entry -> entry.getName().endsWith(".jar"))
                // Create a File with a path that includes the war name
                .map(entry -> new File(war.getName(), entry.getName()))
                // Materialize the list of files while the war is still open
                .collect(Collectors.toList()).stream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.npower.dm.msm.JADCreator.java

public Manifest getJADManufest(File file, String jarURL) throws IOException {
    //JarInputStream jarIn = new JarInputStream(in);
    JarFile jar = new JarFile(file);
    Manifest srcManifest = jar.getManifest();
    /*/*from ww w. ja v a 2s  . c  om*/
    {
      Attributes attrs = srcManifest.getMainAttributes();
      for (Object akey: attrs.keySet()) {
          Object ov = attrs.get(akey);
          System.out.println(akey + ": " + ov);
      }
    }
    */
    Manifest manifest = new Manifest(srcManifest);
    manifest.getMainAttributes().put(new Attributes.Name("MIDlet-Jar-URL"), jarURL);
    manifest.getMainAttributes().put(new Attributes.Name("MIDlet-Jar-Size"), Long.toString(file.length()));
    return manifest;
}

From source file:com.zb.jcseg.core.JcsegTaskConfig.java

public static void unJar(File jarFile, File toDir) throws IOException {
    unJar(new JarFile(jarFile), toDir);
}

From source file:com.liferay.ide.project.core.modules.ServiceWrapperCommand.java

private Map<String, String[]> _getDynamicServiceWrapper() throws IOException {
    PortalRuntime portalRuntime = (PortalRuntime) _server.getRuntime().loadAdapter(PortalRuntime.class, null);

    IPath bundleLibPath = portalRuntime.getAppServerLibGlobalDir();
    IPath bundleServerPath = portalRuntime.getAppServerDir();

    Map<String, String[]> map = new LinkedHashMap<>();

    List<File> libFiles;

    File portalkernelJar = null;/*from   w w w.  ja  v  a2 s . c  o m*/

    try {
        libFiles = FileListing.getFileListing(new File(bundleLibPath.toOSString()));

        for (File lib : libFiles) {
            if (FileUtil.exists(lib) && lib.getName().endsWith("portal-kernel.jar")) {
                portalkernelJar = lib;

                break;
            }
        }

        libFiles = FileListing.getFileListing(new File(bundleServerPath.append("../osgi").toOSString()));

        libFiles.add(portalkernelJar);

        if (ListUtil.isNotEmpty(libFiles)) {
            for (File lib : libFiles) {
                if (lib.getName().endsWith(".lpkg")) {
                    try (JarFile jar = new JarFile(lib)) {
                        Enumeration<JarEntry> enu = jar.entries();

                        while (enu.hasMoreElements()) {
                            try {
                                JarEntry entry = enu.nextElement();

                                String name = entry.getName();

                                if (name.contains(".api-")) {
                                    JarEntry jarentry = jar.getJarEntry(name);

                                    try (InputStream inputStream = jar.getInputStream(jarentry);
                                            JarInputStream jarInputStream = new JarInputStream(inputStream)) {
                                        JarEntry nextJarEntry;

                                        while ((nextJarEntry = jarInputStream.getNextJarEntry()) != null) {
                                            String entryName = nextJarEntry.getName();

                                            _getServiceWrapperList(map, entryName, jarInputStream);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                            }
                        }
                    }
                } else if (lib.getName().endsWith("api.jar") || lib.getName().equals("portal-kernel.jar")) {

                    try (JarFile jar = new JarFile(lib);
                            InputStream inputStream = Files.newInputStream(lib.toPath());
                            JarInputStream jarinput = new JarInputStream(inputStream)) {

                        Enumeration<JarEntry> enu = jar.entries();

                        while (enu.hasMoreElements()) {
                            JarEntry entry = enu.nextElement();

                            String name = entry.getName();

                            _getServiceWrapperList(map, name, jarinput);
                        }
                    } catch (IOException ioe) {
                    }
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
    }

    return map;
}

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

@Test
public void testBSNRenaming() throws Exception {
    // Provide the system with some artifacts that are known to be in the local .m2 repo
    // These are explicitly included in the test section of the pom.xml
    PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2",
            "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app",
            "org.apache.sling/org.apache.sling.commons.json/2.0.12");
    try {// w w  w  .j a v  a  2 s. c o  m
        String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + ""
                + "[feature name=rename_test]\n"
                + "  org.apache.sling/org.apache.sling.commons.json/2.0.12 [bundle:rename-bsn=r-foo.bar.renamed.sling.commons.json]\n";

        Model model = ModelReader.read(new StringReader(modelTxt), null);
        ppm.execute(model);

        File orgJar = getMavenArtifactFile(getMavenRepoRoot(), "org.apache.sling",
                "org.apache.sling.commons.json", "2.0.12");
        File generatedJar = new File(ppm.getTmpDir() + "/r-foo.bar.renamed.sling.commons.json-2.0.12.jar");

        compareJarContents(orgJar, generatedJar);

        try (JarFile jfOrg = new JarFile(orgJar); JarFile jfNew = new JarFile(generatedJar)) {
            Manifest mfOrg = jfOrg.getManifest();
            Manifest mfNew = jfNew.getManifest();

            Attributes orgAttrs = mfOrg.getMainAttributes();
            Attributes newAttrs = mfNew.getMainAttributes();
            for (Object key : orgAttrs.keySet()) {
                String orgVal = orgAttrs.getValue(key.toString());
                String newVal = newAttrs.getValue(key.toString());

                if ("Bundle-SymbolicName".equals(key.toString())) {
                    assertEquals("Should have recorded the original Bundle-SymbolicName", orgVal,
                            newAttrs.getValue("X-Original-Bundle-SymbolicName"));

                    assertEquals("r-foo.bar.renamed.sling.commons.json", newVal);
                } else {
                    assertEquals("Different keys: " + key, orgVal, newVal);
                }
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory()));
    }
}

From source file:org.apache.cocoon.portal.pluto.Deploy.java

/**
 * Deploy the archive//from   www  .ja  v  a 2  s. c  o m
 * Unpack the archive in the servlet engine context directory
 */
public static void deployArchive(final String webAppsDir, final String warFile, final String warFileName)
        throws IOException {
    System.out.println("Deploying '" + warFileName + "' ...");

    final String destination = webAppsDir + warFileName;

    if (debug) {
        System.out.println("  unpacking '" + warFile + "' ...");
    }
    final JarFile jarFile = new JarFile(warFile);
    final Enumeration files = jarFile.entries();
    while (files.hasMoreElements()) {
        JarEntry entry = (JarEntry) files.nextElement();

        File file = new File(destination, entry.getName());
        File dirF = new File(file.getParent());
        dirF.mkdirs();
        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            byte[] buffer = new byte[1024];
            int length = 0;
            InputStream fis = jarFile.getInputStream(entry);
            FileOutputStream fos = new FileOutputStream(file);
            while ((length = fis.read(buffer)) >= 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
        }

    }

    if (debug) {
        System.out.println("Finished!");
    }
}