Example usage for java.util.zip ZipFile entries

List of usage examples for java.util.zip ZipFile entries

Introduction

In this page you can find the example usage for java.util.zip ZipFile entries.

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java

private void renameHocrFiles(final File oldXmlFile, final String newBatchInstanceIdentfier,
        final String oldBatchInstanceIdentifier) {

    LOGGER.info("Retrived list of zip files from " + oldXmlFile.getAbsolutePath());

    String finalZipPath = oldXmlFile.getAbsolutePath();
    File finalZipFile = new File(finalZipPath);

    String destDirectory = finalZipFile.getParent();
    String unzippedFilePath = finalZipFile.getAbsolutePath();
    LOGGER.info("Unziping the " + unzippedFilePath + CONSTANT_TO + destDirectory);

    FileUtils.unzip(finalZipFile, destDirectory);
    ZipFile zipFile = null;
    try {//from w  ww . j  a va2  s . com
        zipFile = new ZipFile(finalZipFile);

        // Only 1st entry picked. Considering that our zip file contains only a single file.
        String xmlFileName = zipFile.entries().nextElement().getName();

        StringBuilder xmlFileNameBuilder = new StringBuilder();
        xmlFileNameBuilder.append(destDirectory);
        xmlFileNameBuilder.append(File.separator);
        xmlFileNameBuilder.append(xmlFileName);
        String xmlFilePath = xmlFileNameBuilder.toString();
        File xmlFile = new File(xmlFilePath);

        xmlFileName = xmlFileName.replaceAll(oldBatchInstanceIdentifier, newBatchInstanceIdentfier);
        StringBuilder newXmlFileNameBuilder = new StringBuilder();
        newXmlFileNameBuilder.append(destDirectory);
        newXmlFileNameBuilder.append(File.separator);
        newXmlFileNameBuilder.append(xmlFileName);
        String newXmlFilePath = newXmlFileNameBuilder.toString();
        File newXmlFile = new File(newXmlFilePath);

        LOGGER.info("Renaming " + unzippedFilePath + CONSTANT_TO + xmlFileName);

        xmlFile.renameTo(newXmlFile);

        List<String> fileNames = new ArrayList<String>();
        fileNames.add(newXmlFile.getAbsolutePath());

        LOGGER.info("Zipping the altered files to " + finalZipPath);

        FileUtils.zipMultipleFiles(fileNames, finalZipPath);
        newXmlFile.delete();
    } catch (ZipException e) {
        LOGGER.error("Error Creating zip file " + e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error("I/O Error while Creating zip file " + e.getMessage(), e);
    }

}

From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Retrieve the content of a result feed URL.
 * //from   ww w  . j  a  v  a 2s  . co  m
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @param resultHeaders
 * @return Reader
 */
private Reader getContent(final URI uri, final String encodingOverride, final String userAgent,
        final Map<String, String> resultHeaders) {
    Reader result = null;
    String contentType = null;

    // Retrieve the feed

    try {
        InputStream inputStream = null;

        if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) {
            FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

            try {
                ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

                if (StringUtils.hasText(uri.getUserInfo())) {
                    if (uri.getUserInfo().contains(":"))
                        ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                                uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
                    else
                        ftpClient.login(uri.getUserInfo(), "");

                    inputStream = ftpClient.retrieveFileStream(uri.getPath());
                }
            } finally {
                ftpClient.disconnect();
            }
        } else if (uri.getScheme().equalsIgnoreCase("file")) {
            File file = new File(uri);

            if (!file.isDirectory())
                inputStream = new FileInputStream(uri.getPath());
            else
                inputStream = RSSDirectoryBuilder.build(file);
        } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
            try {
                HttpGet method = new HttpGet(uri.toString());

                if (resultHeaders != null)
                    for (Entry<String, String> resultHeader : resultHeaders.entrySet())
                        method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
                if (userAgent != null)
                    method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

                SizeRestrictedHttpResponse response = httpClient.execute(method,
                        new SizeRestrictedResponseHandler(maximumContentLength, uri));

                try {
                    if (response != null) {
                        inputStream = new ByteArrayInputStream(response.getResponse());
                        contentType = response.getContentType() != null ? response.getContentType().getValue()
                                : null;
                    } else
                        return null;
                } catch (RuntimeException e) {
                    method.abort();

                    throw e;
                }
            } catch (IllegalArgumentException e) {
                logger.error("Invalid URL " + uri.toString() + " - not returning content", e);

                return null;
            }
        } else {
            logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed.");

            return null;
        }

        // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection)

        InputStream readerInputStream = new BufferedInputStream(inputStream);
        MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata());

        try {
            Reader reader = null;

            if (mediaType.getType().equals("application")) {
                if (mediaType.getSubtype().equals("x-gzip")) {
                    GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream);

                    if (encodingOverride != null)
                        reader = readerToBuffer(new StringBuffer(),
                                new InputStreamReader(gzipInputStream, encodingOverride), false);
                    else
                        reader = readerToBuffer(new StringBuffer(),
                                contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true)
                                        : new XmlReader(gzipInputStream, true),
                                false);

                    gzipInputStream.close();
                } else if (mediaType.getSubtype().equals("zip")) {
                    ZipFile zipFile = null;

                    // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead

                    File temporaryFile = File.createTempFile("profiler-", ".zip");

                    try {
                        FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile);
                        IOUtils.copy(readerInputStream, zipOutputStream);

                        readerInputStream.close();

                        zipOutputStream.flush();
                        zipOutputStream.close();

                        // Create a new entry and process it

                        zipFile = new ZipFile(temporaryFile);
                        Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries();

                        ZipEntry zipEntry = zipEnumeration.nextElement();

                        if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) {
                            logger.error(
                                    "ZIP files are currently expected to contain one and only one entry, which is to be a file");

                            return null;
                        }

                        // We currently only perform prolog stripping for ZIP files

                        InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));

                        if (encodingOverride != null)
                            reader = readerToBuffer(new StringBuffer(), new InputStreamReader(
                                    new BufferedInputStream(zipInputStream), encodingOverride), true);
                        else
                            result = readerToBuffer(new StringBuffer(),
                                    contentType != null
                                            ? new XmlHtmlReader(new BufferedInputStream(zipInputStream),
                                                    contentType, true)
                                            : new XmlReader(new BufferedInputStream(zipInputStream), true),
                                    true);
                    } catch (Exception e) {
                        logger.error("An error occurred during ZIP file processing", e);

                        return null;
                    } finally {
                        if (zipFile != null)
                            zipFile.close();

                        if (!temporaryFile.delete())
                            logger.error("Unable to delete temporary file");
                    }
                }
            }

            if (result == null) {
                if (encodingOverride != null)
                    result = readerToBuffer(new StringBuffer(), reader != null ? reader
                            : new InputStreamReader(readerInputStream, encodingOverride), false);
                else
                    result = readerToBuffer(new StringBuffer(),
                            reader != null ? reader
                                    : contentType != null
                                            ? new XmlHtmlReader(readerInputStream, contentType, true)
                                            : new XmlReader(readerInputStream, true),
                            false);
            }
        } catch (Exception e) {
            logger.error("An error occurred during stream processing", e);

            return null;
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        logger.error("Could not retrieve the given feed: " + e.getMessage(), e);

        return null;
    }

    return result;
}

From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java

/**
 * Store the not-already-cached files from the given URL and return their locations.
 * /*  w ww  .  ja  v  a 2 s .c om*/
 * @param archive
 * @return Map<File, String>
 */
private Map<File, String> storeAndDecompressFiles(final Archive archive) {
    Map<File, String> result = new HashMap<File, String>();

    // Create the FTP client

    FTPClient ftpClient = retrieveFtpClient(archive.getUri());

    try {
        // Retrieve the directory listing

        List<ArchiveFile> files = retrieveFiles(archive.getUri().getPath(), ftpClient,
                archive.getExclusionExpression());

        Integer archiveNumber = -1, archiveTotal = files.size();

        logger.info("Archive with name '" + archive.getName() + "' produced " + archiveTotal + " files");

        // An empty archive typically indicates failure

        if (archiveTotal == 0)
            logger.warn("The given archive produced no entries - something probably went wrong");

        // Handle all archive files

        for (ArchiveFile archiveFile : files) {
            archiveNumber++;

            // Check whether the file already exists within the cache

            String baseUrl = (StringUtils.hasText(archive.getUri().getScheme())
                    ? archive.getUri().getScheme() + "://"
                    : "") + archive.getUri().getHost()
                    + (archive.getUri().getPort() != -1 ? ":" + archive.getUri().getPort() : "");

            if (!cacheService.isArchived(baseUrl + archiveFile.getFullPath())) {
                logger.info("Started decompressing archive " + archiveNumber + "/" + archiveTotal
                        + " with name " + archiveFile.getFullPath());

                // Write out the archive to disk so we can determine the MIME type

                File archiveFileFolder = new File(archiveFile
                        .getTranslatedPath(packagesLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!archiveFileFolder.exists())
                    archiveFileFolder.mkdirs();

                File archiveFileLocation = new File(archiveFileFolder, archiveFile.getFile().getName());

                InputStream archiveInputStream = ftpClient.retrieveFileStream(archiveFile.getFullPath());
                OutputStream archiveOutputStream = new FileOutputStream(archiveFileLocation);

                IOUtils.copy(archiveInputStream, archiveOutputStream);

                archiveInputStream.close();
                ftpClient.completePendingCommand();

                archiveOutputStream.flush();
                archiveOutputStream.close();

                // Now unpack the archive and transform each file

                InputStream compressedArchiveInputStream = new FileInputStream(archiveFileLocation);

                // Now determine the content type and create a reader in case of structured content

                MediaType archiveMediaType = autoDetectParser.getDetector()
                        .detect(new BufferedInputStream(compressedArchiveInputStream), new Metadata());

                if (!(archiveMediaType.getType().equals("application")
                        && archiveMediaType.getSubtype().equals("zip"))) {
                    logger.warn("Archive file " + archiveFile.getFullPath() + " contains " + archiveMediaType
                            + " data, which is not yet supported");

                    compressedArchiveInputStream.close();

                    continue;
                } else
                    compressedArchiveInputStream.close();

                // Create a new ZIP file from the given archive and decompress it

                ZipFile zipFile = new ZipFile(archiveFileLocation);

                File resultsLocationFolder = new File(archiveFile
                        .getTranslatedPath(resultsLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!resultsLocationFolder.exists())
                    resultsLocationFolder.mkdirs();

                File resultsLocation = new File(resultsLocationFolder,
                        stripExtension(archiveFile.getFile().getName()));

                if (!resultsLocation.exists())
                    resultsLocation.mkdirs();

                logger.info("Started processing archive with name " + archiveFile.getFullPath());

                Enumeration<? extends ZipEntry> zipEnumerator = zipFile.entries();

                while (zipEnumerator.hasMoreElements()) {
                    ZipEntry entry = zipEnumerator.nextElement();

                    // Store it locally first

                    File entryLocation = new File(resultsLocation, entry.getName());

                    try {
                        InputStream entryInputStream = zipFile.getInputStream(entry);
                        OutputStream entryOutputStream = new FileOutputStream(entryLocation);

                        IOUtils.copy(entryInputStream, entryOutputStream);

                        entryInputStream.close();
                        entryOutputStream.close();
                    } catch (IOException e) {
                        logger.error("Could not store the compressed archive entry on disk", e);

                        continue;
                    }
                }

                zipFile.close();

                // Add it to the results

                result.put(resultsLocation, baseUrl + archiveFile.getFullPath());

                logger.info("Finished processing archive with name " + archiveFile.getFullPath());
            } else if (logger.isDebugEnabled())
                logger.debug("Skipping previously processed archive with name " + archiveFile.getFullPath());
        }
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    } finally {
        try {
            if (ftpClient.isConnected())
                ftpClient.disconnect();
        } catch (IOException e) {
            logger.error("Could not disconnect the FTP client", e);
        }
    }

    return result;
}

From source file:nl.strohalm.cyclos.themes.ThemeHandlerImpl.java

@Override
protected void doSelect(final String fileName) {
    ZipFile zipFile = null;
    final LocalSettings settings = settingsService.getLocalSettings();
    final String charset = settings.getCharset();
    try {/*  w w  w . j ava  2s.  co  m*/
        final File file = realFile(fileName);
        if (!file.exists()) {
            throw new ThemeNotFoundException(fileName);
        }
        zipFile = new ZipFile(file);

        // Ensure the properties entry exists
        properties(zipFile);

        // Find all currently used images by style
        final Map<String, Collection<String>> imagesByFile = new HashMap<String, Collection<String>>();
        final File imageDir = webImageHelper.imagePath(Image.Nature.STYLE);
        final File[] cssFiles = imageDir.listFiles(STYLE_FILTER);
        for (final File css : cssFiles) {
            final String contents = FileUtils.readFileToString(css, charset);
            final List<String> urls = CSSHelper.resolveURLs(contents);
            imagesByFile.put(css.getName(), urls);
        }

        // Read the files
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            // We will not handle directories
            if (entry.isDirectory()) {
                continue;
            }
            final String name = entry.getName();
            final String entryFileName = new File(name).getName();
            if (name.startsWith("images/")) {
                final ImageType type = ImageType.getByFileName(entryFileName);
                // Save the image
                final Image image = imageService.save(Image.Nature.STYLE, type, entryFileName,
                        zipFile.getInputStream(entry));
                // Update the physical image
                webImageHelper.update(image);
            } else if (name.startsWith("styles/")) {
                // Save the style sheet
                CustomizedFile customizedFile = new CustomizedFile();
                customizedFile.setName(entryFileName);
                customizedFile.setType(CustomizedFile.Type.STYLE);
                final String contents = IOUtils.toString(zipFile.getInputStream(entry), charset);
                customizedFile.setContents(contents);
                final File originalFile = customizationHelper.originalFileOf(Type.STYLE, entryFileName);
                if (originalFile.exists()) {
                    customizedFile.setOriginalContents(FileUtils.readFileToString(originalFile, charset));
                }
                customizedFile = customizedFileService.saveForTheme(customizedFile);

                // Update the physical file
                final File physicalFile = customizationHelper.customizedFileOf(CustomizedFile.Type.STYLE,
                        entryFileName);
                customizationHelper.updateFile(physicalFile, customizedFile);

                // Remove images that are no longer used
                final List<String> newImages = CSSHelper.resolveURLs(contents);
                final Collection<String> oldImages = imagesByFile.get(entryFileName);
                if (CollectionUtils.isNotEmpty(oldImages)) {
                    for (final String imageName : oldImages) {
                        if (!newImages.contains(imageName)) {
                            // No longer used. Remove it
                            imageService.removeStyleImage(imageName);
                            // Remove the physical file
                            final File imageFile = new File(imageDir, imageName);
                            customizationHelper.deleteFile(imageFile);
                        }
                    }
                }
            }
        }
    } catch (final ThemeException e) {
        throw e;
    } catch (final Exception e) {
        throw new ThemeException(e);
    } finally {
        try {
            zipFile.close();
        } catch (final Exception e) {
            // Ignore
        }
    }
}

From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java

@Override
public InstallationResult extractExtension(InputStream inputStream) {
    Throwable cause = null;/* www .  j  a v a  2s .  co  m*/
    Set<MetaData> metaDataSet = new HashSet<MetaData>();

    File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp");

    if (!installTempDir.exists()) {
        installTempDir.mkdir();
    }

    File tempFile = null;
    FileOutputStream tempFileOutputStream = null;
    ZipFile zipFile = null;

    try {
        /*
         * create a new temp file (in the install temp dir) to store the zip file contents
         */
        tempFile = File.createTempFile(ServerUUIDGenerator.getUUID(), ".zip", installTempDir);
        // write the contents of the multipart fileitem to the temp file
        try {
            tempFileOutputStream = new FileOutputStream(tempFile);
            IOUtils.copy(inputStream, tempFileOutputStream);
        } finally {
            IOUtils.closeQuietly(tempFileOutputStream);
        }

        // create a new zip file from the temp file
        zipFile = new ZipFile(tempFile);
        // get a list of all of the entries in the zip file
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entryName.endsWith("plugin.xml") || entryName.endsWith("destination.xml")
                    || entryName.endsWith("source.xml")) {
                // parse the extension metadata xml file
                MetaData extensionMetaData = serializer
                        .deserialize(IOUtils.toString(zipFile.getInputStream(entry)), MetaData.class);
                metaDataSet.add(extensionMetaData);

                if (!extensionLoader.isExtensionCompatible(extensionMetaData)) {
                    if (cause == null) {
                        cause = new VersionMismatchException("Extension \"" + entry.getName()
                                + "\" is not compatible with this version of Mirth Connect.");
                    }
                }
            }
        }

        if (cause == null) {
            // reset the entries and extract
            entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();

                if (entry.isDirectory()) {
                    /*
                     * assume directories are stored parents first then children.
                     * 
                     * TODO: this is not robust, just for demonstration purposes.
                     */
                    File directory = new File(installTempDir, entry.getName());
                    directory.mkdir();
                } else {
                    // otherwise, write the file out to the install temp dir
                    InputStream zipInputStream = zipFile.getInputStream(entry);
                    OutputStream outputStream = new BufferedOutputStream(
                            new FileOutputStream(new File(installTempDir, entry.getName())));
                    IOUtils.copy(zipInputStream, outputStream);
                    IOUtils.closeQuietly(zipInputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } catch (Throwable t) {
        cause = new ControllerException("Error extracting extension. " + t.toString(), t);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (Exception e) {
                cause = new ControllerException(e);
            }
        }

        // delete the temp file since it is no longer needed
        FileUtils.deleteQuietly(tempFile);
    }

    return new InstallationResult(cause, metaDataSet);
}

From source file:org.codehaus.mojo.webstart.JnlpMojo.java

protected void removeSignatures(File currentJar, String shortName) throws IOException {
    // We should remove any previous signature information.  This
    // can screw up the packing code, and if it is signed with 2 signatures
    // it can not be verified.
    ZipFile currentJarZipFile = new ZipFile(currentJar);
    Enumeration entries = currentJarZipFile.entries();

    // There might be more valid extensions but this is what we've seen so far 
    // the ?i makes it case insensitive       
    Pattern signatureChecker = Pattern.compile("(?i)^meta-inf/.*((\\.sf)|(\\.rsa))$");

    getLog().debug("checking for old signature : " + shortName);
    Vector signatureFiles = new Vector();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        Matcher matcher = signatureChecker.matcher(entry.getName());
        if (matcher.find()) {
            // we found a old signature in the file
            signatureFiles.add(entry.getName());
            getLog().warn("found signature: " + entry.getName());
        }//w w w.j a  v a2s  .c o  m
    }

    if (signatureFiles.size() == 0) {
        // no old files were found
        currentJarZipFile.close();
        return;
    }

    // We found some old signature files, write out the file again without
    // them    
    File outFile = new File(currentJar.getParent(), currentJar.getName() + ".unsigned");
    ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(outFile));

    entries = currentJarZipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        if (signatureFiles.contains(entry.getName())) {
            continue;
        }
        InputStream entryInStream = currentJarZipFile.getInputStream(entry);
        ZipEntry newEntry = new ZipEntry(entry);
        zipOutStream.putNextEntry(newEntry);
        IOUtil.copy(entryInStream, zipOutStream);
        entryInStream.close();
    }

    zipOutStream.close();
    currentJarZipFile.close();

    FileUtils.rename(outFile, currentJar);

    getLog().info("removed signature");
}

From source file:org.fireflow.client.impl.WorkflowStatementLocalImpl.java

private Map<String, InputStream> parseModelDefsFromZipFile(File processZipFile) throws InvalidModelException {
    Map<String, InputStream> modelDefsMap = new HashMap<String, InputStream>();
    ZipFile zf = null;
    try {//from  w  w  w . j av a  2  s.  c om
        zf = new ZipFile(processZipFile);
    } catch (ZipException e) {
        throw new InvalidModelException(e);
    } catch (IOException e) {
        throw new InvalidModelException(e);
    }

    Enumeration enu = zf.entries();
    while (enu.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) enu.nextElement();
        String fileName = entry.getName();
        try {
            if (!(entry.isDirectory())) {
                InputStream inputStream = zf.getInputStream(entry);
                modelDefsMap.put(fileName, inputStream);
                //               ByteArrayOutputStream out = new ByteArrayOutputStream();
                //
                //               byte[] buf = new byte[1024];
                //               int read = 0;
                //               do {
                //                  read = inputStream.read(buf, 0, buf.length);
                //                  if (read > 0)
                //                     out.write(buf, 0, read);
                //               } while (read >= 0);
                //               processDefinitionsContent.put(fileName,
                //                     out.toString("UTF-8"));
            }
        } catch (IOException e) {
            throw new InvalidModelException(e);
        }
    }

    return modelDefsMap;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Process file upload/* w  w  w. j  a  va2s . c  om*/
 *
 * @param request Http request
 * @return Html form
 */
public String doCreateFile(HttpServletRequest request) {
    String strDirectoryIndex = null;

    try {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        FileItem item = multiRequest.getFile(PARAMETER_FILE_NAME);

        // The index and value of the directory combo in the form
        strDirectoryIndex = multiRequest.getParameter(PARAMETER_DIRECTORY);

        String strRelativeDirectory = getDirectory(strDirectoryIndex);

        // The absolute path of the target directory
        String strDestDirectory = AppPathService.getWebAppPath() + strRelativeDirectory;

        // List the files in the target directory
        File[] existingFiles = (new File(strDestDirectory)).listFiles();

        // Is the 'unzip' checkbox checked?
        boolean bUnzip = (multiRequest.getParameter(PARAMETER_UNZIP) != null);

        if (item != null && !item.getName().equals(StringUtils.EMPTY)) {
            if (!bUnzip) // copy the file
            {
                AppLogService.debug("copying the file");

                // Getting downloadFile's name
                String strNameFile = FileUploadService.getFileNameOnly(item);

                // Clean name
                String strClearName = UploadUtil.cleanFileName(strNameFile);

                // Checking duplicate
                if (duplicate(strClearName, existingFiles)) {
                    return AdminMessageService.getMessageUrl(request, MESSAGE_FILE_EXISTS,
                            AdminMessage.TYPE_STOP);
                }

                // Move the file to the target directory
                File destFile = new File(strDestDirectory, strClearName);

                FileOutputStream fos = new FileOutputStream(destFile);
                fos.flush();
                fos.write(item.get());
                fos.close();
            } else // unzip the file
            {
                AppLogService.debug("unzipping the file");

                ZipFile zipFile;

                try {
                    // Create a temporary file with result of getTime() as unique file name
                    File tempFile = File.createTempFile(Long.toString((new Date()).getTime()), ".zip");
                    // Delete temp file when program exits.
                    tempFile.deleteOnExit();

                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.flush();
                    fos.write(item.get());
                    fos.close();
                    zipFile = new ZipFile(tempFile);
                } catch (ZipException ze) {
                    AppLogService.error("Error opening zip file", ze);

                    return AdminMessageService.getMessageUrl(request, MESSAGE_ZIP_ERROR,
                            AdminMessage.TYPE_STOP);
                }

                // Each zipped file is indentified by a zip entry :
                Enumeration zipEntries = zipFile.entries();

                while (zipEntries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

                    // Clean the name :
                    String strZippedName = zipEntry.getName();
                    String strClearName = UploadUtil.cleanFilePath(strZippedName);

                    if (strZippedName.equals(strClearName)) {
                        // The unzipped file :
                        File destFile = new File(strDestDirectory, strClearName);

                        // Create the parent directory structure if needed :
                        destFile.getParentFile().mkdirs();

                        if (!zipEntry.isDirectory()) // don't unzip directories
                        {
                            AppLogService.debug("unzipping " + strZippedName + " to " + destFile.getName());

                            // InputStream from zipped data
                            InputStream inZipStream = zipFile.getInputStream(zipEntry);

                            // OutputStream to the destination file
                            OutputStream outDestStream = new FileOutputStream(destFile);

                            // Helper method to copy data
                            copyStream(inZipStream, outDestStream);

                            inZipStream.close();
                            outDestStream.close();
                        } else {
                            AppLogService.debug("skipping directory " + strZippedName);
                        }
                    } else {
                        AppLogService.debug("skipping accented file " + strZippedName);
                    }
                }
            }
        } else {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    // Returns upload management page
    UrlItem url = new UrlItem(getHomeUrl(request));

    if (strDirectoryIndex != null) {
        url.addParameter(PARAMETER_DIRECTORY, strDirectoryIndex);
    }

    return url.getUrl();
}

From source file:com.web.server.WarDeployer.java

/**
 * This method deploys the war in exploded form and configures it. 
 * @param file/*  ww  w  . ja  v a  2s  .  c o  m*/
 * @param customClassLoader
 * @param warDirectoryPath
 */
public void extractWar(File file, WebClassLoader customClassLoader) {

    StringBuffer classPath = new StringBuffer();
    int numBytes;
    try {
        ConcurrentHashMap jspMap = new ConcurrentHashMap();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        //String fileName=file.getName();
        String directoryName = file.getName();
        directoryName = directoryName.substring(0, directoryName.indexOf('.'));
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            //logger.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
            new WebServer().addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"),
                    customClassLoader);
            //new WebServer().addURL(new URL("file://"+warDirectoryPath+"/"),customClassLoader);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //System.out.println("Unzipping " + ze.getName());
            String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //System.out.println(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jsp")) {
                    jspMap.put(ze.getName(), filePath);
                } else if (ze.getName().endsWith(".jar")) {
                    new WebServer().addURL(
                            new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()),
                            customClassLoader);
                    classPath.append(filePath);
                    classPath.append(";");
                }
            }
        }
        zip.close();
        Set jsps = jspMap.keySet();
        Iterator jspIterator = jsps.iterator();
        classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes/;");
        ArrayList<String> jspFiles = new ArrayList();
        //System.out.println(classPath.toString());
        if (jspIterator.hasNext())
            new WebServer().addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"),
                    customClassLoader);
        while (jspIterator.hasNext()) {
            String filepackageInternal = (String) jspIterator.next();
            String filepackageInternalTmp = filepackageInternal;
            if (filepackageInternal.lastIndexOf('/') == -1) {
                filepackageInternal = "";
            } else {
                filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/'))
                        .replace("/", ".");
                filepackageInternal = "." + filepackageInternal;
            }
            createDirectory(scanDirectory + "/temp/" + directoryName);
            File jspFile = new File((String) jspMap.get(filepackageInternalTmp));
            String fName = jspFile.getName();
            String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp";
            //String fileCreated=new JspCompiler().compileJsp((String) jspMap.get(filepackageInternalTmp), scanDirectory+"/temp/"+fileName, "com.web.server"+filepackageInternal,classPath.toString());
            synchronized (customClassLoader) {
                String fileNameInWar = filepackageInternalTmp;
                jspFiles.add(fileNameInWar.replace("/", "\\"));
                if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                    customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                            "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                } else {
                    customClassLoader.addURL("/" + fileNameInWar,
                            "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                }
            }
        }
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(customClassLoader);
            try {
                JspC jspc = new JspC();
                jspc.setUriroot(scanDirectory + "/" + directoryName + "/");
                jspc.setAddWebXmlMappings(false);
                jspc.setCompile(true);
                jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                jspc.setPackage("com.web.server");
                StringBuffer buffer = new StringBuffer();
                for (String jspFile : jspFiles) {
                    buffer.append(",");
                    buffer.append(jspFile);
                }
                String jsp = buffer.toString();
                jsp = jsp.substring(1, jsp.length());
                System.out.println(jsp);
                jspc.setJspFiles(jsp);
                jspc.execute();
            } catch (Throwable je) {
                je.printStackTrace();
            } finally {
                Thread.currentThread().setContextClassLoader(oldCL);
            }
            Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        try {
            new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap,
                    new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"),
                    customClassLoader);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        try {
            new MessagingClassConstruct().getMessagingClass(messagedigester,
                    new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"),
                    customClassLoader, messagingClassMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        webxmldigester.setNamespaceAware(true);
        webxmldigester.setValidating(true);
        //digester.setRules(null);
        FileInputStream webxml = new FileInputStream(
                scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml");
        InputSource is = new InputSource(webxml);
        try {
            System.out.println("SCHEMA");
            synchronized (webxmldigester) {
                //webxmldigester.set("config/web-app_2_4.xsd");
                WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is);
                servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig);
            }
            webxml.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (Exception ex) {

    }
}