Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:net.sf.zekr.common.config.ApplicationConfig.java

private RevelationData loadRevelationData(File revelZipFile) throws IOException, ConfigurationException {
    ZipFile zipFile = new ZipFile(revelZipFile);
    InputStream is = zipFile.getInputStream(new ZipEntry(ApplicationPath.REVELATION_DESC));
    if (is == null) {
        logger.warn("Will ignore invalid revelation data archive \"" + zipFile.getName() + "\".");
        return null;
    }//from   ww  w . ja va  2 s. c  om
    PropertiesConfiguration pc = ConfigUtils.loadConfig(is, "UTF-8");
    zipFile.close();

    RevelationData rd = new RevelationData();

    int len;
    if ("aya".equals(pc.getString("mode", "sura"))) {
        len = QuranPropertiesUtils.QURAN_AYA_COUNT;
        rd.mode = RevelationData.AYA_MODE;
    } else {
        len = 114;
        rd.mode = RevelationData.SURA_MODE;
    }
    rd.suraOrders = new int[len];
    rd.orders = new int[len];
    // rd.years = new int[len]; // not used for now

    rd.version = pc.getString("version");
    String zipFileName = revelZipFile.getName();
    rd.id = zipFileName.substring(0, zipFileName.length() - ApplicationPath.REVEL_PACK_SUFFIX.length());
    rd.archiveFile = revelZipFile;
    rd.delimiter = pc.getString("delimiter", "\n");
    String sig = pc.getString("signature");

    byte[] sigBytes = sig.getBytes("US-ASCII");
    rd.signature = sig == null ? null : Base64.decodeBase64(sigBytes);

    rd.loadLocalizedNames(pc, "name");

    if (StringUtils.isBlank(rd.id) || rd.localizedNameMap.size() == 0 || StringUtils.isBlank(rd.version)) {
        logger.warn("Invalid revelation data package: \"" + rd + "\".");
        return null;
    }
    return rd;
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

/**
 * Unzip the specified file./*from w w  w . ja  va  2  s .  c  o  m*/
 * 
 * @param zipFilePath String path to zip file.
 * @throws IOException during zip or read process.
 */
public static void extractFolder(String zipFilePath) throws IOException {
    ZipFile zipFile = null;

    try {
        int BUFFER = 2048;
        File file = new File(zipFilePath);

        zipFile = new ZipFile(file);
        String newPath = zipFilePath.substring(0, zipFilePath.length() - 4);

        makeDirs(new File(newPath));
        Enumeration<?> zipFileEntries = zipFile.entries();

        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            makeDirs(destinationParent);

            InputStream is = null;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;

            try {
                if (destFile.exists() && destFile.isDirectory())
                    continue;

                if (!entry.isDirectory()) {
                    int currentByte;
                    byte data[] = new byte[BUFFER];
                    is = zipFile.getInputStream(entry);
                    bis = new BufferedInputStream(is);
                    fos = new FileOutputStream(destFile);
                    bos = new BufferedOutputStream(fos, BUFFER);

                    while ((currentByte = bis.read(data, 0, BUFFER)) != -1) {
                        bos.write(data, 0, currentByte);
                    }
                    bos.flush();
                }
            } finally {
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(bos);
                IOUtils.closeQuietly(fos);
            }

            if (currentEntry.endsWith(".zip")) {
                extractFolder(destFile.getAbsolutePath());
            }
        }
    } catch (Exception e) {
        log.warning("Failed to unzip: " + zipFilePath, e);
        throw new IllegalStateException(e);
    } finally {
        if (zipFile != null)
            zipFile.close();
    }
}

From source file:org.openflexo.toolbox.ZipUtils.java

public static final void unzip(File zip, File outputDir, IProgress progress) throws ZipException, IOException {
    Enumeration<? extends ZipEntry> entries;
    outputDir = outputDir.getCanonicalFile();
    if (!outputDir.exists()) {
        boolean b = outputDir.mkdirs();
        if (!b) {
            throw new IllegalArgumentException("Could not create dir " + outputDir.getAbsolutePath());
        }//  w  ww .j  av  a  2s.com
    }
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException(
                outputDir.getAbsolutePath() + "is not a directory or is not writeable!");
    }
    ZipFile zipFile;
    zipFile = new ZipFile(zip);
    entries = zipFile.entries();
    if (progress != null) {
        progress.resetSecondaryProgress(zipFile.size());
    }
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (progress != null) {
            progress.setSecondaryProgress(
                    FlexoLocalization.localizedForKey("unzipping") + " " + entry.getName());
        }
        if (entry.getName().startsWith("__MACOSX")) {
            continue;
        }
        if (entry.isDirectory()) {
            // Assume directories are stored parents first then
            // children.
            // This is not robust, just for demonstration purposes.
            new File(outputDir, entry.getName().replace('\\', '/')).mkdirs();
            continue;
        }
        File outputFile = new File(outputDir, entry.getName().replace('\\', '/'));
        if (outputFile.getName().startsWith("._")) {
            // This block is made to drop MacOS crap added to zip files
            if (zipFile.getEntry(
                    entry.getName().substring(0, entry.getName().length() - outputFile.getName().length())
                            + outputFile.getName().substring(2)) != null) {
                continue;
            }
            if (new File(outputFile.getParentFile(), outputFile.getName().substring(2)).exists()) {
                continue;
            }
        }
        FileUtils.createNewFile(outputFile);
        InputStream zipStream = null;
        FileOutputStream fos = null;
        try {
            zipStream = zipFile.getInputStream(entry);
            if (zipStream == null) {
                System.err.println("Could not find input stream for entry: " + entry.getName());
                continue;
            }
            fos = new FileOutputStream(outputFile);
            copyInputStream(zipStream, new BufferedOutputStream(fos));
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Could not extract: " + outputFile.getAbsolutePath()
                    + " maybe some files contains invalid characters.");
        } finally {
            IOUtils.closeQuietly(zipStream);
            IOUtils.closeQuietly(fos);
        }
    }
    Collection<File> listFiles = org.apache.commons.io.FileUtils.listFiles(outputDir, null, true);
    for (File file : listFiles) {
        if (file.isFile() && file.getName().startsWith("._")) {
            File f = new File(file.getParentFile(), file.getName().substring(2));
            if (f.exists()) {
                file.delete();
            }
        }
    }
    zipFile.close();
}

From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *//*from   ww w  . j av a2s .com*/
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(updateFolder, name);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException ex) {
        this.sender.sendMessage(
                this.prefix + "The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        this.plugin.getLogger().log(Level.SEVERE, null, ex);
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

/**
 * Extract an entry in a gived folder. If this entry is a directory,
 * all its contents are extracted too.//from w  w w. j a  va 2  s .  c  om
 *
 * @param entryName, the name of an entry in the jar
 * @param destPath,  the path to the destination folder
 */
public void extractEntry(String entryName, String destPath) throws JahiaException {

    try {

        ZipEntry entry = m_JarFile.getEntry(entryName);

        if (entry == null) {
            StringBuilder strBuf = new StringBuilder(1024);
            strBuf.append(" extractEntry(), cannot find entry ");
            strBuf.append(entryName);
            strBuf.append(" in the jar file ");

            throw new JahiaException(CLASS_NAME, strBuf.toString(), JahiaException.SERVICE_ERROR,
                    JahiaException.ERROR_SEVERITY);

        }

        File destDir = new File(destPath);
        if (destDir == null || !destDir.isDirectory() || !destDir.canWrite()) {

            logger.error(" cannot access to the destination dir " + destPath);

            throw new JahiaException(CLASS_NAME, " cannot access to the destination dir ",
                    JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
        }

        String path = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        while ((ze = zis.getNextEntry()) != null && !ze.getName().equalsIgnoreCase(entryName)) {
            // loop until the requested entry
            zis.closeEntry();
        }

        try {
            if (ze != null) {
                if (ze.isDirectory()) {

                    while (ze != null) {
                        zeName = ze.getName();
                        path = destPath + File.separator + genPathFile(zeName);
                        File fo = new File(path);
                        if (ze.isDirectory()) {
                            fo.mkdirs();
                        } else {

                            FileOutputStream outs = new FileOutputStream(fo);
                            copyStream(zis, outs);
                            //outs.flush();
                            //outs.close();
                        }
                        zis.closeEntry();
                        ze = zis.getNextEntry();

                    }
                } else {

                    zeName = ze.getName();
                    path = destPath + File.separator + genPathFile(zeName);

                    File fo = new File(path);
                    FileOutputStream outs = new FileOutputStream(fo);
                    copyStream(zis, outs);
                    //outs.flush();
                    //outs.close();
                }
            }
        } finally {
            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException(CLASS_NAME, "faile processing unzip", JahiaException.SERVICE_ERROR,
                JahiaException.ERROR_SEVERITY, ioe);

    }

}

From source file:org.tellervo.desktop.bulkdataentry.command.PopulateFromODKCommand.java

public void execute(MVCEvent argEvent) {

    try {/*from  w  ww.j a v a2 s.  co  m*/
        MVC.splitOff(); // so other mvc events can execute
    } catch (IllegalThreadException e) {
        // this means that the thread that called splitOff() was not an MVC thread, and the next event's won't be blocked anyways.
        e.printStackTrace();
    } catch (IncorrectThreadException e) {
        // this means that this MVC thread is not the main thread, it was already splitOff() previously
        e.printStackTrace();
    }

    PopulateFromODKFileEvent event = (PopulateFromODKFileEvent) argEvent;
    ArrayList<ODKParser> filesProcessed = new ArrayList<ODKParser>();
    ArrayList<ODKParser> filesFailed = new ArrayList<ODKParser>();
    Path instanceFolder = null;

    // Launch the ODK wizard to collect parameters from user
    ODKImportWizard wizard = new ODKImportWizard(BulkImportModel.getInstance().getMainView());

    if (wizard.wasCancelled())
        return;

    if (wizard.isRemoteAccessSelected()) {
        // Doing remote server download of ODK files
        try {

            // Request a zip file of ODK files from the server ensuring the temp file is deleted on exit
            URI uri;
            uri = new URI(
                    App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid url!") + "/" + "odk/fetchInstances.php");
            String file = getRemoteODKFiles(uri);

            if (file == null) {
                // Download was cancelled
                return;
            }

            new File(file).deleteOnExit();

            // Unzip to a temporary folder, again ensuring it is deleted on exit 
            instanceFolder = Files.createTempDirectory("odk-unzip");
            instanceFolder.toFile().deleteOnExit();

            log.debug("Attempting to open zip file: '" + file + "'");

            ZipFile zipFile = new ZipFile(file);
            try {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    File entryDestination = new File(instanceFolder.toFile(), entry.getName());
                    entryDestination.deleteOnExit();
                    if (entry.isDirectory()) {
                        entryDestination.mkdirs();
                    } else {
                        entryDestination.getParentFile().mkdirs();
                        InputStream in = zipFile.getInputStream(entry);
                        OutputStream out = new FileOutputStream(entryDestination);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        out.close();
                    }
                }
            } finally {
                zipFile.close();
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // Accessing ODK files from local folder
        instanceFolder = new File(wizard.getODKInstancesFolder()).toPath();
    }

    // Check the instance folder specified exists
    File folder = instanceFolder.toFile();
    if (!folder.exists()) {

        log.error("Instances folder does not exist");
        return;
    }

    // Compile a hash set of all media files in the instance folder and subfolders
    File file = null;
    File[] mediaFileArr = null;
    if (wizard.isIncludeMediaFilesSelected()) {
        HashSet<File> mediaFiles = new HashSet<File>();

        // Array of file extensions to consider as media files
        String[] mediaExtensions = { "jpg", "mpg", "snd", "mp4", "m4a" };
        for (String ext : mediaExtensions) {
            SuffixFileFilter filter = new SuffixFileFilter("." + ext);
            Iterator<File> it = FileUtils.iterateFiles(folder, filter, TrueFileFilter.INSTANCE);
            while (it.hasNext()) {
                file = it.next();
                mediaFiles.add(file);
            }
        }

        // Copy files to consolidate to a new folder 
        mediaFileArr = mediaFiles.toArray(new File[mediaFiles.size()]);
        String copyToFolder = wizard.getCopyToLocation();
        for (int i = 0; i < mediaFileArr.length; i++) {
            file = mediaFileArr[i];

            File target = new File(copyToFolder + file.getName());
            try {
                FileUtils.copyFile(file, target, true);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mediaFileArr[i] = target;
        }
    }

    SampleModel smodel = event.sampleModel;
    ElementModel emodel = event.elementModel;
    ObjectModel model = event.objectModel;

    try {
        if (smodel.getTableModel().getRowCount() == 1 && smodel.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleSampleModel.TITLE) == null) {
            // Empty table first
            smodel.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    try {
        if (emodel.getTableModel().getRowCount() == 1 && emodel.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleElementModel.TITLE) == null) {
            // Empty table first
            emodel.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    try {
        if (model.getTableModel().getRowCount() == 1 && model.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleObjectModel.OBJECT_CODE) == null) {
            // Empty table first
            model.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    SuffixFileFilter fileFilter = new SuffixFileFilter(".xml");
    Iterator<File> iterator = FileUtils.iterateFiles(folder, fileFilter, TrueFileFilter.INSTANCE);
    while (iterator.hasNext()) {
        file = iterator.next();
        filesFound++;

        try {

            ODKParser parser = new ODKParser(file);
            filesProcessed.add(parser);

            if (!parser.isValidODKFile()) {
                filesFailed.add(parser);
                continue;
            } else if (parser.getFileType() == null) {
                filesFailed.add(parser);
                continue;
            } else if (parser.getFileType() == ODKFileType.OBJECTS) {
                addObjectToTableFromParser(parser, model, wizard, mediaFileArr);
            } else if (parser.getFileType() == ODKFileType.ELEMENTS_AND_SAMPLES) {
                addElementFromParser(parser, emodel, wizard, mediaFileArr);
                addSampleFromParser(parser, smodel, wizard, mediaFileArr);
            } else {
                filesFailed.add(parser);
                continue;
            }

        } catch (FileNotFoundException e) {
            otherErrors += "<p color=\"red\">Error loading file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - File not found<br/><br/>";
        } catch (IOException e) {
            otherErrors += "<p color=\"red\">Error loading file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - IOException - " + e.getLocalizedMessage() + "<br/><br/>";
        } catch (Exception e) {
            otherErrors += "<p color=\"red\">Error parsing file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - Exception - " + e.getLocalizedMessage() + "<br/><br/>";
        }

    }

    // Create a CSV file of metadata if the user requested it
    if (wizard.isCreateCSVFileSelected()) {
        try {
            createCSVFile(filesProcessed, wizard.getCSVFilename());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // Compile logs to display to user
    StringBuilder log = new StringBuilder();
    log.append("<html>\n");
    for (ODKParser parser : filesFailed) {
        log.append("<p color=\"red\">Error loading file:</p>\n"
                + ODKParser.formatFileNameForReport(parser.getFile()));
        log.append("<br/>  - " + parser.getParseErrorMessage() + "<br/><br/>");
    }
    for (ODKParser parser : filesProcessed) {
        if (filesFailed.contains(parser))
            continue;
        if (parser.getParseErrorMessage() == "")
            continue;

        log.append("<p color=\"orange\">Warning loading file:</p>\n"
                + ODKParser.formatFileNameForReport(parser.getFile()));
        log.append("<br/>  - " + parser.getParseErrorMessage() + "<br/><br/>");
    }
    log.append(otherErrors);
    log.append("</html>");
    ODKParserLogViewer logDialog = new ODKParserLogViewer(BulkImportModel.getInstance().getMainView());
    logDialog.setLog(log.toString());
    logDialog.setFileCount(filesFound, filesLoadedSuccessfully);

    // Display log if there were any errors or if no files were found
    if (filesFound > filesLoadedSuccessfully) {
        logDialog.setVisible(true);
    } else if (filesFound == 0 && wizard.isRemoteAccessSelected()) {
        Alert.error(BulkImportModel.getInstance().getMainView(), "Not found",
                "No ODK data files were found on the server.  Please ensure you've used the 'send finalized form' option in ODK Collect and try again");
        return;
    } else if (filesFound == 0) {
        Alert.error(BulkImportModel.getInstance().getMainView(), "Not found",
                "No ODK data files were found in the specified folder.  Please check and try again.");
        return;
    } else if (wizard.isIncludeMediaFilesSelected()) {
        Alert.message(BulkImportModel.getInstance().getMainView(), "Download Complete",
                "The ODK download is complete.  As requested, your media files have been temporarily copied to the local folder '"
                        + wizard.getCopyToLocation()
                        + "'.  Please remember to move them to their final location");
    }

}

From source file:com.facebook.buck.android.AndroidBinaryIntegrationTest.java

@Test
public void testLibraryMetadataChecksum() throws IOException {
    String target = "//apps/sample:app_cxx_lib_asset";
    workspace.runBuckCommand("build", target).assertSuccess();
    Path pathToZip = workspace//w w w  .j  a v  a 2 s .c  o  m
            .getPath(BuildTargets.getGenPath(filesystem, BuildTargetFactory.newInstance(target), "%s.apk"));
    ZipFile file = new ZipFile(pathToZip.toFile());
    ZipEntry metadata = file.getEntry("assets/lib/metadata.txt");
    assertNotNull(metadata);

    BufferedReader contents = new BufferedReader(new InputStreamReader(file.getInputStream(metadata)));
    String line = contents.readLine();
    byte[] buffer = new byte[512];
    while (line != null) {
        // Each line is of the form <filename> <filesize> <SHA256 checksum>
        String[] tokens = line.split(" ");
        assertSame(tokens.length, 3);
        String filename = tokens[0];
        int filesize = Integer.parseInt(tokens[1]);
        String checksum = tokens[2];

        ZipEntry lib = file.getEntry("assets/lib/" + filename);
        assertNotNull(lib);
        InputStream is = file.getInputStream(lib);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while (filesize > 0) {
            int read = is.read(buffer, 0, Math.min(buffer.length, filesize));
            assertTrue(read >= 0);
            out.write(buffer, 0, read);
            filesize -= read;
        }
        String actualChecksum = Hashing.sha256().hashBytes(out.toByteArray()).toString();
        assertEquals(checksum, actualChecksum);
        is.close();
        out.close();
        line = contents.readLine();
    }
    file.close();
    contents.close();
}

From source file:com.app.server.SARDeployer.java

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file//  w w w .j a v  a 2s.c o m
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSarDeploy(ClassLoader cL, Object... args) throws IOException {
    CopyOnWriteArrayList classPath = null;
    File file = null;
    String fileName = "";
    String fileWithPath = "";
    if (args[0] instanceof File) {
        classPath = new CopyOnWriteArrayList();
        file = (File) args[0];
        fileWithPath = file.getAbsolutePath();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        fileName = file.getName();
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        int numBytes;
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //log.info("Unzipping " + ze.getName());
            String filePath = serverConfig.getDeploydirectory() + "/" + fileName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //log.info(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(".jar")) {
                    classPath.add(filePath);
                }
            }
        }
        zip.close();
    } else if (args[0] instanceof FileObject) {
        FileObject fileObj = (FileObject) args[0];
        fileName = fileObj.getName().getBaseName();
        try {
            fileWithPath = fileObj.getURL().toURI().toString();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileName = fileName.substring(0, fileName.indexOf('.'));
        fileName += "sar";
        classPath = unpack(fileObj, new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"),
                (StandardFileSystemManager) args[1]);
    }
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader;
    if (cL != null) {
        sarClassLoader = new WebClassLoader(urls, cL);
    } else {
        sarClassLoader = new WebClassLoader(urls);
    }
    for (int index = 0; index < classPath.size(); index++) {
        // log.info("file:"+classPath.get(index));
        sarClassLoader.addURL(new URL("file:" + classPath.get(index)));
    }
    sarClassLoader.addURL(new URL("file:" + serverConfig.getDeploydirectory() + "/" + fileName + "/"));
    //log.info(sarClassLoader.geturlS());
    sarsMap.put(fileWithPath, sarClassLoader);
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(
                serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName, classLoaderObjectName = new ObjectName("com.app.server:classLoader=" + fileName);
        if (!mbeanServer.isRegistered(classLoaderObjectName)) {
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
        } else {
            mbeanServer.unregisterMBean(classLoaderObjectName);
            mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName);
            ;
        }
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = sarClassLoader.loadClass(mbean.getCls());
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName, classLoaderObjectName);
            //mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
            serviceListObjName.put(fileWithPath, objName);
        }
    } catch (Exception e) {
        log.error("Could not able to deploy sar archive " + fileWithPath, e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}

From source file:org.telscenter.sail.webapp.presentation.web.controllers.admin.UploadProjectController.java

/**
 * @override @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
 *///from  ww  w  .ja v a 2  s .  com
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    // probably should do some kind of virus check. but for now, it's only
    // accessible to admin.

    // uploaded file must be a zip file and have a .zip extension

    ProjectUpload projectUpload = (ProjectUpload) command;
    MultipartFile file = projectUpload.getFile();

    // upload the zipfile to curriculum_base_dir
    String curriculumBaseDir = portalProperties.getProperty("curriculum_base_dir");

    File uploadDir = new File(curriculumBaseDir);
    if (!uploadDir.exists()) {
        throw new Exception("curriculum upload directory does not exist.");
    }

    // save the upload zip file in the curriculum folder.
    String sep = System.getProperty("file.separator");
    long timeInMillis = Calendar.getInstance().getTimeInMillis();
    String zipFilename = file.getOriginalFilename();
    String filename = zipFilename.substring(0, zipFilename.indexOf(".zip"));
    String newFilename = filename;
    if (new File(curriculumBaseDir + sep + filename).exists()) {
        // if this directory already exists, add a date time in milliseconds to the filename to make it unique
        newFilename = filename + "-" + timeInMillis;
    }
    String newFileFullPath = curriculumBaseDir + sep + newFilename + ".zip";

    // copy the zip file inside curriculum_base_dir temporarily
    File uploadedFile = new File(newFileFullPath);
    uploadedFile.createNewFile();
    FileCopyUtils.copy(file.getBytes(), uploadedFile);

    // make a new folder where the contents of the zip should go
    String newFileFullDir = curriculumBaseDir + sep + newFilename;
    File newFileFullDirFile = new File(newFileFullDir);
    newFileFullDirFile.mkdir();

    // unzip the zip file
    try {
        ZipFile zipFile = new ZipFile(newFileFullPath);
        Enumeration entries = zipFile.entries();

        int i = 0; // index used later to check for first folder in the zip file

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

            if (entry.getName().startsWith("__MACOSX")) {
                // if this entry starts with __MACOSX, this zip file was created by a user using mac's "compress" feature.
                // ignore it.
                continue;
            }

            if (entry.isDirectory()) {
                // first check to see if the user has changed the zip file name and therefore the zipfile name
                // is no longer the same as the name of the first folder in the top-level of the zip file.
                // if this is the case, import will fail, so throw an error.
                if (i == 0) {
                    if (!entry.getName().startsWith(filename)) {
                        throw new Exception(
                                "Zip file name does not match folder name. Do not change zip filename");
                    }
                    i++;
                }

                // Assume directories are stored parents first then children.
                System.out.println("Extracting directory: " + entry.getName());
                // This is not robust, just for demonstration purposes.
                (new File(entry.getName().replace(filename, newFileFullDir))).mkdir();
                continue;
            }

            System.out.println("Extracting file: " + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(entry.getName().replaceFirst(filename, newFileFullDir))));
        }

        zipFile.close();
    } catch (IOException ioe) {
        System.err.println("Unhandled exception during project import. Project was not properly imported.");
        ioe.printStackTrace();
        throw ioe;
    }

    // remove the temp zip file
    uploadedFile.delete();

    // now create a project in the db with the new path
    String path = sep + newFilename + sep + "wise4.project.json";
    String name = projectUpload.getName();
    User signedInUser = ControllerUtil.getSignedInUser();
    Set<User> owners = new HashSet<User>();
    owners.add(signedInUser);

    CreateUrlModuleParameters cParams = new CreateUrlModuleParameters();
    cParams.setUrl(path);
    Curnit curnit = curnitService.createCurnit(cParams);

    ProjectParameters pParams = new ProjectParameters();
    pParams.setCurnitId(curnit.getId());
    pParams.setOwners(owners);
    pParams.setProjectname(name);
    pParams.setProjectType(ProjectType.LD);

    ProjectMetadata metadata = null;

    // see if a file called wise4.project-meta.json exists. if yes, try parsing it.
    try {
        String projectMetadataFilePath = newFileFullDir + sep + "wise4.project-meta.json";
        String projectMetadataStr = FileUtils.readFileToString(new File(projectMetadataFilePath));
        JSONObject metadataJSONObj = new JSONObject(projectMetadataStr);
        metadata = new ProjectMetadataImpl();
        metadata.populateFromJSON(metadataJSONObj);
    } catch (Exception e) {
        // if there is any error during the parsing of the metadata, set the metadata to null
        metadata = null;
    }

    // If metadata is null at this point, either wise4.project-meta.json was not
    // found in the zip file, or there was an error parsing. 
    // Set a new fresh metadata object
    if (metadata == null) {
        metadata = new ProjectMetadataImpl();
        metadata.setTitle(name);
    }

    pParams.setMetadata(metadata);

    Project project = projectService.createProject(pParams);

    ModelAndView modelAndView = new ModelAndView(getSuccessView());
    modelAndView.addObject("msg", "Upload project complete, new projectId is: " + project.getId());
    return modelAndView;
}

From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *//*from w w w  .ja  v a2s. co m*/
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            this.fileIOOrError(destinationFilePath.getParentFile(),
                    destinationFilePath.getParentFile().mkdirs(), true);
            if (!entry.isDirectory()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(this.updateFolder, name);
                    this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException e) {
        this.plugin.getLogger().log(Level.SEVERE,
                "The auto-updater tried to unzip a new update file, but was unsuccessful.", e);
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
    } finally {
        this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
    }
}