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.bimserver.plugins.VirtualFile.java

public static VirtualFile fromJar(InputStream inputStream) throws IOException {
    VirtualFile result = new VirtualFile();
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    JarEntry jarEntry = jarInputStream.getNextJarEntry();
    while (jarEntry != null) {
        String n = jarEntry.getName();
        n = n.replace("/", File.separator);
        n = n.replace("\\", File.separator);
        VirtualFile newFile = result.createFile(n);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(jarInputStream, byteArrayOutputStream);
        newFile.setData(byteArrayOutputStream.toByteArray());
        jarEntry = jarInputStream.getNextJarEntry();
    }//  w  ww  .j  a  v a2s.c om
    return result;
}

From source file:fr.gael.dhus.server.http.TomcatServer.java

public void install(fr.gael.dhus.server.http.WebApplication web_application) throws TomcatException {
    logger.info("Installing webapp " + web_application);
    String appName = web_application.getName();
    String folder;//from   w  w  w  .j  a v  a  2  s .co  m

    if (appName.trim().isEmpty()) {
        folder = "ROOT";
    } else {
        folder = appName;
    }

    try {
        if (web_application.hasWarStream()) {
            InputStream stream = web_application.getWarStream();
            if (stream == null) {
                throw new TomcatException("Cannot install webApplication " + web_application.getName()
                        + ". The referenced war file does not exist.");
            }
            JarInputStream jis = new JarInputStream(stream);
            File destDir = new File(tomcatpath, "webapps/" + folder);

            byte[] buffer = new byte[4096];
            JarEntry file;
            while ((file = jis.getNextJarEntry()) != null) {
                File f = new File(destDir + java.io.File.separator + file.getName());
                if (file.isDirectory()) { // if its a directory, create it
                    f.mkdirs();
                    continue;
                }
                if (!f.getParentFile().exists()) {
                    f.getParentFile().mkdirs();
                }

                java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
                int read;
                while ((read = jis.read(buffer)) != -1) {
                    fos.write(buffer, 0, read);
                }
                fos.flush();
                fos.close();
            }
            jis.close();
        }
        web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath());

        StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer();
        Container container = engine.findChild(engine.getDefaultHost());

        StandardContext ctx = new StandardContext();
        String url = (web_application.getName() == "" ? "" : "/") + web_application.getName();
        ctx.setName(url);
        ctx.setPath(url);
        ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath());

        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url));

        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);

        ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml");

        container.addChild(ctx);

        List<String> welcomeFiles = web_application.getWelcomeFiles();

        for (String welcomeFile : welcomeFiles) {
            ctx.addWelcomeFile(welcomeFile);
        }

        if (web_application.getAllow() != null || web_application.getDeny() != null) {
            RemoteIpValve valve = new RemoteIpValve();
            valve.setRemoteIpHeader("x-forwarded-for");
            valve.setProxiesHeader("x-forwarded-by");
            valve.setProtocolHeader("x-forwarded-proto");
            ctx.addValve(valve);

            RemoteAddrValve valve_addr = new RemoteAddrValve();
            valve_addr.setAllow(web_application.getAllow());
            valve_addr.setDeny(web_application.getDeny());
            ctx.addValve(valve_addr);
        }

        web_application.checkInstallation();
    } catch (Exception e) {
        throw new TomcatException("Cannot install webApplication " + web_application.getName(), e);
    }
}

From source file:org.artifactory.maven.MavenModelUtils.java

/**
 * Gathers maven artifact information which was (or was not) managed to gather from the given Jar file
 *
 * @param file Jar file to gather info from
 */// ww w. j  a va 2 s .  co  m

private static MavenArtifactInfo gatherInfoFromJarFile(File file) {
    MavenArtifactInfo artifactInfo = null;
    JarInputStream jis = null;
    JarEntry entry;
    try {
        //Create a stream and try to find the pom file within the jar
        jis = new JarInputStream(new FileInputStream(file));
        entry = getPomFile(jis);

        //If a valid pom file was found
        if (entry != null) {
            try {
                //Read the uncompressed content
                artifactInfo = mavenModelToArtifactInfo(jis);
                artifactInfo.setType(PathUtils.getExtension(file.getPath()));
            } catch (Exception e) {
                log.warn("Failed to read maven model from '" + entry.getName() + "'. Cause: " + e.getMessage()
                        + ".", e);
                artifactInfo = null;
            }
        }
    } catch (IOException e) {
        log.warn("Failed to read maven model from '" + file + "'. Cause: " + e.getMessage() + ".", e);
    } finally {
        IOUtils.closeQuietly(jis);
    }
    return artifactInfo;
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

/**
 * @param scanJarsAtDir//from   w  w  w . jav  a  2 s.c o m
 * @return A Map(featureId -> featureVersion)
 */
public Map<String, String> scanFeatureVersionsAtDir(final String scanJarsAtDir) {
    final Map<String, String> featureVersions = new LinkedHashMap<String, String>();

    final File file = new File(scanJarsAtDir);
    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return featureVersions;
    }

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                final String featureId = manifest.getMainAttributes().getValue("FeatureBuilder-FeatureId");
                final String featureVersion = manifest.getMainAttributes()
                        .getValue("FeatureBuilder-FeatureVersion");

                if (featureId != null && featureVersion != null) {
                    featureVersions.put(featureId, featureVersion);
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }
        }
    }
    return featureVersions;
}

From source file:org.apache.axis2.jaxws.framework.JAXWSDeployer.java

/**
 * Check if this inputstream is a jar/zip
 *
 * @param f - file/*ww  w .  jav  a 2 s .c  o m*/
 * @return true if inputstream is a jar
 */
public static boolean isJar(File f) {
    try {
        JarInputStream jis = new JarInputStream(new FileInputStream(f));
        if (jis.getNextEntry() != null) {
            return true;
        }
    } catch (IOException ioe) {
    }
    return false;
}

From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it.
 *
 * This is a static method to provide a convenience method for others to be able to use.
 *
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file
 * @throws PluginContainerException if failed to find or parse a descriptor file in the plugin jar
 *//* w w  w.ja  v  a2 s  .c  o m*/
public static PluginDescriptor loadPluginDescriptorFromUrl(URL pluginJarFileUrl)
        throws PluginContainerException {

    final Log logger = LogFactory.getLog(AgentPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new PluginContainerException("A valid plugin JAR URL must be supplied.");
    }
    logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;
    ValidationEventCollector validationEventCollector = new ValidationEventCollector();
    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        if (descriptorEntry == null) {
            throw new Exception("The plugin descriptor does not exist");
        }

        return parsePluginDescriptor(jis, validationEventCollector);
    } catch (Exception e) {
        throw new PluginContainerException(
                "Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                        + "] found in plugin jar at [" + pluginJarFileUrl + "].",
                new WrappedRemotingException(e));
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }

        logValidationEvents(pluginJarFileUrl, validationEventCollector, logger);
    }
}

From source file:org.xwiki.tool.packager.PackageMojo.java

private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException {
    VelocityContext context = createVelocityContext();
    Artifact configurationResourcesArtifact = this.factory.createArtifact("org.xwiki.platform",
            "xwiki-platform-tool-configuration-resources", this.project.getVersion(), "", "jar");
    resolveArtifact(configurationResourcesArtifact);

    configurationFileTargetDirectory.mkdirs();

    try {/* www  .  j  a v  a 2s . c om*/
        JarInputStream jarInputStream = new JarInputStream(
                new FileInputStream(configurationResourcesArtifact.getFile()));
        JarEntry entry;
        while ((entry = jarInputStream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".vm")) {

                String fileName = entry.getName().replace(".vm", "");
                File outputFile = new File(configurationFileTargetDirectory, fileName);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile));
                getLog().info("Writing config file: " + outputFile);
                // Note: Init is done once even if this method is called several times...
                Velocity.init();
                Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream));
                writer.close();
                jarInputStream.closeEntry();
            }
        }
        // Flush and close all the streams
        jarInputStream.close();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to extract configuration files", e);
    }
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries)
        throws IOException {
    // Create a jar with a manifest we'd expect to see merged.
    Path originalJar = folder.newFile("unexpected.jar");
    JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
    ignored.close();/*from w  w  w  .j a v  a  2 s.co m*/

    // Now create the actual manifest
    Path manifestFile = folder.newFile("actual_manfiest.mf");
    try (OutputStream os = Files.newOutputStream(manifestFile)) {
        fromUser.write(os);
    }

    Path tmp = folder.newFolder();
    Path output = tmp.resolve("example.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries,
            /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    step.execute(context);

    // Now verify that the created manifest matches the expected one.
    try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
        return jis.getManifest();
    }
}

From source file:org.drools.guvnor.server.RepositoryModuleService.java

private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException {
    if (!asset.isBinary()) {
        return null;
    }/*w ww  . j  av  a  2s .co m*/
    if (asset.getBinaryContentAttachment() == null) {
        return null;
    }

    JarInputStream jis;
    jis = new JarInputStream(asset.getBinaryContentAttachment());
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) {
                res.add(ModelContentHandler.convertPathToName(entry.getName()));
            }
        }
    }
    return jis;
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all installed i18n language properties
 * //from w ww.j a va2s. c o m
 * @param pageContext
 * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez)
 * @since 2.7.x
 */
public Map listLanguages(PageContext pageContext) {
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString();
    JarInputStream jarStream = null;

    try {
        JarEntry entry;
        InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH);
        jarStream = new JarInputStream(inputStream);

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();

            if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX)
                    && name.endsWith(I18NRESOURCE_SUFFIX)) {
                name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX));

                Locale locale = new Locale(name.substring(0, 2),
                        ((name.indexOf("_") == -1) ? "" : name.substring(3, 5)));

                String defaultLanguage = "";

                if (clientLanguage.startsWith(name)) {
                    defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE);
                }

                resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage);
            }
        }
    } catch (IOException ioe) {
        if (log.isDebugEnabled())
            log.debug("Could not search jar file '" + I18NRESOURCE_PATH
                    + "'for properties files due to an IOException: \n" + ioe.getMessage());
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
            }
        }
    }

    return resultMap;
}