Example usage for java.util.jar JarFile getJarEntry

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

Introduction

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

Prototype

public JarEntry getJarEntry(String name) 

Source Link

Document

Returns the JarEntry for the given base entry name or null if not found.

Usage

From source file:org.jahia.configuration.configurators.JahiaGlobalConfiguratorTest.java

public void testGlobalConfiguration() throws Exception {

    JahiaConfigBean websphereDerbyConfigBean;

    Logger logger = LoggerFactory.getLogger(JahiaGlobalConfiguratorTest.class);

    URL configuratorsResourceURL = this.getClass().getClassLoader().getResource("configurators");
    File configuratorsFile = new File(configuratorsResourceURL.toURI());

    websphereDerbyConfigBean = new JahiaConfigBean();
    websphereDerbyConfigBean.setDatabaseType("derby_embedded");
    websphereDerbyConfigBean.setTargetServerType("was");
    websphereDerbyConfigBean.setTargetServerVersion("6.1.0.25");
    websphereDerbyConfigBean.setTargetConfigurationDirectory(configuratorsFile.toString());
    websphereDerbyConfigBean.setCluster_activated("true");
    websphereDerbyConfigBean.setCluster_node_serverId("jahiaServer1");
    websphereDerbyConfigBean.setProcessingServer("true");
    websphereDerbyConfigBean.setLdapActivated("true");
    websphereDerbyConfigBean.setExternalizedConfigActivated(true);
    websphereDerbyConfigBean.setExternalizedConfigExploded(false);
    websphereDerbyConfigBean.setExternalizedConfigTargetPath(configuratorsFile.getPath());
    websphereDerbyConfigBean.setExternalizedConfigClassifier("jahiaServer1");
    websphereDerbyConfigBean.setExternalizedConfigFinalName("jahia-externalized-config");
    websphereDerbyConfigBean.setJeeApplicationLocation(configuratorsFile.toString());
    websphereDerbyConfigBean.setJeeApplicationModuleList(
            "jahia-war:web:jahia.war:jahia,portlet-testsuite:web:websphere-testsuite.war:testsuite,java-example:java:somecode.jar");
    websphereDerbyConfigBean.setJahiaToolManagerUsername("toolmgr");

    JahiaGlobalConfigurator jahiaGlobalConfigurator = new JahiaGlobalConfigurator(new SLF4JLogger(logger),
            websphereDerbyConfigBean);//w  w w. ja v  a 2s  . c  om
    jahiaGlobalConfigurator.execute();

    File configFile = new File(configuratorsFile, "jahia-externalized-config-jahiaServer1.jar");
    JarFile configJarFile = new JarFile(configFile);
    try {
        JarEntry licenseJarEntry = configJarFile.getJarEntry("jahia/license.xml");
        assertNotNull("Missing license file in jahia-externalized-config-jahiaServer1.jar file!",
                licenseJarEntry);
        JarEntry jahiaPropertiesJarEntry = configJarFile.getJarEntry("jahia/jahia.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaPropertiesJarEntry);
        JarEntry jahiaAdvancedPropertiesJarEntry = configJarFile
                .getJarEntry("jahia/jahia.node.jahiaServer1.properties");
        assertNotNull(
                "Missing jahia.node.jahiaServer1.properties file in jahia-externalized-config-jahiaServer1.jar file!",
                jahiaAdvancedPropertiesJarEntry);

        InputStream jahiaPropsInputStream = configJarFile.getInputStream(jahiaPropertiesJarEntry);
        Properties jahiaProperties = new Properties();
        jahiaProperties.load(jahiaPropsInputStream);
        assertEquals("Tool manager is not set", "toolmgr", jahiaProperties.get("jahiaToolManagerUsername"));
    } finally {
        configJarFile.close();
    }
    // The following tests are NOT exhaustive
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document jdomDocument = saxBuilder.build(configuratorsFile.toString() + "/META-INF/application.xml");
    String prefix = "";

    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/web-uri/text()", prefix,
            "jahia.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"jahia-war\"]/web/context-root/text()", prefix,
            "jahia");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/web-uri/text()",
            prefix, "websphere-testsuite.war");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"portlet-testsuite\"]/web/context-root/text()",
            prefix, "testsuite");
    assertAllTextEquals(jdomDocument, "//application/module[@id=\"java-example\"]/java/text()", prefix,
            "somecode.jar");

}

From source file:org.jahia.configuration.modules.ModuleDeployer.java

private void copyDbScripts(File warFile, File targetDir) {
    JarFile war = null;
    try {//w ww .  j a va2s .  co m
        war = new JarFile(warFile);
        if (war.getJarEntry("META-INF/db") != null) {
            war.close();
            ZipUnArchiver unarch = new ZipUnArchiver(warFile);
            File tmp = new File(FileUtils.getTempDirectory(), String.valueOf(System.currentTimeMillis()));
            tmp.mkdirs();
            File destDir = new File(targetDir, "db/sql/schema");
            try {
                unarch.extract("META-INF/db", tmp);
                FileUtils.copyDirectory(new File(tmp, "META-INF/db"), destDir);
            } finally {
                FileUtils.deleteQuietly(tmp);
            }
            logger.info("Copied database scripts from " + warFile.getName() + " to " + destDir);
        }
    } catch (Exception e) {
        logger.error("Error copying database scripts for module " + warFile, e);
    } finally {
        if (war != null) {
            try {
                war.close();
            } catch (Exception e) {
                logger.warn("Unable to close the JAR file " + warFile, e);
            }
        }
    }
}

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

private int scanJar(File jarFile, boolean externalDependency, String packageDirectory, String version,
        boolean optional, ParsingContext parsingContext, String logPrefix) throws IOException {
    int scanned = 0;

    if (jarFile.isDirectory()) {
        getLog().debug(logPrefix + "Processing dependency directory " + jarFile + "...");
        processDirectoryTlds(jarFile, version, parsingContext);
        processDirectory(jarFile, false, version, parsingContext);
        return scanned;
    }//from   w w  w .  j a  v  a 2s.com

    JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
    try {
        JarEntry jarEntry = null;
        getLog().debug(logPrefix + "Processing JAR file " + jarFile + "...");
        if (processJarManifest(jarFile, parsingContext, jarInputStream)) {
            getLog().debug(logPrefix
                    + "Used OSGi bundle manifest information, but scanning for additional resources (taglibs, CNDs, etc)... ");
        }
        scanned = processJarInputStream(jarFile.getPath(), externalDependency, packageDirectory, version,
                optional, parsingContext, logPrefix, scanned, jarInputStream);
    } finally {
        jarInputStream.close();
    }

    if (parsingContext.getBundleClassPath().size() > 0) {
        getLog().debug(logPrefix + "Processing embedded dependencies...");
        JarFile jar = new JarFile(jarFile);
        for (String embeddedJar : parsingContext.getBundleClassPath()) {
            if (".".equals(embeddedJar)) {
                continue;
            }
            JarEntry jarEntry = jar.getJarEntry(embeddedJar);
            if (jarEntry != null) {
                getLog().debug(logPrefix + "Processing embedded JAR..." + jarEntry);
                InputStream jarEntryInputStream = jar.getInputStream(jarEntry);
                ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarEntryInputStream, entryOutputStream);
                JarInputStream entryJarInputStream = new JarInputStream(
                        new ByteArrayInputStream(entryOutputStream.toByteArray()));
                processJarInputStream(jarFile.getPath() + "!" + jarEntry, externalDependency, packageDirectory,
                        version, optional, parsingContext, logPrefix, scanned, entryJarInputStream);
                IOUtils.closeQuietly(jarEntryInputStream);
                IOUtils.closeQuietly(entryJarInputStream);
            } else {
                getLog().warn(logPrefix + "Couldn't find embedded JAR to parse " + embeddedJar + " in JAR "
                        + jarFile);
            }
        }
    }

    if (parsingContext.getAdditionalFilesToParse().size() > 0) {
        getLog().debug(logPrefix + "Processing additional files to parse...");
        JarFile jar = new JarFile(jarFile);
        for (String fileToParse : parsingContext.getAdditionalFilesToParse()) {
            JarEntry jarEntry = jar.getJarEntry(fileToParse);
            if (jarEntry != null) {
                InputStream jarEntryInputStream = jar.getInputStream(jarEntry);
                ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarEntryInputStream, entryOutputStream);
                if (processNonTldFile(jarEntry.getName(),
                        new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFile.getPath(), optional,
                        version, parsingContext)) {
                    scanned++;
                }
                IOUtils.closeQuietly(jarEntryInputStream);
            } else {
                getLog().warn(logPrefix + "Couldn't find additional file to parse " + fileToParse + " in JAR "
                        + jarFile);
            }
        }
        parsingContext.clearAdditionalFilesToParse();
    }

    return scanned;
}

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

/**
 * Writes the WAR to Tomcat's webapps directory, as specified by {@link TomcatDeployerConfig#getCatalinaWebapps()}.
 *///from ww  w . j av  a2  s .  c  om
@Override
protected final void deployWar(WebModule webModule, JarFile earFile, DeployerConfig deployerConfig)
        throws MojoFailureException {
    final String webUri = webModule.getWebUri();
    final JarEntry warEntry = earFile.getJarEntry(webUri);
    final File webappsDir = getWebAppsDir(deployerConfig);

    String contextName = webModule.getContextRoot();
    if (contextName.endsWith(".war")) {
        contextName = contextName.substring(contextName.length() - 4);
    }
    if (contextName.startsWith("/")) {
        contextName = contextName.substring(1);
    }

    if (deployerConfig.isRemoveExistingWebappDirectories()) {
        final File contextDir = new File(webappsDir, contextName);

        if (contextDir.exists()) {
            try {
                FileUtils.deleteDirectory(contextDir);
            } catch (IOException e) {
                throw new MojoFailureException("Failed to remove webapp context directory: " + contextDir, e);
            }
        }
    }

    if (deployerConfig.isExtractWars()) {
        final File contextDir = new File(webappsDir, contextName);
        this.extractWar(earFile, warEntry, contextDir);
    } else {
        final String warName = contextName += ".war";
        File warDest;
        try {
            warDest = this.createSafeFile(webappsDir, warName);
        } catch (IOException e) {
            throw new MojoFailureException(
                    "Failed to setup File to deploy '" + warName + "' to '" + webappsDir + "'", e);
        }
        this.copyAndClose(warEntry, earFile, warDest);
    }
}

From source file:org.jsweet.transpiler.candies.CandiesProcessor.java

private void extractCandy( //
        CandyDescriptor descriptor, //
        JarFile jarFile, //
        File javaOutputDirectory, //
        File tsDefOutputDirectory, //
        File jsOutputDirectory, //
        Predicate<String> isTsDefToBeExtracted) {
    logger.info("extract candy: " + jarFile.getName() + " javaOutputDirectory=" + javaOutputDirectory
            + " tsDefOutputDirectory=" + tsDefOutputDirectory + " jsOutputDir=" + jsOutputDirectory);

    jarFile.stream().filter(entry -> entry.getName().endsWith(".d.ts")
            && (entry.getName().startsWith("src/") || entry.getName().startsWith("META-INF/resources/"))) //
            .forEach(entry -> {/*from   w w  w  .  jav  a2 s.c o m*/

                File out;
                if (entry.getName().endsWith(".java")) {
                    // RP: this looks like dead code...
                    out = new File(javaOutputDirectory + "/" + entry.getName().substring(4));
                } else if (entry.getName().endsWith(".d.ts")) {
                    if (isTsDefToBeExtracted != null && !isTsDefToBeExtracted.test(entry.getName())) {
                        return;
                    }
                    out = new File(tsDefOutputDirectory + "/" + entry.getName());
                } else {
                    out = null;
                }
                extractEntry(jarFile, entry, out);
            });

    for (String jsFilePath : descriptor.jsFilesPaths) {
        JarEntry entry = jarFile.getJarEntry(jsFilePath);
        String relativeJsPath = jsFilePath.substring(descriptor.jsDirPath.length());

        File out = new File(jsOutputDirectory, relativeJsPath);
        extractEntry(jarFile, entry, out);
    }
}

From source file:org.kepler.objectmanager.ActorMetadata.java

/**
 * search the classpath for a specific class and return the file. In the
 * tradition of ptolemy, this will also search for moml files with a class
 * definition. this is required for composite actors.
 * /*from   w w  w  .  j av a2  s . c  om*/
 * @param className
 *            the name of the class to search for
 * @param workDir
 *            the directory where temp files can be created
 */
protected File searchClasspath(String className) throws FileNotFoundException {

    // separate the class name from the package path
    String actualClassName = className.substring(className.lastIndexOf(".") + 1, className.length());
    String packagePath = className.substring(0, className.lastIndexOf("."));
    String[] packagePathStruct = packagePath.split("\\.");

    // get the classpath so we can search for the class files
    String classpath = System.getProperty("java.class.path");
    String sep = System.getProperty("path.separator");
    StringTokenizer st = new StringTokenizer(classpath, sep);

    while (st.hasMoreTokens()) {
        String path = st.nextToken();
        File pathDir = new File(path);

        if (pathDir.isDirectory()) {
            // search the directory for the file

            if (matchDirectoryPath(pathDir, packagePathStruct, 0)) {
                // now we found a candidate...see if the class is in there
                File classDir = new File(pathDir.getAbsolutePath() + File.separator
                        + packagePath.replace('.', File.separator.toCharArray()[0]));
                File[] classDirFiles = classDir.listFiles();
                for (int i = 0; i < classDirFiles.length; i++) {

                    String dirFileName = classDirFiles[i].getName();

                    if (dirFileName.indexOf(".") != -1) {
                        String extension = dirFileName.substring(dirFileName.lastIndexOf("."),
                                dirFileName.length());
                        String prefix = dirFileName.substring(0, dirFileName.lastIndexOf("."));
                        if (actualClassName.equals(prefix)
                                && (extension.equals(".class") || extension.equals(".xml"))) {
                            // search for xml or class files
                            return classDirFiles[i];
                        }
                    }
                }
            }
        } else if (pathDir.isFile()) {
            // search a jar file for the file. if it's not a jar file,
            // ignore it
            try {
                String entryName = className.replace('.', '/') + ".class";
                JarFile jarFile = null;
                try {
                    jarFile = new JarFile(pathDir);
                    // this looks for a class file
                    JarEntry entry = jarFile.getJarEntry(entryName);
                    if (entry != null) {
                        // get the class file from the jar and return it
                        return pathDir;
                    } else {
                        // look for the xml file instead
                        entryName = className.replace('.', '/') + ".xml";
                        entry = jarFile.getJarEntry(entryName);
                        if (entry != null) {
                            return pathDir;
                        }
                    }
                } finally {
                    if (jarFile != null) {
                        jarFile.close();
                    }
                }
            } catch (Exception e) {
                // keep going if this isn't a jar file
                continue;
            }
        }
    }
    throw new FileNotFoundException("Cannot find the specified class " + "file in the classpath.");
}

From source file:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
  * Returns the URL of a given resource in the given file which may
  * either be a directory or a jar file.
  */*from www .  ja v a 2  s.c o  m*/
  * @param file The file (directory or jar) in which to search for
  *             the resource. Must not be <code>null</code>.
  * @param resourceName The name of the resource for which a stream
  *                     is required. Must not be <code>null</code>.
  *
  * @return a stream to the required resource or <code>null</code> if the
  *         resource cannot be found in the given file object.
  */
private URL getResourceURL(URL url, String resourceName) {
    JarFile jFile = null;
    try {
        // gets the file from URL
        File file = new File(url.toURI());
        // if is a directory, then checks on the file system
        // where URL id the parent file and resource name is the file
        if (file.isDirectory()) {
            File resource = new File(file, resourceName);
            // checks if exists
            if (resource.exists()) {
                // returns URL
                return resource.toURI().toURL();
            }
        } else if (file.exists()) {
            // if here, the URL must be a link to a JAR file
            jFile = new JarFile(file);
            // searches in the JAR for the resource name
            JarEntry entry = jFile.getJarEntry(resourceName);
            // if found return the JAR URL
            if (entry != null) {
                return new URL("jar:" + file.toURI().toURL() + "!/" + entry);
            }
        }
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    } finally {
        // closes the JAR file if open
        if (jFile != null) {
            try {
                jFile.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
    return null;
}

From source file:org.pepstock.jem.util.ReverseURLClassLoader.java

/**
  * Returns an input stream to a given resource in the given file which may
  * either be a directory or a jar file.
  */*from  w w  w. j a  va  2 s  .  c o m*/
  * @param url the file (directory or jar) in which to search for the
  *             resource. Must not be <code>null</code>.
  * @param resourceName The name of the resource for which a stream is
  *                     required. Must not be <code>null</code>.
  *
  * @return a stream to the required resource or <code>null</code> if
  *         the resource cannot be found in the given file.
  */
private InputStream getResourceStream(URL url, String resourceName) {
    JarFile jFile = null;
    try {
        // gets the file from URL
        File file = new File(url.toURI());
        // if is a directory, then checks on the file system
        // where URL id the parent file and resource name is the file
        if (file.isDirectory()) {
            File resource = new File(file, resourceName);
            // checks if exists
            if (resource.exists()) {
                // returns inpu stream
                return new FileInputStream(resource);
            }
        } else if (file.exists()) {
            // if here, the URL must be a link to a JAR file
            jFile = new JarFile(file);
            // searches in the JAR for the resource name
            JarEntry entry = jFile.getJarEntry(resourceName);
            // if found return the JAR InputStream
            if (entry != null) {
                // FINDBUGS: it's correct do not close the jar file
                // otherwise the stream will be closed
                InputStream resourceIS = jFile.getInputStream(entry);
                // reads input stream in byte array
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                return copy(jFile, resourceIS, baos);
            }
            // close always the jar file
            jFile.close();
        }
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
    }
    return null;
}

From source file:org.rhq.enterprise.server.core.AgentManagerBean.java

@ExcludeDefaultInterceptors
public File getAgentUpdateVersionFile() throws Exception {
    File agentDownloadDir = getAgentDownloadDir();
    File versionFile = new File(agentDownloadDir, "rhq-server-agent-versions.properties");
    if (!versionFile.exists()) {
        // we do not have the version properties file yet, let's extract some info and create one
        StringBuilder serverVersionInfo = new StringBuilder();

        // first, get the server version info (by asking our server for the info)
        CoreServerMBean coreServer = LookupUtil.getCoreServer();
        serverVersionInfo.append(RHQ_SERVER_VERSION + '=').append(coreServer.getVersion()).append('\n');
        serverVersionInfo.append(RHQ_SERVER_BUILD_NUMBER + '=').append(coreServer.getBuildNumber())
                .append('\n');

        // calculate the MD5 of the agent update binary file
        File binaryFile = getAgentUpdateBinaryFile();
        String md5Property = RHQ_AGENT_LATEST_MD5 + '=' + MessageDigestGenerator.getDigestString(binaryFile)
                + '\n';

        // second, get the agent version info (by peeking into the agent update binary jar)
        JarFile binaryJarFile = new JarFile(binaryFile);
        try {// w  w w .j a v  a  2 s  . c  o m
            JarEntry binaryJarFileEntry = binaryJarFile.getJarEntry("rhq-agent-update-version.properties");
            InputStream binaryJarFileEntryStream = binaryJarFile.getInputStream(binaryJarFileEntry);

            // now write the server and agent version info in our internal version file our servlet will use
            FileOutputStream versionFileOutputStream = new FileOutputStream(versionFile);
            try {
                versionFileOutputStream.write(serverVersionInfo.toString().getBytes());
                versionFileOutputStream.write(md5Property.getBytes());
                StreamUtil.copy(binaryJarFileEntryStream, versionFileOutputStream, false);
            } finally {
                try {
                    versionFileOutputStream.close();
                } catch (Exception e) {
                }
                try {
                    binaryJarFileEntryStream.close();
                } catch (Exception e) {
                }
            }
        } finally {
            binaryJarFile.close();
        }
    }

    return versionFile;
}

From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java

/**
 * Parse the passed war file, try to read an enclosed jboss-web.xml and look for
 * virtual-hosts in it. If found, return one virtual host name. Else return localhost.
 * @param warFile File pointer pointing to a .war file
 * @return The name of a defined virtual host or localhost
 *//* ww  w  .j  a  va  2  s .c o  m*/
private String getVhostFromWarFile(File warFile) {

    JarFile jfile = null;
    InputStream is = null;
    try {
        jfile = new JarFile(warFile);
        JarEntry entry = jfile.getJarEntry("WEB-INF/jboss-web.xml");
        if (entry != null) {
            is = jfile.getInputStream(entry);
            SAXBuilder saxBuilder = new SAXBuilder();
            SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver
                    .getDtdAndXsdSkippingInstance();
            saxBuilder.setEntityResolver(entityResolver);

            Document doc = saxBuilder.build(is);
            Element root = doc.getRootElement(); // <jboss-web>
            List<Element> vHosts = root.getChildren("virtual-host");
            if (vHosts == null || vHosts.isEmpty()) {
                if (log.isDebugEnabled())
                    log.debug("No vhosts found in war file, using " + LOCALHOST);
                return LOCALHOST;
            }

            // So we have vhost, just return one of them, this is enough
            Element vhost = vHosts.get(0);
            return vhost.getText();
        }
    } catch (Exception ioe) {
        log.warn("Exception when getting vhost from war file : " + ioe.getMessage());
    } finally {
        if (jfile != null) {
            if (is != null) {
                try {
                    // see http://bugs.sun.com/view_bug.do?bug_id=6735255 for why we do this
                    is.close();
                } catch (IOException e) {
                    log.info("Exception when trying to close the war file stream: " + e.getMessage());
                }
            }
            try {
                jfile.close();
            } catch (IOException e) {
                log.info("Exception when trying to close the war file: " + e.getMessage());
            }
        }
    }

    // We're not able to determine a vhost, so return localhost
    return LOCALHOST;
}