Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:eu.optimis.ics.ImageCreationServiceREST.java

/**
 * Uncompresses the given zip file. Unfortunately, the files' permission is not
 * preserved, especially with regards to an executable file.
 * @param zipFile       the zip file/*from   www . ja v a  2 s . com*/
 * @param destination   the directory location
 * @throws IOException  IO Exception
 */
private void unzipFile(File zipFile, String destination) throws IOException {
    LOGGER.debug("ics.REST.unzipFile(): Unzipping " + zipFile + " to directory " + destination);
    //LOGGER.debug("ics.REST.unzipFile(): Opening input streams");
    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destinationDirectory = new File(destination);

    while ((entry = zin.getNextEntry()) != null) {
        //LOGGER.debug("ics.REST.unzipFile(): Extracting: " + entry);

        if (entry.isDirectory()) {
            //LOGGER.debug("ics.REST.unzipFile(): Directory found, will be created");
            File targetDirectory = new File(destinationDirectory, entry.getName());
            targetDirectory.mkdir();
        } else {
            // extract data
            // open output streams
            int BUFFER = 2048;

            File destinationFile = new File(destinationDirectory, entry.getName());
            destinationFile.getParentFile().mkdirs();

            //LOGGER.debug("ics.REST.unzipFile(): Creating parent file of destination: "
            //        + destinationFile.getParent());
            //boolean parentDirectoriesCreated = destinationFile.getParentFile().mkdirs();                
            //LOGGER.debug("ics.REST.unzipFile(): Result of creating parents: "
            //        + parentDirectoriesCreated);

            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];

            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zin.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }

    LOGGER.debug("ics.REST.unzipFile(): Unzipping file is done");
    zin.close();
    fis.close();
}

From source file:it.openprj.jValidator.services.ServiceScheduledJob.java

@Override
protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
    JobsEntity jobEntity = jobsDao.find(jobId);
    if (!jobEntity.isWorking()) {

        if (jobsDao.setWorkStatus(jobId, true)) {
            try {
                long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null
                        ? -1l//from   w  ww .j a  va  2 s. c  o  m
                        : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId"));
                if (eventTriggerId > 0) {
                    EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId);
                    String className = entity.getName();
                    try {
                        String sourceCode = entity.getCode();
                        EventTrigger eventTrigger;
                        String response;
                        eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className,
                                "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class,
                                sourceCode);
                        assert eventTrigger != null;
                        response = eventTrigger.trigger();
                        log.info("Response From EventTrigger(" + className + ") :" + response);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("EventTrigger(" + className + ") :" + e.getMessage(), e);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage());
                    } catch (NoClassDefFoundError err) {
                        log.error("EventTrigger(" + className + ") :" + err.getMessage(), err);
                        logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage());
                    }
                    return;
                }

                int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day"));
                int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1
                        : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month"));
                if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH))
                        || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) {
                    return;
                }
                StandardFileSystemManager fsManager = new StandardFileSystemManager();
                boolean isDataStream = true;
                try {
                    fsManager.init();
                    long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId");
                    long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId");
                    //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId");
                    long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId");

                    String datastream = "";
                    int idSchemaType = schemasDao.find(schemaId).getIdSchemaType();

                    TasksEntity taskEntity = tasksDao.find(schedulerId);
                    //JobsEntity jobEntity = jobsDao.find(jobId);
                    if (taskEntity.getIsOneShoot()) {
                        jobEntity.setIsActive(0);
                        jobsDao.update(jobEntity);
                    }
                    if (idSchemaType == SchemaType.GENERATION) {
                        StreamGenerationUtils sgu = new StreamGenerationUtils();
                        datastream = sgu.getStream(schemaId);

                        log.debug("Content stream: " + schemaId);

                        if (datastream.trim().length() > 0) {
                            log.debug("Datastream to validate: " + datastream);
                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                            String result = datastreamsInput.datastreamsInput(datastream, schemaId, null);
                            log.debug("Validation result: " + result);
                        } else {
                            isDataStream = false;
                            log.debug("No datastream create");
                        }
                    }
                    if (connectionId != 0) {
                        int serviceId = Integer
                                .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId"));

                        String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp");
                        String port = arg0.getJobDetail().getJobDataMap().getString("port");
                        String userName = arg0.getJobDetail().getJobDataMap().getString("userName");
                        String password = arg0.getJobDetail().getJobDataMap().getString("password");
                        String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory");
                        String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName");

                        ConnectionsEntity conn;

                        conn = connectionsDao.find(connectionId);

                        if (inputDirectory == null || inputDirectory.trim().length() == 0) {
                            inputDirectory = fileName;
                        } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn
                                && serviceId == Servers.HTTP.getDbCode())) {
                            inputDirectory = inputDirectory + "/" + fileName;
                        }

                        log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server ["
                                + hostName + ":" + port + "] with user[" + userName + "].");
                        String url = "";
                        if (serviceId == Servers.SAMBA.getDbCode()) {
                            if (!fsManager.hasProvider("smb")) {
                                fsManager.addProvider("smb", new SmbFileProvider());
                            }
                            url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        } else if (serviceId == Servers.HTTP.getDbCode()) {
                            if (!fsManager.hasProvider("http")) {
                                fsManager.addProvider("http", new HttpFileProvider());
                            }
                            url = "http://" + hostName + ":" + port + "/" + inputDirectory;
                        } else if (serviceId == Servers.FTP.getDbCode()) {
                            if (!fsManager.hasProvider("ftp")) {
                                fsManager.addProvider("ftp", new FtpFileProvider());
                            }
                            url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/"
                                    + inputDirectory;
                        }
                        log.info("url:" + url);
                        final FileObject fileObject = fsManager.resolveFile(url);

                        if (conn.getIdConnType() == GenericType.DownloadTypeConn) {

                            if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject
                                    .getContent().getLastModifiedTime()) {
                                log.info("There is no New or Updated '" + fileName
                                        + "' file on server to validate. Returning ...");
                                return;
                            } else {
                                log.info("There is New or Updated '" + fileName
                                        + "' file on server to validate. Validating ...");
                                ConnectionsEntity connection = connectionsDao.find(connectionId);
                                connection.setFileDateTime(
                                        new Date(fileObject.getContent().getLastModifiedTime()));
                                ApplicationContext ctx = AppContext.getApplicationContext();
                                ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class));

                                if (connDao != null) {
                                    connDao.update(connection);
                                }

                                Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
                                byte data[] = new byte[(int) fileObject.getContent().getSize()];
                                fileObject.getContent().getInputStream().read(data);
                                resultMap.put(fileObject.getName().getBaseName(), data);

                                Set<String> keySet = resultMap.keySet();
                                Iterator<String> itr = keySet.iterator();
                                while (itr.hasNext()) {

                                    String strFileName = itr.next();
                                    String result = "";
                                    try {

                                        Long longSchemaId = schemaId;
                                        SchemaEntity schemaEntity = schemasDao.find(longSchemaId);
                                        if (schemaEntity == null) {
                                            result = "No schema found in database with Id [" + longSchemaId
                                                    + "]";
                                            log.error(result);
                                            logDao.setErrorLogMessage(result);
                                        } else {
                                            if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                                                // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one
                                                ZipInputStream inStream = null;
                                                try {
                                                    inStream = new ZipInputStream(
                                                            new ByteArrayInputStream(resultMap.get(fileName)));
                                                    ZipEntry entry;
                                                    while (!(isStreamClose(inStream))
                                                            && (entry = inStream.getNextEntry()) != null) {
                                                        if (!entry.isDirectory()) {
                                                            DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                            datastreamsInput
                                                                    .setUploadedFileName(entry.getName());
                                                            byte[] byteInput = IOUtils.toByteArray(inStream);
                                                            result += datastreamsInput.datastreamsInput(
                                                                    new String(byteInput), longSchemaId,
                                                                    byteInput);
                                                        }
                                                        inStream.closeEntry();
                                                    }
                                                    log.debug(result);
                                                } catch (IOException ex) {
                                                    result = "Error occured during fetch records from ZIP file.";
                                                    log.error(result);
                                                    logDao.setErrorLogMessage(result);
                                                } finally {
                                                    if (inStream != null)
                                                        inStream.close();
                                                }
                                            } else {
                                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                                datastreamsInput.setUploadedFileName(strFileName);
                                                result = datastreamsInput.datastreamsInput(
                                                        new String(resultMap.get(strFileName)), longSchemaId,
                                                        resultMap.get(strFileName));
                                                log.debug(result);
                                            }
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        result = "Exception occured during process the message for xml file "
                                                + strFileName + " Error - " + ex.getMessage();
                                        log.error(result);
                                        logDao.setErrorLogMessage(result);
                                    }
                                }
                            }
                        } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) {

                            File uploadFile = File.createTempFile(fileName, ".tmp");

                            try {
                                BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile));
                                bw.write(datastream);
                                bw.flush();
                                bw.close();
                            } catch (IOException ioex) {
                                log.error("Datastream file can't be created");
                                logDao.setErrorLogMessage("Datastream file can't be created");
                                return;
                            }

                            if (serviceId == Servers.HTTP.getDbCode()) {
                                try {
                                    HttpClient httpclient = new HttpClient();
                                    PostMethod method = new PostMethod(url);

                                    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                                            new DefaultHttpMethodRetryHandler(3, false));

                                    Part[] parts = new Part[] {
                                            new FilePart("file", uploadFile.getName(), uploadFile) };
                                    method.setRequestEntity(
                                            new MultipartRequestEntity(parts, method.getParams()));
                                    method.setDoAuthentication(true);

                                    int statusCode = httpclient.executeMethod(method);

                                    String responseBody = new String(method.getResponseBody());

                                    if (statusCode != HttpStatus.SC_OK) {
                                        throw new HttpException(method.getStatusLine().toString());
                                    } else {
                                        System.out.println(responseBody);
                                    }

                                    method.releaseConnection();

                                } catch (Exception ex) {
                                    log.error("Exception occurred during uploading of file at HTTP Server: "
                                            + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file at HTTP Server: "
                                                    + ex.getMessage());
                                }
                            } else {
                                try {
                                    FileObject localFileObject = fsManager
                                            .resolveFile(uploadFile.getAbsolutePath());
                                    fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
                                    System.out.println("File uploaded at : " + new Date());
                                    if (uploadFile.exists()) {
                                        uploadFile.delete();
                                    }
                                } catch (Exception ex) {
                                    log.error(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                    logDao.setErrorLogMessage(
                                            "Exception occurred during uploading of file: " + ex.getMessage());
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    log.error("Error " + ": " + ex.getMessage());
                } finally {
                    fsManager.close();
                }
            } finally {
                jobsDao.setWorkStatus(jobId, false);
            }
        } else {
            log.error("Can not set " + jobEntity.getName() + "working.");
        }
    } else {
        log.debug("Job " + jobEntity.getName() + " is working.");
    }

}

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void registerApp(AppInfo appInfo, byte[] appPackage) throws Exception {
    System.out.println("REGISTER REQUEST RECEIVED ");
    // appPackage should be received as a zip file. extract this to the apps
    // directory, and write appinfo to a json file under config/
    File appHomeDir = getAppConfigDirectory();
    if (!appHomeDir.exists()) {
        appHomeDir.mkdirs();/*from   w w w .  ja  v  a2  s.c om*/
        if (!appHomeDir.exists()) {
            // if it still doesn't exist throw an error
            throw new Exception(
                    "App home directory does not exist and cannot be created " + appHomeDir.getAbsolutePath());
        }
    }
    System.out.println("HOME DIR " + appHomeDir.getAbsolutePath());
    // create a directory for the app
    File newAppDir = new File(appHomeDir.getAbsolutePath() + File.separator + appInfo.getId());
    if (newAppDir.exists()) {
        throw new Exception("App " + appInfo.getId() + " already exists");
    }

    try {
        newAppDir.mkdirs();
        // Extract zip file into new app dir
        ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(appPackage));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file and write to dir
        while (entry != null) {
            String filePath = newAppDir + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();

        writeAppInfo(appInfo);

        // add to apps hashmap
        apps.put(appInfo.getId(), appInfo);
    } catch (Exception e) {
        // Clean up app dir if fails
        newAppDir.delete();
        throw e;
    }
}

From source file:net.rptools.lib.io.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;/*from www  .  j  a  va 2 s. c  om*/

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    InputStream is = null;

    // Create the new file
    File newFile = new File(tmpDir, new GUID() + ".pak");
    ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
    try {
        saveTimer.start(CONTENT_FILE);
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            is = getFileAsInputStream(CONTENT_FILE); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop(CONTENT_FILE);

        saveTimer.start(PROPERTY_FILE);
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            xstream.toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop(PROPERTY_FILE);

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            is = getFileAsInputStream(path); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    //                  if (entry.getName().endsWith(".png") ||
                    //                        entry.getName().endsWith(".gif") ||
                    //                        entry.getName().endsWith(".jpeg"))
                    //                     zout.setLevel(Deflater.NO_COMPRESSION); // none needed for images as they are already compressed
                    //                  else
                    //                     zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
                    zout.putNextEntry(entry);
                    is = getFileAsInputStream(entry.getName()); // When copying, always use an InputStream
                    IOUtils.copy(is, zout);
                    IOUtils.closeQuietly(is);
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        IOUtils.closeQuietly(zout);
        zout = null;
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir, new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                saveTimer.start("backup file");
                FileUtil.copyFile(file, backupFile);
                file.delete();
                saveTimer.stop("backup file");
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file)) {
            saveTimer.start("backup newFile");
            FileUtil.copyFile(newFile, file);
            saveTimer.stop("backup newFile");
        }
        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zout);
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void validateSkinZip(File file) throws SkinException {
    ZipFile myZipFile = null;//from w  w w .  j a  v  a  2 s  . c o  m
    try {
        boolean isToolFound = false;
        boolean isPortalFound = false;
        boolean isImagesFound = false;
        myZipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> myEntries = myZipFile.entries();
        while (myEntries.hasMoreElements()) {
            ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement();
            String myName = myZipEntry.getName();
            if (myName.contains("..") || myName.startsWith("/")) {
                throw new SkinException("Illegal file name found in zip file '" + myName + "'");
            }
            if (!myZipEntry.isDirectory()) {
                if (myName.equals("tool.css")) {
                    isToolFound = true;
                } else if (myName.equals("portal.css")) {
                    isPortalFound = true;
                } else if (PATTERN_IMAGES_DIR_CONTENT.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            } else {
                if (PATTERN_IMAGES_DIR_EMPTY.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            }
        }

        if (!isPortalFound) {
            throw getMissingResourceException("portal.css", false);
        }
        if (!isToolFound) {
            throw getMissingResourceException("tool.css", false);
        }
        if (!isImagesFound) {
            throw getMissingResourceException("images", true);
        }
    } catch (ZipException z) {
        throw new SkinException("Error reading zip file", z);
    } catch (IOException e) {
        throw new SkinException("IO Error reading zip file", e);
    } finally {
        if (myZipFile != null) {
            try {
                myZipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }

    }

}

From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java

private byte[] extractBar(File barFile) {
    ZipFile zipFile = null;/*from  w  w w .ja v a 2s  .  com*/
    InputStream entryInputStream = null;
    byte[] processBytes = null;
    try {
        zipFile = new ZipFile(barFile);

        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                if (entry.getName().endsWith(".proc")) { //$NON-NLS-1$
                    entryInputStream = zipFile.getInputStream(entry);
                    processBytes = IOUtils.toByteArray(entryInputStream);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (entryInputStream != null) {
            try {
                entryInputStream.close();
            } catch (IOException e) {
            }
        }
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }

    }
    return processBytes;
}

From source file:com.htmlhifive.tools.wizard.download.DownloadModule.java

/**
 * ?.//from w w w. ja va 2 s.c o m
 * 
 * @param monitor 
 * @param totalTask 
 * @param logger 
 * @param baseProject 
 * @param proj 
 * @throws CoreException 
 */
public void downloadProject(IProgressMonitor monitor, int totalTask, ResultStatus logger,
        BaseProject baseProject, IProject proj) throws CoreException {

    // ??400work.
    int perLibWork = totalTask;

    // SE0063=INFO,ZIP???
    logger.log(Messages.SE0063);

    // ??
    // ?????????.
    defaultOverwriteMode = 1;

    String siteUrl = baseProject.getUrl();
    String path = H5IOUtils.getURLPath(siteUrl);
    if (path == null) {
        logger.log(Messages.SE0082, baseProject.getUrl());
        logger.setSuccess(false);
        throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(),
                Messages.SE0082.format(baseProject.getUrl())));
    }

    final ZipFile zipFile;
    //try {
    //URI uri = new URI(baseProject.getUrl());
    zipFile = download(monitor, totalTask, logger, null, siteUrl);
    //} catch (URISyntaxException e) {
    //throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0013.format(), e));
    //}

    perLibWork = perLibWork - 100;
    if (!lastDownloadStatus) {
        // .
        logger.log(Messages.SE0068);
        logger.setSuccess(false);
        throw new CoreException(new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0068.format()));
    }

    // SE0064=INFO,ZIP????
    logger.log(Messages.SE0064);

    // .
    //proj.refreshLocal(IResource.DEPTH_ONE, monitor);
    //logger.log(Messages.SE0101);

    // ?
    int perExtractWork = Math.max(1, perLibWork / zipFile.size());
    for (Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); enumeration.hasMoreElements();) {
        final ZipEntry zipEntry = enumeration.nextElement();

        // PI0113=INFO,[{0}]...
        monitor.subTask(Messages.PI0113.format(zipEntry.getName()));

        if (zipEntry.isDirectory()) {
            // 
            IFolder iFolder = proj.getFolder(zipEntry.getName());
            if (!iFolder.exists()) {
                logger.log(Messages.SE0091, iFolder.getFullPath());
                H5IOUtils.createParentFolder(iFolder, null);
                logger.log(Messages.SE0092, iFolder.getFullPath());
            }
        } else {
            // 
            IFile iFile = proj.getFile(zipEntry.getName());

            // ?.
            try {
                updateFile(monitor, 0, logger, iFile, new ZipFileContentsHandler(zipFile, zipEntry));
            } catch (IOException e) {
                throw new CoreException(
                        new Status(IStatus.ERROR, H5WizardPlugin.getId(), Messages.SE0068.format(), e));
            }
        }
        monitor.worked(perExtractWork);
    }

    // //  ZIP???????.
    // H5StringUtils.log(getShell(), null, Messages.SE0043,
    // Messages.SE0045.format(site.getFile()));

    // ??.
    defaultOverwriteMode = 0;

    logger.log(Messages.SE0070);
}

From source file:brut.androlib.Androlib.java

private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile) throws IOException {
    // First, copy the contents from the existing outFile:
    Enumeration<? extends ZipEntry> entries = inputFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = new ZipEntry(entries.nextElement());

        // We can't reuse the compressed size because it depends on compression sizes.
        entry.setCompressedSize(-1);/*from   w ww  . ja  v a  2 s.  com*/
        outputFile.putNextEntry(entry);

        // No need to create directory entries in the final apk
        if (!entry.isDirectory()) {
            BrutIO.copy(inputFile, outputFile, entry);
        }

        outputFile.closeEntry();
    }
}

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  w w  w.  j  av  a 2  s  .  c  o  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(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:com.orange.mmp.midlet.MidletManager.java

/**
 * Deploy a midlet archive file on PFS// w w w . j  a v  a  2  s  . c  o m
 * @param midletFile The midlet file (ZIP file)
 */
@SuppressWarnings("unchecked")
public void deployMidlet(File midletFile) throws MMPException {
    try {
        File tmpDeployDir = new File(System.getProperty("java.io.tmpdir"), "tmpDeployDir");
        FileUtils.deleteDirectory(tmpDeployDir);
        FileUtils.forceMkdir(tmpDeployDir);

        ZipInputStream zip = new ZipInputStream(new FileInputStream(midletFile));
        ZipEntry entry;
        try {
            while ((entry = zip.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    File repFile = new File(tmpDeployDir, entry.getName());
                    repFile.mkdirs();
                } else {
                    String filename = entry.getName();
                    File entryFile = new File(tmpDeployDir, filename);
                    FileOutputStream fos = new FileOutputStream(entryFile);
                    try {
                        IOUtils.copy(zip, fos);
                    } finally {
                        fos.close();
                    }
                }
            }
        } finally {
            zip.closeEntry();
        }

        List<Midlet> midletList = new ArrayList<Midlet>();
        Collection<File> filesList = FileUtils.listFiles(tmpDeployDir, new String[] { "jar", "jad" }, true);

        for (File currentfile : filesList) {
            String midletType = null;
            String midletFilename = null;
            if (currentfile.getParentFile().getAbsolutePath().equals(tmpDeployDir.getAbsolutePath())) {
                midletType = currentfile.getName().split("\\.")[0];
            } else {
                midletType = currentfile.getParentFile().getName();
            }

            midletFilename = currentfile.getName();

            if (midletType != null) {
                boolean found = false;
                for (Midlet midlet : midletList) {
                    found = false;
                    if (midlet.getType().equals(midletType)) {
                        if (midlet.getJadLocation() == null)
                            midlet.setJadLocation(currentfile.toURI().toString());
                        else
                            midlet.setJarLocation(currentfile.toURI().toString());
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    Midlet midlet = new Midlet();
                    midlet.setType(midletType);
                    if (midletFilename.endsWith("jad"))
                        midlet.setJadLocation(currentfile.toURI().toString());
                    else
                        midlet.setJarLocation(currentfile.toURI().toString());
                    midletList.add(midlet);
                }
            }
        }

        for (Midlet midlet : midletList) {
            DaoManagerFactory.getInstance().getDaoManager().getDao("midlet").createOrUdpdate(midlet);
        }

        FileUtils.deleteDirectory(tmpDeployDir);
    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy PFM", ioe);
    }
}