Example usage for java.util.jar JarFile getInputStream

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

Introduction

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

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;//  w  w w  . j a  va  2  s. com
    if (outputFileUri == null) {
        throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. ");
    }
    outputFolder = new File(outputFileUri.path());
    if (!outputFolder.exists()) {
        if (!outputFolder.mkdirs()) {
            throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath());
        }
    }

    File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT);
    if (!cssFolderOut.exists()) {
        if (!cssFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath());
        }
    }

    File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT);
    if (!jsFolderOut.exists()) {
        if (!jsFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath());
        }
    }

    File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT);
    if (!imgFolderOut.exists()) {
        if (!imgFolderOut.mkdirs()) {
            throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath());
        }
    }

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE),
            outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE);

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE);

    copyResourceFile(
            getClass()
                    .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE);

    ClassLoader classLoader = getClass().getClassLoader();
    CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource();
    URL codeSourceUrl = srcCode.getLocation();
    File codeSourseFile = new File(codeSourceUrl.getPath());

    if (codeSourseFile.isDirectory()) {
        File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile());
        File[] imgFiles = imgFolder.listFiles();
        if (imgFiles != null) {
            for (File imgFile : imgFiles) {
                InputStream inputStream = getClass()
                        .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK
                                + System.getProperty("file.separator") + imgFile.getName());
                copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName());
            }
        }
    } else if (codeSourseFile.getName().endsWith("jar")) {
        JarFile jarFile = new JarFile(codeSourseFile);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) {

                copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT,
                        entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, ""));
            }

        }
        jarFile.close();

    }

    return outputFolder;
}

From source file:org.jenkins.tools.test.PluginCompatTester.java

/**
 * Scans through a WAR file, accumulating plugin information
 * @param war WAR to scan/*from www  . j  a  va 2s .com*/
 * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION
 * @return Update center data
 * @throws IOException
 */
private UpdateSite.Data scanWAR(File war, Map<String, String> pluginGroupIds) throws IOException {
    JSONObject top = new JSONObject();
    top.put("id", DEFAULT_SOURCE_ID);
    JSONObject plugins = new JSONObject();
    JarFile jf = new JarFile(war);
    if (pluginGroupIds == null) {
        pluginGroupIds = new HashMap<String, String>();
    }
    try {
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            Matcher m = Pattern.compile("WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9.]+)?(?:-SNAPSHOT)?)[.]jar")
                    .matcher(name);
            if (m.matches()) {
                if (top.has("core")) {
                    throw new IOException(">1 jenkins-core.jar in " + war);
                }
                top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1))
                        .accumulate("url", ""));
            }
            m = Pattern.compile("WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi").matcher(name);
            if (m.matches()) {
                JSONObject plugin = new JSONObject().accumulate("url", "");
                InputStream is = jf.getInputStream(entry);
                try {
                    JarInputStream jis = new JarInputStream(is);
                    try {
                        Manifest manifest = jis.getManifest();
                        String shortName = manifest.getMainAttributes().getValue("Short-Name");
                        if (shortName == null) {
                            shortName = manifest.getMainAttributes().getValue("Extension-Name");
                            if (shortName == null) {
                                shortName = m.group(1);
                            }
                        }
                        plugin.put("name", shortName);
                        pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id"));
                        plugin.put("version", manifest.getMainAttributes().getValue("Plugin-Version"));
                        plugin.put("url", "jar:" + war.toURI() + "!/" + name);
                        JSONArray dependenciesA = new JSONArray();
                        String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies");
                        if (dependencies != null) {
                            // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional
                            for (String pair : dependencies.replace(";resolution:=optional", "").split(",")) {
                                String[] nameVer = pair.split(":");
                                assert nameVer.length == 2;
                                dependenciesA.add(new JSONObject().accumulate("name", nameVer[0])
                                        .accumulate("version", nameVer[1])
                                        ./* we do care about even optional deps here */accumulate("optional",
                                                "false"));
                            }
                        }
                        plugin.accumulate("dependencies", dependenciesA);
                        plugins.put(shortName, plugin);
                    } finally {
                        jis.close();
                    }
                } finally {
                    is.close();
                }
            }
        }
    } finally {
        jf.close();
    }
    top.put("plugins", plugins);
    if (!top.has("core")) {
        throw new IOException("no jenkins-core.jar in " + war);
    }
    System.out.println("Scanned contents of " + war + ": " + top);
    return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top);
}

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  w w  .j  a va  2s  . c om
        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:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    JarFile jarFile = null;
    try {/*w w  w  .  j a va 2s.  c  o m*/
        jarFile = new JarFile(archiveFile);

        final Manifest manifest = jarFile.getManifest();
        assertNotNull("Manifest should be present", manifest);
        assertEquals("Manifest version should be 1.0", "1.0",
                manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION));

        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            final JarEntry jarEntry = entries.nextElement();
            if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) {
                // It is the manifest file, not added by use
                continue;
            }
            if (jarEntry.isDirectory()) {
                assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.dirs.contains(jarEntry.getName()));
                archiveEntries.dirs.remove(jarEntry.getName());
            } else {
                assertTrue("File in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.files.containsKey(jarEntry.getName()));
                final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false);
                assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]",
                        archiveEntries.files.get(jarEntry.getName()), inflatedMd5);
                archiveEntries.files.remove(jarEntry.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the jar", archiveEntries.files.isEmpty());
    } finally {
        if (null != jarFile) {
            jarFile.close();
        }
    }
}

From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java

private void readVersionInformation() {
    InputStream stream = null;//w ww .  ja  va 2  s  .  c  o  m
    try {
        JarFile tgfmJar = null;
        URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation")
                .getResource("ConfigOperation.class");
        JarURLConnection c = (JarURLConnection) jarname.openConnection();
        tgfmJar = c.getJarFile();
        stream = tgfmJar.getInputStream(tgfmJar.getEntry("META-INF/MANIFEST.MF"));
        Manifest manifest = new Manifest(stream);
        Attributes attributes = manifest.getMainAttributes();
        for (Object attributeName : attributes.keySet()) {
            if (((Attributes.Name) attributeName).toString().equals(("Implementation-Version"))) {
                ConfigSettings.SOFTWARE_VERSION = attributes.getValue("Implementation-Version");
            } else if (((Attributes.Name) attributeName).toString().equals(("Built-Date"))) {
                ConfigSettings.SOFTWARE_BUILD_DATE = attributes.getValue("Built-Date");
            }

            LogManager
                    .debug(attributeName + ": " + attributes.getValue((Attributes.Name) attributeName) + "\n");
        }

        stream.close();
    } catch (Exception e) {
        LogManager.error("Failed to retreive version information.", e);
    } finally {
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.slamd.admin.JobPack.java

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server./*ww w .j  a  v a2  s.  c o m*/
 *
 * @throws  SLAMDServerException  If a problem occurs while processing the job
 *                                pack JAR file.
 */
public void processJobPack() throws SLAMDServerException {
    byte[] fileData = null;
    File tempFile = null;
    String fileName = null;
    String separator = System.getProperty("file.separator");

    if (filePath == null) {
        // First, get the request and ensure it is multipart content.
        HttpServletRequest request = requestInfo.request;
        if (!FileUpload.isMultipartContent(request)) {
            throw new SLAMDServerException("Request does not contain multipart " + "content");
        }

        // Iterate through the request fields to get to the file data.
        Iterator iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) {
                fileData = fileItem.get();
                fileName = fileItem.getName();
            }
        }

        // Make sure that a file was actually uploaded.
        if (fileData == null) {
            throw new SLAMDServerException("No file data was found in the " + "request.");
        }

        // Write the JAR file data to a temp file, since that's the only way we
        // can parse it.
        if (separator == null) {
            separator = "/";
        }

        tempFile = new File(jobClassDirectory + separator + fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(fileData);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ioe) {
            try {
                tempFile.delete();
            } catch (Exception e) {
            }

            ioe.printStackTrace();
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
            throw new SLAMDServerException("I/O error writing temporary JAR " + "file:  " + ioe, ioe);
        }
    } else {
        tempFile = new File(filePath);
        if ((!tempFile.exists()) || (!tempFile.isFile())) {
            throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist");
        }

        try {
            fileName = tempFile.getName();
            int fileLength = (int) tempFile.length();
            fileData = new byte[fileLength];

            FileInputStream inputStream = new FileInputStream(tempFile);
            int bytesRead = 0;
            while (bytesRead < fileLength) {
                bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
            throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e);
        }
    }

    StringBuilder htmlBody = requestInfo.htmlBody;

    // Parse the jar file
    JarFile jarFile = null;
    Manifest manifest = null;
    Enumeration jarEntries = null;
    try {
        jarFile = new JarFile(tempFile, true);
        manifest = jarFile.getManifest();
        jarEntries = jarFile.entries();
    } catch (IOException ioe) {
        try {
            if (filePath == null) {
                tempFile.delete();
            }
        } catch (Exception e) {
        }

        ioe.printStackTrace();
        slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
        throw new SLAMDServerException("Unable to parse the JAR file:  " + ioe, ioe);
    }

    ArrayList<String> dirList = new ArrayList<String>();
    ArrayList<String> fileNameList = new ArrayList<String>();
    ArrayList<byte[]> fileDataList = new ArrayList<byte[]>();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        String entryName = jarEntry.getName();
        if (jarEntry.isDirectory()) {
            dirList.add(entryName);
        } else {
            try {
                int entrySize = (int) jarEntry.getSize();
                byte[] entryData = new byte[entrySize];
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                extractFileData(inputStream, entryData);
                fileNameList.add(entryName);
                fileDataList.add(entryData);
            } catch (IOException ioe) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe);
            } catch (SLAMDServerException sse) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                sse.printStackTrace();
                throw sse;
            }
        }
    }

    // If we have gotten here, then we have read all the data from the JAR file.
    // Delete the temporary file to prevent possible (although unlikely)
    // conflicts with data contained in the JAR.
    try {
        jarFile.close();
        if (filePath == null) {
            tempFile.delete();
        }
    } catch (Exception e) {
    }

    // Create the directory structure specified in the JAR file.
    if (!dirList.isEmpty()) {
        htmlBody.append("<B>Created the following directories</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < dirList.size(); i++) {
            File dirFile = new File(jobClassDirectory + separator + dirList.get(i));
            try {
                dirFile.mkdirs();
                htmlBody.append("  <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (Exception e) {
                htmlBody.append("</UL>" + Constants.EOL);
                e.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
                throw new SLAMDServerException(
                        "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Write all the files to disk.  If we have gotten this far, then there
    // should not be any failures, but if there are, then we will have to
    // leave things in a "dirty" state.
    if (!fileNameList.isEmpty()) {
        htmlBody.append("<B>Created the following files</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < fileNameList.size(); i++) {
            File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i));

            try {
                // Make sure the parent directory exists.
                dataFile.getParentFile().mkdirs();
            } catch (Exception e) {
            }

            try {
                FileOutputStream outputStream = new FileOutputStream(dataFile);
                outputStream.write(fileDataList.get(i));
                outputStream.flush();
                outputStream.close();
                htmlBody.append("  <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (IOException ioe) {
                htmlBody.append("</UL>" + Constants.EOL);
                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Finally, parse the manifest to get the names of the classes that should
    // be registered with the SLAMD server.
    Attributes manifestAttributes = manifest.getMainAttributes();
    Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR);
    String registerClassesStr = (String) manifestAttributes.get(key);
    if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) {
        htmlBody.append("<B>No job classes registered</B>" + Constants.EOL);
    } else {
        ArrayList<String> successList = new ArrayList<String>();
        ArrayList<String> failureList = new ArrayList<String>();

        StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n");
        while (tokenizer.hasMoreTokens()) {
            String className = tokenizer.nextToken();

            try {
                JobClass jobClass = slamdServer.loadJobClass(className);
                slamdServer.addJobClass(jobClass);
                successList.add(className);
            } catch (Exception e) {
                failureList.add(className + ":  " + e);
            }
        }

        if (!successList.isEmpty()) {
            htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < successList.size(); i++) {
                htmlBody.append("  <LI>" + successList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }

        if (!failureList.isEmpty()) {
            htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < failureList.size(); i++) {
                htmlBody.append("  <LI>" + failureList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }
    }
}

From source file:org.mule.util.FileUtils.java

/**
 * Extract recources contain if jar (have to in classpath)
 *
 * @param connection          JarURLConnection to jar library
 * @param outputDir           Directory for unpack recources
 * @param keepParentDirectory true -  full structure of directories is kept; false - file - removed all directories, directory - started from resource point
 * @throws IOException if any error/*w w w.j ava  2s .  c  om*/
 */
private static void extractJarResources(JarURLConnection connection, File outputDir,
        boolean keepParentDirectory) throws IOException {
    JarFile jarFile = connection.getJarFile();
    JarEntry jarResource = connection.getJarEntry();
    Enumeration entries = jarFile.entries();
    InputStream inputStream = null;
    OutputStream outputStream = null;
    int jarResourceNameLenght = jarResource.getName().length();
    for (; entries.hasMoreElements();) {
        JarEntry entry = (JarEntry) entries.nextElement();
        if (entry.getName().startsWith(jarResource.getName())) {

            String path = outputDir.getPath() + File.separator + entry.getName();

            //remove directory struct for file and first dir for directory
            if (!keepParentDirectory) {
                if (entry.isDirectory()) {
                    if (entry.getName().equals(jarResource.getName())) {
                        continue;
                    }
                    path = outputDir.getPath() + File.separator
                            + entry.getName().substring(jarResourceNameLenght, entry.getName().length());
                } else {
                    if (entry.getName().length() > jarResourceNameLenght) {
                        path = outputDir.getPath() + File.separator
                                + entry.getName().substring(jarResourceNameLenght, entry.getName().length());
                    } else {
                        path = outputDir.getPath() + File.separator + entry.getName()
                                .substring(entry.getName().lastIndexOf("/"), entry.getName().length());
                    }
                }
            }

            File file = FileUtils.newFile(path);
            if (!file.getParentFile().exists()) {
                if (!file.getParentFile().mkdirs()) {
                    throw new IOException("Could not create directory: " + file.getParentFile());
                }
            }
            if (entry.isDirectory()) {
                if (!file.exists() && !file.mkdirs()) {
                    throw new IOException("Could not create directory: " + file);
                }

            } else {
                try {
                    inputStream = jarFile.getInputStream(entry);
                    outputStream = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }

        }
    }
}

From source file:catalina.startup.ContextConfig.java

/**
 * Scan the JAR file at the specified resource path for TLDs in the
 * <code>META-INF</code> subdirectory, and scan them for application
 * event listeners that need to be registered.
 *
 * @param resourcePath Resource path of the JAR file to scan
 *
 * @exception Exception if an exception occurs while scanning this JAR
 *//*from   www  .  j ava 2s.  co m*/
private void tldScanJar(String resourcePath) throws Exception {

    if (debug >= 1) {
        log(" Scanning JAR at resource path '" + resourcePath + "'");
    }

    JarFile jarFile = null;
    String name = null;
    InputStream inputStream = null;
    try {
        URL url = context.getServletContext().getResource(resourcePath);
        if (url == null) {
            throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath));
        }
        url = new URL("jar:" + url.toString() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        conn.setUseCaches(false);
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            if (debug >= 2) {
                log("  Processing TLD at '" + name + "'");
            }
            inputStream = jarFile.getInputStream(entry);
            tldScanStream(inputStream);
            inputStream.close();
            inputStream = null;
            name = null;
        }
        // FIXME - Closing the JAR file messes up the class loader???
        //            jarFile.close();
    } catch (Exception e) {
        if (name == null) {
            throw new ServletException(sm.getString("contextConfig.tldJarException", resourcePath), e);
        } else {
            throw new ServletException(sm.getString("contextConfig.tldEntryException", name, resourcePath), e);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                ;
            }
            inputStream = null;
        }
        if (jarFile != null) {
            // FIXME - Closing the JAR file messes up the class loader???
            //                try {
            //                    jarFile.close();
            //                } catch (Throwable t) {
            //                    ;
            //                }
            jarFile = null;
        }
    }

}

From source file:org.apache.jasper.compiler.TagLibraryInfoImpl.java

/**
 * Constructor.//from ww  w.  j  av  a2s. c  om
 */
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn,
        String[] location, ErrorDispatcher err) throws JasperException {
    super(prefix, uriIn);

    this.ctxt = ctxt;
    this.parserController = pc;
    this.err = err;
    InputStream in = null;
    JarFile jarFile = null;

    if (location == null) {
        // The URI points to the TLD itself or to a JAR file in which the
        // TLD is stored
        location = generateTLDLocation(uri, ctxt);
    }

    try {
        if (!location[0].endsWith("jar")) {
            // Location points to TLD file
            try {
                in = getResourceAsStream(location[0]);
                if (in == null) {
                    throw new FileNotFoundException(location[0]);
                }
            } catch (FileNotFoundException ex) {
                err.jspError("jsp.error.file.not.found", location[0]);
            }

            parseTLD(ctxt, location[0], in, null);
            // Add TLD to dependency list
            PageInfo pageInfo = ctxt.createCompiler().getPageInfo();
            if (pageInfo != null) {
                pageInfo.addDependant(location[0]);
            }
        } else {
            // Tag library is packaged in JAR file
            try {
                URL jarFileUrl = new URL("jar:" + location[0] + "!/");
                JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
                conn.setUseCaches(false);
                conn.connect();
                jarFile = conn.getJarFile();
                ZipEntry jarEntry = jarFile.getEntry(location[1]);
                in = jarFile.getInputStream(jarEntry);
                parseTLD(ctxt, location[0], in, jarFileUrl);
            } catch (Exception ex) {
                err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString());
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
            }
        }
    }

}

From source file:org.tinygroup.jspengine.compiler.TagLibraryInfoImpl.java

/**
 * Constructor which builds a TagLibraryInfoImpl by parsing a TLD.
 *///from  w ww .  j a  va  2s  .c o m
public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn,
        String[] location, ErrorDispatcher err) throws JasperException {
    super(prefix, uriIn);

    this.ctxt = ctxt;
    this.parserController = pc;
    this.pageInfo = pc.getCompiler().getPageInfo();
    this.err = err;
    InputStream in = null;
    JarFile jarFile = null;

    if (location == null) {
        // The URI points to the TLD itself or to a JAR file in which the
        // TLD is stored
        location = generateTLDLocation(uri, ctxt);
    }

    try {
        if (!location[0].endsWith("jar")) {
            // Location points to TLD file
            try {
                in = getResourceAsStream(location[0]);
                if (in == null) {
                    throw new FileNotFoundException(location[0]);
                }
            } catch (FileNotFoundException ex) {
                err.jspError("jsp.error.file.not.found", location[0]);
            }
            parseTLD(ctxt, location[0], in, null);
            // Add TLD to dependency list
            PageInfo pageInfo = ctxt.createCompiler(false).getPageInfo();
            if (pageInfo != null) {
                pageInfo.addDependant(location[0]);
            }
        } else {
            // Tag library is packaged in JAR file
            try {
                URL jarFileUrl = new URL("jar:" + location[0] + "!/");
                JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection();
                conn.setUseCaches(false);
                conn.connect();
                jarFile = conn.getJarFile();
                ZipEntry jarEntry = jarFile.getEntry(location[1]);
                in = jarFile.getInputStream(jarEntry);
                parseTLD(ctxt, location[0], in, jarFileUrl);
            } catch (Exception ex) {
                err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString());
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable t) {
            }
        }
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (Throwable t) {
            }
        }
    }

}