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:com.kotcrab.vis.editor.plugin.PluginDescriptor.java

public PluginDescriptor(FileHandle file, Manifest manifest) throws EditorException {
    this.file = file;
    folderName = file.parent().name();// w w w.ja v  a  2  s .  com
    libs.addAll(file.parent().child("lib").list());

    Attributes attributes = manifest.getMainAttributes();

    id = attributes.getValue(PLUGIN_ID);
    name = attributes.getValue(PLUGIN_NAME);
    description = attributes.getValue(PLUGIN_DESCRIPTION);
    provider = attributes.getValue(PLUGIN_PROVIDER);
    version = attributes.getValue(PLUGIN_VERSION);
    String comp = attributes.getValue(PLUGIN_COMPATIBILITY);
    String licenseFile = attributes.getValue(PLUGIN_LICENSE);

    if (id == null || name == null || description == null || provider == null || version == null
            || comp == null)
        throw new EditorException("Missing one of required field in plugin manifest, plugin: " + file.name());

    try {
        compatibility = Integer.valueOf(comp);
    } catch (NumberFormatException e) {
        throw new EditorException("Failed to parse compatibility code, value must be integer!", e);
    }

    if (licenseFile != null && !licenseFile.isEmpty()) {
        JarFile jar = null;
        try {
            jar = new JarFile(file.file());
            JarEntry licenseEntry = jar.getJarEntry(licenseFile);
            license = StreamUtils.copyStreamToString(jar.getInputStream(licenseEntry));
        } catch (Exception e) {
            throw new EditorException("Failed to read license file for plugin: " + file.name(), e);
        } finally {
            IOUtils.closeQuietly(jar);
        }
    }
}

From source file:net.dmulloy2.ultimatearena.api.ArenaLoader.java

public final ArenaDescription getArenaDescription(File file) throws InvalidArenaException {
    Validate.notNull(file, "file cannot be null!");

    try (Closer closer = new Closer()) {
        JarFile jar = closer.register(new JarFile(file));
        JarEntry entry = jar.getJarEntry("arena.yml");

        if (entry == null)
            throw new InvalidArenaException(new FileNotFoundException("Jar does not contain arena.yml"));

        InputStream stream = closer.register(jar.getInputStream(entry));
        Map<?, ?> map = (Map<?, ?>) yaml.load(stream);

        String name = (String) map.get("name");
        Validate.notNull(name, "Missing required key: name");
        Validate.isTrue(name.matches("^[A-Za-z0-9 _.-]+$"), "Name '" + name + "' contains invalid characters");

        String main = (String) map.get("main");
        Validate.notNull(main, "Missing required key: main");

        String version = (String) map.get("version");
        Validate.notNull(version, "Missing required key: version");

        String author = (String) map.get("author");
        if (author == null)
            author = "Unascribed";

        String stylized = (String) map.get("stylized");
        if (stylized == null)
            stylized = name;// ww  w.ja v  a2  s .  c o m

        return new ArenaDescription(name, main, stylized, version, author);
    } catch (InvalidArenaException ex) {
        throw ex;
    } catch (Throwable ex) {
        throw new InvalidArenaException("Failed to read arena.yml from " + file.getName(), ex);
    }
}

From source file:io.fabric8.vertx.maven.plugin.it.PackagingIT.java

@Test
public void testContentInTheJar() throws IOException, VerificationException {
    File testDir = initProject(PACKAGING_META_INF);
    assertThat(testDir).isDirectory();//from  w  ww .  j av a  2 s. c om
    initVerifier(testDir);
    prepareProject(testDir, verifier);
    runPackage(verifier);

    assertThat(testDir).isNotNull();

    File out = new File(testDir, "target/vertx-demo-start-0.0.1.BUILD-SNAPSHOT.jar");
    assertThat(out).isFile();
    JarFile jar = new JarFile(out);

    // Commons utils
    // org.apache.commons.io.CopyUtils
    JarEntry entry = jar.getJarEntry("org/apache/commons/io/CopyUtils.class");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();

    // SLF4J-API
    // /org/slf4j/MDC.class
    entry = jar.getJarEntry("org/slf4j/MDC.class");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();

    // tc native
    // /org/apache/tomcat/Apr.class
    entry = jar.getJarEntry("org/apache/tomcat/Apr.class");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();
    // /org/apache/tomcat/apr.properties
    entry = jar.getJarEntry("org/apache/tomcat/apr.properties");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();
    // /META-INF/native/libnetty-tcnative-linux-x86_64.so
    entry = jar.getJarEntry("META-INF/native/libnetty-tcnative-linux-x86_64.so");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();

    // Jackson (transitive of vert.x core)
    // /com/fasterxml/jackson/annotation/JacksonAnnotation.class
    entry = jar.getJarEntry("com/fasterxml/jackson/annotation/JacksonAnnotation.class");
    assertThat(entry).isNotNull();
    assertThat(entry.isDirectory()).isFalse();

    // Not included
    // codegen - transitive optional
    entry = jar.getJarEntry("io/vertx/codegen/Case.class");
    assertThat(entry).isNull();
    // log4j - transitive provided
    entry = jar.getJarEntry("org/apache/log4j/MDC.class");
    assertThat(entry).isNull();
    // junit - test
    entry = jar.getJarEntry("junit/runner/Version.class");
    assertThat(entry).isNull();
    // commons-lang3 - provided
    entry = jar.getJarEntry("org/apache/commons/lang3/RandomUtils.class");
    assertThat(entry).isNull();

}

From source file:de.smartics.maven.plugin.jboss.modules.util.classpath.AbstractProjectClassLoader.java

/**
 * Opens a reader to the class file within the archive.
 *
 * @param className the name of the class to load.
 * @param fileName the name of the class file to load.
 * @param dirName the name of the directory the archive file is located.
 * @return the reader to the source file for the given class in the archive.
 * @throws ClassNotFoundException if the class cannot be found.
 *//*from ww  w .  j a  va  2  s. c  om*/
protected Class<?> loadClassFromLibrary(final String className, final String fileName, final File dirName)
        throws ClassNotFoundException {
    ensurePackageProvided(className);
    try {
        final JarFile jarFile = new JarFile(dirName); // NOPMD
        final JarEntry entry = jarFile.getJarEntry(fileName);
        if (entry != null) {
            InputStream in = null;
            try {
                in = new BufferedInputStream(jarFile.getInputStream(entry));
                final byte[] data = IOUtils.toByteArray(in);
                final Class<?> clazz = defineClass(className, data, 0, data.length);
                return clazz;
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (final IOException e) {
        final String message = "Cannot load class '" + className + "' from file '" + dirName + "'.";
        LOG.fine(message);

        throw new ClassNotFoundException(message, e);
    }

    final String message = "Cannot load class '" + className + "' from file '" + dirName + "'.";
    LOG.fine(message);

    throw new ClassNotFoundException(message);
}

From source file:com.eviware.soapui.actions.MockAsWarActionTest.java

private void assertValidWarFile(String warFileName) throws IOException {

    JarFile jarFile = new JarFile(warFileName);
    try {//from   www. j  a va  2s . c  o m
        for (String fileName : getExpectedWarContents()) {
            JarEntry jarEntry = jarFile.getJarEntry(fileName);
            assertNotNull(jarEntry);
        }
    } finally {
        jarFile.close();
    }
}

From source file:at.tuwien.minimee.migration.engines.MonitorEngineTOPDefault.java

/**
 * Copies resource file 'from' from destination 'to' and set execution permission.
 * /*from  w w  w  . jav  a  2s  . c  om*/
 * @param from
 * @param to
 * @throws Exception
 */
protected void copyFile(String from, String to, String workingDirectory) throws Exception {

    //
    // copy the shell script to the working directory
    //
    URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from);
    File f = new File(monitorCallShellScriptUrl.getFile());
    String directoryPath = f.getAbsolutePath();
    // if the application was created as exploded archive, the absolute path is a real filename
    String fileName = from;
    InputStream in = null;
    if (directoryPath.indexOf(".jar!") > -1) {
        // this class is not in an exploded archive, extract the filename  
        URL urlJar = new URL(
                directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!')));

        JarFile jf = new JarFile(urlJar.getFile());
        JarEntry je = jf.getJarEntry(from);
        fileName = je.getName();
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    } else {
        in = new FileInputStream(f);
    }

    File outScriptFile = new File(to);

    FileOutputStream fos = new FileOutputStream(outScriptFile);
    int nextChar;
    while ((nextChar = in.read()) != -1)
        fos.write(nextChar);

    fos.flush();
    fos.close();

    //
    // This seems kind of hard core, but we have to set execution rights for the shell script, 
    // otherwise we wouldn't be allowed to execute it.
    // The Java-way with FilePermission didn't work for some reason.
    //
    try {
        LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor();
        cmdExecutor.setWorkingDirectory(workingDirectory);

        cmdExecutor.runCommand("chmod 777 " + to);
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java

private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException {
    JarFile jarFile = null;
    try {/* w w w.j a  v  a 2  s .  co  m*/
        jarFile = new JarFile(jar);
        JarEntry entry = jarFile.getJarEntry(subPath);

        if (entry == null) {
            response.sendError(404);
            return;
        }

        // fallback for requesting a directory without a trailing /
        // this leads to a jarentry which is not null, and not a directory and of size 0
        // this shouldn't be
        if (!entry.isDirectory() && entry.getSize() == 0) {
            if (!subPath.endsWith("/")) {
                JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/");
                if (entryWithSlash != null && entryWithSlash.isDirectory()) {
                    entry = entryWithSlash;
                }
            }
        }

        if (entry.isDirectory()) {
            for (String indexFile : DEFAULT_INDEX_FILES) {
                entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile);
                if (entry != null) {
                    break;
                }
            }
        }

        if (entry == null) {
            response.sendError(404);
            return;
        }

        response.setContentLength((int) entry.getSize());
        String mimetype = getMimeType(entry.getName());
        response.setContentType(mimetype);
        InputStream input = jarFile.getInputStream(entry);
        try {
            ByteStreams.copy(input, response.getOutputStream());
        } finally {
            input.close();
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

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);/*from w  ww  .  j a  v  a 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:com.egreen.tesla.server.api.component.Component.java

/**
 *
 * Init configurations from Component/*from w  w w . j  a  va  2 s  .  com*/
 *
 * @param jf
 * @throws IOException
 * @throws ConfigurationException
 */
private void setConfiguraton(JarFile jf) throws IOException, ConfigurationException {
    JarEntry entry = jf.getJarEntry(TESLAR_WIDGET_MAINIFIESTXML);

    InputStream inputStream = jf.getInputStream(entry);
    configuration = new XMLConfiguration();
    configuration.load(inputStream);
    componentID = configuration.getString(Settings.COMPONENT_ID.getType());

    LOGGER.info("Loadding : " + componentID);

    component_base = context.getRealPath("/") + "/components/" + componentID;
}

From source file:com.taobao.android.apatch.MergePatch.java

private Dex getDexFromJar(File file) throws IOException {
    JarFile jarFile = null;
    try {// w  w w  .ja v a  2s  . c o m
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("classes.dex");
        return new Dex(jarFile.getInputStream(dexEntry));
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}