Example usage for java.util.jar JarFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

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

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.//from w  w w .ja  v a2  s.co  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:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlSourceArchive() throws IOException {
    File sourceArchiveFile = getSourceArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single",
            "6.6.6");
    sourceArchiveFile.delete();//from   w ww . jav  a  2  s  .c om
    assertFalse(sourceArchiveFile.exists());

    // compile one file
    compile("modules/single/module.ceylon");

    // make sure it was created
    assertTrue(sourceArchiveFile.exists());

    JarFile sourceArchive = new JarFile(sourceArchiveFile);
    assertEquals(2, countEntries(sourceArchive));

    ZipEntry moduleClass = sourceArchive
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/module.ceylon");
    assertNotNull(moduleClass);

    ZipEntry moduleClassDir = sourceArchive
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/");
    assertNotNull(moduleClassDir);
    sourceArchive.close();

    // now compile another file
    compile("modules/single/subpackage/Subpackage.ceylon");

    // MUST reopen it
    sourceArchive = new JarFile(sourceArchiveFile);
    assertEquals(4, countEntries(sourceArchive));

    ZipEntry subpackageClass = sourceArchive
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/Subpackage.ceylon");
    assertNotNull(subpackageClass);
    ZipEntry subpackageClassDir = sourceArchive
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/");
    assertNotNull(subpackageClassDir);

    sourceArchive.close();
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

/**
 * Checks if a jar file is a MidletJar created by rapc.
 *
 * @param f//w w w .ja  va  2 s.co  m
 * @return
 */
static public int getJarFileType(File f) {
    int type = 0x0;
    if (!f.exists()) {
        return type;
    }
    java.util.jar.JarFile jar = null;
    try {
        jar = new java.util.jar.JarFile(f, false);
        java.util.jar.Manifest manifest = jar.getManifest();
        if (manifest != null) {
            java.util.jar.Attributes attributes = manifest.getMainAttributes();
            String profile = attributes.getValue("MicroEdition-Profile");
            if (profile != null) {
                if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) {
                    type = type | MIDLET_JAR;
                }
            }
        }
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        String entryName;
        InputStream is = null;
        IClassFileReader classFileReader = null;
        // check the attribute of the class files in the jar file
        for (; entries.hasMoreElements();) {
            entry = entries.nextElement();
            entryName = entry.getName();
            if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) {
                is = jar.getInputStream(entry);
                classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL);
                if (isEvisceratedClass(classFileReader)) {
                    type = type | EVISCERATED_JAR;
                    break;
                }
            }
        }
    } catch (IOException e) {
        _log.error(e.getMessage());
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
    }
    return type;
}

From source file:goja.initialize.ctxbox.ClassSearcher.java

/**
 * jarclass/*from   w w w . jav a  2  s.co m*/
 */
private List<String> findjarFiles(String baseDirName) {
    List<String> classFiles = Lists.newArrayList();
    File baseDir = new File(baseDirName);
    if (!baseDir.exists() || !baseDir.isDirectory()) {
        LOG.error("file search error:" + baseDirName + " is not a dir?");
    } else {
        File[] files = baseDir.listFiles();
        if (files == null) {
            return Collections.EMPTY_LIST;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                classFiles.addAll(findjarFiles(file.getAbsolutePath()));
            } else {
                if (includeAllJarsInLib || includeJars.contains(file.getName())) {
                    JarFile localJarFile = null;
                    try {
                        localJarFile = new JarFile(new File(baseDirName + File.separator + file.getName()));
                        Enumeration<JarEntry> entries = localJarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry = entries.nextElement();
                            String entryName = jarEntry.getName();
                            if (scanPackages.isEmpty()) {
                                if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {
                                    String className = StringUtils.replace(entryName, StringPool.SLASH, ".")
                                            .substring(0, entryName.length() - 6);
                                    classFiles.add(className);
                                }
                            } else {
                                for (String scanPackage : scanPackages) {
                                    scanPackage = scanPackage.replaceAll("\\.", "\\" + File.separator);
                                    if (!jarEntry.isDirectory() && entryName.endsWith(".class")
                                            && entryName.startsWith(scanPackage)) {
                                        String className = StringUtils.replace(entryName, File.separator, ".")
                                                .substring(0, entryName.length() - 6);
                                        classFiles.add(className);
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (localJarFile != null) {
                                localJarFile.close();
                            }
                        } catch (IOException e) {
                            LOG.error("close jar file has error!", e);
                        }
                    }
                }
            }

        }
    }
    return classFiles;
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlCompilerGeneratesModuleForValidUnits() throws IOException {
    CeyloncTaskImpl compilerTask = getCompilerTask("modules/single/module.ceylon",
            "modules/single/Correct.ceylon", "modules/single/Invalid.ceylon");
    Boolean success = compilerTask.call();
    assertFalse(success);// w w  w.  j a va2s  .  c  o m

    File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6");
    assertTrue(carFile.exists());

    JarFile car = new JarFile(carFile);

    ZipEntry moduleClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class");
    assertNotNull(moduleClass);

    ZipEntry correctClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/Correct.class");
    assertNotNull(correctClass);

    ZipEntry invalidClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/Invalid.class");
    assertNull(invalidClass);

    car.close();
}

From source file:org.batfish.common.plugin.PluginConsumer.java

private void loadPluginJar(Path path) {
    /*/*  w  ww . j av a  2  s. c om*/
     * Adapted from
     * http://stackoverflow.com/questions/11016092/how-to-load-classes-at-
     * runtime-from-a-folder-or-jar Retrieved: 2016-08-31 Original Authors:
     * Kevin Crain http://stackoverflow.com/users/2688755/kevin-crain
     * Apfelsaft http://stackoverflow.com/users/1447641/apfelsaft License:
     * https://creativecommons.org/licenses/by-sa/3.0/
     */
    String pathString = path.toString();
    if (pathString.endsWith(".jar")) {
        try {
            URL[] urls = { new URL("jar:file:" + pathString + "!/") };
            URLClassLoader cl = URLClassLoader.newInstance(urls, _currentClassLoader);
            _currentClassLoader = cl;
            Thread.currentThread().setContextClassLoader(cl);
            JarFile jar = new JarFile(path.toFile());
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry element = entries.nextElement();
                String name = element.getName();
                if (element.isDirectory() || !name.endsWith(CLASS_EXTENSION)) {
                    continue;
                }
                String className = name.substring(0, name.length() - CLASS_EXTENSION.length()).replace("/",
                        ".");
                try {
                    cl.loadClass(className);
                    Class<?> pluginClass = Class.forName(className, true, cl);
                    if (!Plugin.class.isAssignableFrom(pluginClass)
                            || Modifier.isAbstract(pluginClass.getModifiers())) {
                        continue;
                    }
                    Constructor<?> pluginConstructor;
                    try {
                        pluginConstructor = pluginClass.getConstructor();
                    } catch (NoSuchMethodException | SecurityException e) {
                        throw new BatfishException(
                                "Could not find default constructor in plugin: '" + className + "'", e);
                    }
                    Object pluginObj;
                    try {
                        pluginObj = pluginConstructor.newInstance();
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        throw new BatfishException(
                                "Could not instantiate plugin '" + className + "' from constructor", e);
                    }
                    Plugin plugin = (Plugin) pluginObj;
                    plugin.initialize(this);

                } catch (ClassNotFoundException e) {
                    jar.close();
                    throw new BatfishException("Unexpected error loading classes from jar", e);
                }
            }
            jar.close();
        } catch (IOException e) {
            throw new BatfishException("Error loading plugin jar: '" + path.toString() + "'", e);
        }
    }
}

From source file:org.openmrs.module.ModuleUtil.java

/**
 * Expand the given <code>fileToExpand</code> jar to the <code>tmpModuleFile</code> directory
 *
 * If <code>name</code> is null, the entire jar is expanded. If<code>name</code> is not null,
 * then only that path/file is expanded.
 *
 * @param fileToExpand file pointing at a .jar
 * @param tmpModuleDir directory in which to place the files
 * @param name filename inside of the jar to look for and expand
 * @param keepFullPath if true, will recreate entire directory structure in tmpModuleDir
 *            relating to <code>name</code>. if false will start directory structure at
 *            <code>name</code>
 *///from w ww . j a v  a 2 s.  co m
public static void expandJar(File fileToExpand, File tmpModuleDir, String name, boolean keepFullPath)
        throws IOException {
    JarFile jarFile = null;
    InputStream input = null;
    String docBase = tmpModuleDir.getAbsolutePath();
    try {
        jarFile = new JarFile(fileToExpand);
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        boolean foundName = (name == null);

        // loop over all of the elements looking for the match to 'name'
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (name == null || jarEntry.getName().startsWith(name)) {
                String entryName = jarEntry.getName();
                // trim out the name path from the name of the new file
                if (!keepFullPath && name != null) {
                    entryName = entryName.replaceFirst(name, "");
                }

                // if it has a slash, it's in a directory
                int last = entryName.lastIndexOf('/');
                if (last >= 0) {
                    File parent = new File(docBase, entryName.substring(0, last));
                    parent.mkdirs();
                    log.debug("Creating parent dirs: " + parent.getAbsolutePath());
                }
                // we don't want to "expand" directories or empty names
                if (entryName.endsWith("/") || "".equals(entryName)) {
                    continue;
                }
                input = jarFile.getInputStream(jarEntry);
                expand(input, docBase, entryName);
                input.close();
                input = null;
                foundName = true;
            }
        }
        if (!foundName) {
            log.debug("Unable to find: " + name + " in file " + fileToExpand.getAbsolutePath());
        }

    } catch (IOException e) {
        log.warn("Unable to delete tmpModuleFile on error", e);
        throw e;
    } finally {
        try {
            input.close();
        } catch (Exception e) {
            /* pass */}
        try {
            jarFile.close();
        } catch (Exception e) {
            /* pass */}
    }
}

From source file:de.knurt.fam.plugin.DefaultPluginResolver.java

private void initPlugins() {
    File pluginDirectory = new File(FamConnector.me().getPluginDirectory());
    if (pluginDirectory.exists() && pluginDirectory.isDirectory() && pluginDirectory.canRead()) {
        File[] files = pluginDirectory.listFiles();
        ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
        for (File file : files) {
            if (file.isFile() && file.getName().toLowerCase().endsWith("jar")) {
                JarFile jar = null;
                try {
                    jar = new JarFile(file.getAbsoluteFile().toString());
                    Enumeration<JarEntry> jarEntries = jar.entries();
                    while (jarEntries.hasMoreElements()) {
                        JarEntry entry = jarEntries.nextElement();
                        if (entry.getName().toLowerCase().endsWith("class")) {
                            String className = entry.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                            // @SuppressWarnings("resource") // classLoader must not be closed, getting an "IllegalStateException: zip file closed" otherwise
                            URLClassLoader classLoader = new URLClassLoader(new URL[] { file.toURI().toURL() },
                                    currentThreadClassLoader);
                            Class<?> cl = classLoader.loadClass(className);
                            if (this.isPlugin(cl)) {
                                Plugin plugin = (Plugin) cl.newInstance();
                                this.plugins.add(plugin);
                            }//from w ww. ja  va  2 s.c o m
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091426l);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091424l);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091425l);
                } catch (IOException e) {
                    e.printStackTrace();
                    FamLog.logException(this.getClass(), e, "failed to load plugin", 201010091351l);
                } finally {
                    try {
                        jar.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        for (Plugin plugin : this.plugins) {
            boolean found = false;
            if (this.implementz(plugin.getClass(), RegisterSubmission.class)) {
                if (found == true) {
                    throw new PluginConfigurationException("Found more than one RegisterSubmission classes");
                    // TODO #19 supply a solution Ticket
                }
                this.registerSubmission = (RegisterSubmission) plugin;
                found = true;
            }
        }
        for (Plugin plugin : this.plugins) {
            plugin.start();
        }
    }
    // search plugin
    if (this.registerSubmission == null) {
        this.registerSubmission = new DefaultRegisterSubmission();
    }
}

From source file:com.icesoft.jasper.compiler.TldLocationsCache.java

/**
 * Scans the given JarURLConnection for TLD files located in META-INF (or a
 * subdirectory of it), adding an implicit map entry to the taglib map for
 * any TLD that has a <uri> element.
 *
 * @param conn   The JarURLConnection to the JAR file to scan
 * @param ignore true if any exceptions raised when processing the given JAR
 *               should be ignored, false otherwise
 *//* ww w.j av  a  2 s.  c  o m*/
private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException {

    JarFile jarFile = null;
    String resourcePath = conn.getJarFileURL().toString();
    try {
        if (redeployMode) {
            conn.setUseCaches(false);
        }
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith("META-INF/"))
                continue;
            if (!name.endsWith(".tld"))
                continue;
            InputStream stream = jarFile.getInputStream(entry);
            try {
                String uri = getUriFromTld(resourcePath, stream);
                // Add implicit map entry only if its uri is not already
                // present in the map
                if (uri != null && mappings.get(uri) == null) {
                    mappings.put(uri, new String[] { resourcePath, name });
                }
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        if (log.isDebugEnabled()) {
            log.debug(ex.getMessage(), ex);
        }
        if (!redeployMode) {
            // if not in redeploy mode, close the jar in case of an error
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (!ignore) {
            throw new JasperException(ex);
        }
    } finally {
        if (redeployMode) {
            // if in redeploy mode, always close the jar
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
}

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Deploy WAR files.//from   w  ww .jav a2  s . c o m
 */
protected void deployWARs(File appBase, String[] files) {

    for (int i = 0; i < files.length; i++) {

        if (files[i].equalsIgnoreCase("META-INF"))
            continue;
        if (files[i].equalsIgnoreCase("WEB-INF"))
            continue;
        if (deployed.contains(files[i]))
            continue;
        File dir = new File(appBase, files[i]);
        if (files[i].toLowerCase().endsWith(".war")) {

            deployed.add(files[i]);

            // Calculate the context path and make sure it is unique
            String contextPath = "/" + files[i];
            int period = contextPath.lastIndexOf(".");
            if (period >= 0)
                contextPath = contextPath.substring(0, period);
            if (contextPath.equals("/ROOT"))
                contextPath = "";
            if (host.findChild(contextPath) != null)
                continue;

            // Checking for a nested /META-INF/context.xml
            JarFile jar = null;
            JarEntry entry = null;
            InputStream istream = null;
            BufferedOutputStream ostream = null;
            File xml = new File(configBase, files[i].substring(0, files[i].lastIndexOf(".")) + ".xml");
            if (!xml.exists()) {
                try {
                    jar = new JarFile(dir);
                    entry = jar.getJarEntry("META-INF/context.xml");
                    if (entry != null) {
                        istream = jar.getInputStream(entry);
                        ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024);
                        byte buffer[] = new byte[1024];
                        while (true) {
                            int n = istream.read(buffer);
                            if (n < 0) {
                                break;
                            }
                            ostream.write(buffer, 0, n);
                        }
                        ostream.flush();
                        ostream.close();
                        ostream = null;
                        istream.close();
                        istream = null;
                        entry = null;
                        jar.close();
                        jar = null;
                        deployDescriptors(configBase(), configBase.list());
                        return;
                    }
                } catch (Exception e) {
                    // Ignore and continue
                    if (ostream != null) {
                        try {
                            ostream.close();
                        } catch (Throwable t) {
                            ;
                        }
                        ostream = null;
                    }
                    if (istream != null) {
                        try {
                            istream.close();
                        } catch (Throwable t) {
                            ;
                        }
                        istream = null;
                    }
                    entry = null;
                    if (jar != null) {
                        try {
                            jar.close();
                        } catch (Throwable t) {
                            ;
                        }
                        jar = null;
                    }
                }
            }

            if (isUnpackWARs()) {

                // Expand and deploy this application as a directory
                log.debug(sm.getString("hostConfig.expand", files[i]));
                URL url = null;
                String path = null;
                try {
                    url = new URL("jar:file:" + dir.getCanonicalPath() + "!/");
                    path = ExpandWar.expand(host, url);
                } catch (IOException e) {
                    // JAR decompression failure
                    log.warn(sm.getString("hostConfig.expand.error", files[i]));
                    continue;
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.expand.error", files[i]), t);
                    continue;
                }
                try {
                    if (path != null) {
                        url = new URL("file:" + path);
                        ((Deployer) host).install(contextPath, url);
                    }
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.expand.error", files[i]), t);
                }

            } else {

                // Deploy the application in this WAR file
                log.info(sm.getString("hostConfig.deployJar", files[i]));
                try {
                    URL url = new URL("file", null, dir.getCanonicalPath());
                    url = new URL("jar:" + url.toString() + "!/");
                    ((Deployer) host).install(contextPath, url);
                } catch (Throwable t) {
                    log.error(sm.getString("hostConfig.deployJar.error", files[i]), t);
                }

            }

        }

    }

}