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.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

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

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

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.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 jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

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

        // Update the web.xml to contain the correct JENKINS_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 updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.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 = jenkinsTemplateWarJar.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(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

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

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

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static Map<String, File> extractContainedDepJars(JarFile jar, File baseModsDir, File versionedModsDir)
        throws IOException {
    Map<String, File> result = Maps.newHashMap();
    if (!jar.getManifest().getMainAttributes().containsKey(MODCONTAINSDEPS))
        return result;

    String deps = jar.getManifest().getMainAttributes().getValue(MODCONTAINSDEPS);
    String[] depList = deps.split(" ");
    for (String dep : depList) {
        String depEndName = new File(dep).getName(); // extract last part of name
        if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
            FMLRelaunchLog.log(Level.ERROR, "Skipping dep at request: %s", dep);
            continue;
        }/*from   w  ww  .j a  v a2s  .c o  m*/
        final JarEntry jarEntry = jar.getJarEntry(dep);
        if (jarEntry == null) {
            FMLRelaunchLog.log(Level.ERROR, "Found invalid ContainsDeps declaration %s in %s", dep,
                    jar.getName());
            continue;
        }
        File target = new File(versionedModsDir, depEndName);
        File modTarget = new File(baseModsDir, depEndName);
        if (target.exists()) {
            FMLRelaunchLog.log(Level.DEBUG, "Found existing ContainsDep extracted to %s, skipping extraction",
                    target.getCanonicalPath());
            result.put(dep, target);
            continue;
        } else if (modTarget.exists()) {
            FMLRelaunchLog.log(Level.DEBUG,
                    "Found ContainsDep in main mods directory at %s, skipping extraction",
                    modTarget.getCanonicalPath());
            result.put(dep, modTarget);
            continue;
        }

        FMLRelaunchLog.log(Level.DEBUG, "Extracting ContainedDep %s from %s to %s", dep, jar.getName(),
                target.getCanonicalPath());
        try {
            Files.createParentDirs(target);
            FileOutputStream targetOutputStream = null;
            InputStream jarInputStream = null;
            try {
                targetOutputStream = new FileOutputStream(target);
                jarInputStream = jar.getInputStream(jarEntry);
                ByteStreams.copy(jarInputStream, targetOutputStream);
            } finally {
                IOUtils.closeQuietly(targetOutputStream);
                IOUtils.closeQuietly(jarInputStream);
            }
            FMLRelaunchLog.log(Level.DEBUG, "Extracted ContainedDep %s from %s to %s", dep, jar.getName(),
                    target.getCanonicalPath());
            result.put(dep, target);
        } catch (IOException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "An error occurred extracting dependency");
        }
    }
    return result;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException {
    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(pathName);
    InputStream input = jarFile.getInputStream(entry);
    byte[] classData = new byte[(int) entry.getSize()];
    int totalBytes = 0;
    while (totalBytes < classData.length) {
        int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes);
        if (bytesRead == -1) {
            throw new IOException("Jar Entry too short!");
        }/*from  w  w  w. j  a v  a2  s  . c  om*/
        totalBytes += bytesRead;
    }
    Class<?> loadedClass = defineClass(name, classData, 0, classData.length,
            new CodeSource(url, entry.getCertificates()));
    input.close();
    jarFile.close();
    return loadedClass;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 *
 * @see java.lang.ClassLoader#findLibrary(java.lang.String)
 *//*from w w  w .  j a  v  a 2  s  . c  o m*/
protected String findLibrary(String libname) {
    try {
        String name = System.mapLibraryName(libname + "-" + System.getProperty("os.arch"));
        URL url = getResourceURL(name);
        log.info("Loading " + name + " from " + url);
        if (url != null) {
            File jar = cachedJars.get(url);
            JarFile jarFile = new JarFile(jar);
            JarEntry entry = jarFile.getJarEntry(name);
            File library = new File(localLibDirectory, name);
            if (!library.exists()) {
                InputStream input = jarFile.getInputStream(entry);
                FileOutputStream output = new FileOutputStream(library);
                byte[] buffer = new byte[BUFFER_SIZE];
                int totalBytes = 0;
                while (totalBytes < entry.getSize()) {
                    int bytesRead = input.read(buffer);
                    if (bytesRead < 0) {
                        throw new IOException("Jar Entry too short!");
                    }
                    output.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }
                output.close();
                input.close();
                jarFile.close();
            }
            return library.getAbsolutePath();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
    Validate.notNull(file, "File cannot be null");

    JarFile jar = null;
    InputStream stream = null;//from   w w w .ja v  a2  s.co m

    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry("plugin.yaml");

        if (entry == null)
            entry = jar.getJarEntry("plugin.yml");

        if (entry == null) {
            throw new InvalidDescriptionException(
                    new FileNotFoundException("Jar does not contain plugin.yaml"));
        }

        stream = jar.getInputStream(entry);

        return new PluginDescriptionFile(stream);

    } catch (IOException ex) {
        throw new InvalidDescriptionException(ex);
    } catch (YAMLException ex) {
        throw new InvalidDescriptionException(ex);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.util.InstallUtil.java

private Properties getDefaultProperties() throws IOException {
    String os = System.getProperty("os.name");

    String jar = ServerUtil.getPath() + "/install/installer.jar";
    String fileName = "data/installDefaultValues.properties";

    if (os.startsWith("Linux")) {
        fileName = "data/installDefaultValuesNoUI.properties";
    }/*  w w  w  . jav a2 s.c o m*/

    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(fileName);
    InputStream input = jarFile.getInputStream(entry);

    Properties p = new Properties();
    p.load(input);

    jarFile.close();
    return p;
}

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

private URL getWebappConfigFileFromJar(File docBase, String url) {
    URL result = null;/*from  w ww .  jav a2s.  c om*/
    JarFile jar = null;
    try {
        jar = new JarFile(docBase);
        JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
        if (entry != null) {
            result = new URL("jar:" + docBase.toURI().toString() + "!/" + Constants.ApplicationContextXml);
        }
    } catch (IOException e) {
        logger.warn("Unable to determine web application context.xml " + docBase, e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return result;
}

From source file:org.ormma.controller.OrmmaAssetController.java

/**
 * Copy text file from jar into asset directory.
 * /*from w ww. j a v  a2  s  .  c  o m*/
 * @param alias
 *            the alias to store it in
 * @param source
 *            the source
 * @return the path to the copied asset
 */
public String copyTextFromJarIntoAssetDir(String alias, String source) {
    InputStream in = null;
    try {
        URL url = OrmmaAssetController.class.getClassLoader().getResource(source);
        String file = url.getFile();
        if (file.startsWith("file:")) {
            file = file.substring(5);
        }
        int pos = file.indexOf("!");
        if (pos > 0)
            file = file.substring(0, pos);
        JarFile jf = new JarFile(file);
        JarEntry entry = jf.getJarEntry(source);
        in = jf.getInputStream(entry);
        String name = writeToDisk(in, alias, false);
        return name;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            in = null;
        }
    }
    return null;
}

From source file:ffx.FFXClassLoader.java

/**
 * {@inheritDoc}//from ww  w.ja  v  a2  s .  c o m
 *
 * Returns the URL of the given resource searching first if it exists among
 * the extension JARs given in constructor.
 */
@Override
public URL findResource(String name) {
    if (!extensionsLoaded) {
        loadExtensions();
    }

    if (name.equals("List all scripts")) {
        listScripts();
    }

    if (extensionJars != null) {
        for (JarFile extensionJar : extensionJars) {
            JarEntry jarEntry = extensionJar.getJarEntry(name);
            if (jarEntry != null) {
                String path = "jar:file:" + extensionJar.getName() + "!/" + jarEntry.getName();
                try {
                    return new URL(path);
                } catch (MalformedURLException ex) {
                    System.out.println(path + "\n" + ex.toString());
                }
            }
        }
    }

    return super.findResource(name);
}

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

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;
    Manifest manifest;//from  w ww .  ja  va  2s.c  o m
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}