Example usage for java.util.zip ZipInputStream closeEntry

List of usage examples for java.util.zip ZipInputStream closeEntry

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream closeEntry.

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.candlepin.sync.ExporterTest.java

/**
 * return true if export has a given entry named name.
 * @param export zip file to inspect/*  w  w w . j  a v a  2 s  .c  om*/
 * @param name entry
 * @return
 */
private boolean verifyHasEntry(File export, String name) {
    ZipInputStream zis = null;
    boolean found = false;

    try {
        zis = new ZipInputStream(new FileInputStream(export));
        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            byte[] buf = new byte[1024];

            if (entry.getName().equals("consumer_export.zip")) {
                OutputStream os = new FileOutputStream("/tmp/consumer_export.zip");

                int n;
                while ((n = zis.read(buf, 0, 1024)) > -1) {
                    os.write(buf, 0, n);
                }
                os.flush();
                os.close();
                File exportdata = new File("/tmp/consumer_export.zip");
                // open up the zip and look for the metadata
                verifyHasEntry(exportdata, name);
            } else if (entry.getName().equals(name)) {
                found = true;
            }

            zis.closeEntry();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return found;
}

From source file:org.saiku.web.rest.resources.BasicRepositoryResource2.java

/**
 * Upload a zip archive to the server.// w  ww. j  a v  a2s  . c o m
 * @param test Not used.
 * @param uploadedInputStream File Info
 * @param fileDetail File Info
 * @param directory Location
 * @return A response status 200
 */
@POST
@Path("/zipupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadArchiveZip(@QueryParam("test") String test,
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("directory") String directory) {
    String zipFile = fileDetail.getFileName();
    String output = "";
    try {
        if (StringUtils.isBlank(zipFile))
            throw new Exception("You must specify a zip file to upload");

        output = "Uploding file: " + zipFile + " ...\r\n";
        ZipInputStream zis = new ZipInputStream(uploadedInputStream);
        ZipEntry ze = zis.getNextEntry();
        byte[] doc = null;
        boolean isFile = false;
        if (ze == null) {
            doc = IOUtils.toByteArray(uploadedInputStream);
            isFile = true;
        }
        while (ze != null || doc != null) {
            String fileName = null;
            if (!isFile) {
                fileName = ze.getName();
                doc = IOUtils.toByteArray(zis);
            } else {
                fileName = zipFile;
            }

            output += "Saving " + fileName + "... ";
            String fullPath = (StringUtils.isNotBlank(directory)) ? directory + "/" + fileName : fileName;

            String content = new String(doc);
            Response r = saveResource(fullPath, content);
            doc = null;

            if (Status.OK.getStatusCode() != r.getStatus()) {
                output += " ERROR: " + r.getEntity().toString() + "\r\n";
            } else {
                output += " OK\r\n";
            }
            if (!isFile)
                ze = zis.getNextEntry();
        }

        if (!isFile) {
            zis.closeEntry();
            zis.close();
        }
        uploadedInputStream.close();

        output += " SUCCESSFUL!\r\n";
        return Response.ok(output).build();

    } catch (Exception e) {
        log.error("Cannot unzip resources " + zipFile, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(output + "\r\n" + error).build();
    }

}

From source file:org.wso2.carbon.bridge.EquinoxFrameworkLauncher.java

/**
 * Extract an archive to the target location
 *
 * @param compressFilePath - Archive path
 * @param target           - Location to extract
 *///from   w  w w.  jav  a 2  s .c o  m
protected void extractResource(String compressFilePath, File target) {
    try {
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(context.getResourceAsStream(compressFilePath));

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            String entryName = zipentry.getName();
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(entryName);
            String directory = newFile.getParent();

            if (directory == null) {
                if (newFile.isDirectory())
                    break;
            }

            if (zipentry.isDirectory()) {
                zipinputstream.closeEntry();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.isDirectory())
                break;
            File outputFile = new File(target.getPath(), entryName);
            if (outputFile.getParentFile() != null && !outputFile.getParentFile().mkdirs()) {
                throw new IOException(
                        "Fail to create the directory: " + outputFile.getParentFile().getAbsolutePath());
            }
            fileoutputstream = new FileOutputStream(outputFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
                fileoutputstream.write(buf, 0, n);

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }

        zipinputstream.close();
    } catch (Exception ignored) {
        //ignore invalid compress file
        context.log(ignored.getMessage(), ignored);
    }
}

From source file:org.gradle.api.plugins.buildcomparison.outcome.internal.archive.entry.FileToArchiveEntrySetTransformer.java

private ImmutableSet<ArchiveEntry> walk(InputStream archiveInputStream,
        ImmutableSet.Builder<ArchiveEntry> allEntries, ImmutableList<String> parentPaths) {
    ImmutableSet.Builder<ArchiveEntry> entries = ImmutableSet.builder();
    ZipInputStream zipStream = new ZipInputStream(archiveInputStream);

    try {//from w w w .  jav a  2 s . c  om
        ZipEntry entry = zipStream.getNextEntry();
        while (entry != null) {
            ArchiveEntry.Builder builder = new ArchiveEntry.Builder();
            builder.setParentPaths(parentPaths);
            builder.setPath(entry.getName());
            builder.setCrc(entry.getCrc());
            builder.setDirectory(entry.isDirectory());
            builder.setSize(entry.getSize());
            if (!builder.isDirectory() && (zipStream.available() == 1)) {
                boolean zipEntry;
                final BufferedInputStream bis = new BufferedInputStream(zipStream) {
                    @Override
                    public void close() throws IOException {
                    }
                };
                bis.mark(Integer.MAX_VALUE);
                zipEntry = new ZipInputStream(bis).getNextEntry() != null;
                bis.reset();
                if (zipEntry) {
                    ImmutableList<String> nextParentPaths = ImmutableList.<String>builder().addAll(parentPaths)
                            .add(entry.getName()).build();
                    ImmutableSet<ArchiveEntry> subEntries = walk(bis, allEntries, nextParentPaths);
                    builder.setSubEntries(subEntries);
                }
            }

            ArchiveEntry archiveEntry = builder.build();
            entries.add(archiveEntry);
            allEntries.add(archiveEntry);
            zipStream.closeEntry();
            entry = zipStream.getNextEntry();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(zipStream);
    }

    return entries.build();
}

From source file:util.TraversalZipTool.java

/**
 * Returns the zip entries as Media beans.
 *
 * @param zipBytes//from  ww w .j ava  2s .c om
 * @return List of Media beans
 */
public List getEntries(byte[] zipBytes) throws SomeZipException {

    ByteArrayInputStream bis = null;
    ZipInputStream zis = null;
    ZipEntry zipEntry = null;
    List entries = new ArrayList();
    byte[] b = null;

    try {
        bis = new ByteArrayInputStream(zipBytes);
        zis = new ZipInputStream(bis);
        boolean notDone = true;
        zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            if (zipEntry.isDirectory()) {
                zipEntry = zis.getNextEntry();
                continue;
            }
            b = new byte[MAX_MEDIA_SIZE];
            int offset = 0;
            int rb = 0;
            while ((zis.available() != 0) && ((rb = zis.read(b, offset, CHUNK)) != -1)) {
                offset += rb;
            }
            if ((zis.available() == 0) || (rb == -1)) {
                String entryName = zipEntry.getName();
                String suffix = getSuffix(entryName);
                if (validImage.isValidSuffix(suffix)) {
                    Media media = new Media();
                    //logger.info("Found New Image " + offset + " bytes");
                    media.setData(new String(b, 0, offset).getBytes());
                    media.setSize(offset);
                    //logger.info("ZipEntry name = " + entryName);
                    media.setName(fileName(entryName));
                    entries.add(media);
                } else {
                    logger.warn("Bad image file in zip, ignoring " + entryName);
                }
                zis.closeEntry();
                zipEntry = zis.getNextEntry();
            }
        }
        zis.close();
    } catch (Exception e) {
        throw new SomeZipException("Error processing zip bytes", e);
    }
    return entries;
}

From source file:util.CreationZipTool.java

/**
 * Returns the zip entries as Media beans.
 *
 * @param zipBytes/* w  w w. j  a va  2s . com*/
 * @return List of Media beans
 */
public List getEntries(byte[] zipBytes) throws SomeZipException {

    ByteArrayInputStream bis = null;
    ZipInputStream zis = null;
    ZipEntry zipEntry = null;
    List entries = new ArrayList();
    byte[] b = null;

    try {
        bis = new ByteArrayInputStream(zipBytes);
        zis = new ZipInputStream(bis);
        boolean notDone = true;
        zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            if (zipEntry.isDirectory()) {
                zipEntry = zis.getNextEntry();
                continue;
            }
            b = new byte[MAX_MEDIA_SIZE];
            int offset = 0;
            int rb = 0;
            while ((zis.available() != 0) && ((rb = zis.read(b, offset, CHUNK)) != -1)) {
                offset += rb;
            }
            if ((zis.available() == 0) || (rb == -1)) {
                String entryName = zipEntry.getName();
                String suffix = getSuffix(entryName);
                //if (validImage.isValidSuffix(suffix)) {
                Media media = new Media();
                logger.info("Found New Image " + offset + " bytes");
                media.setData(new String(b, 0, offset).getBytes());
                media.setSize(offset);
                logger.info("ZipEntry name = " + entryName);
                media.setName(fileName(entryName));
                entries.add(media);
                //} else {
                //logger.warn("Bad image file in zip, ignoring " + entryName);
                //}
                zis.closeEntry();
                zipEntry = zis.getNextEntry();
            }
        }
        zis.close();
    } catch (Exception e) {
        throw new SomeZipException("Error processing zip bytes", e);
    }
    return entries;
}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@POST
@Path("/zipupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadArchiveZip(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("directory") String directory) {
    String zipFile = fileDetail.getFileName();
    String output = "";
    try {/*from   w w  w.ja v  a 2 s.co  m*/
        if (StringUtils.isBlank(zipFile))
            throw new Exception("You must specify a zip file to upload");

        output = "Uploding file: " + zipFile + " ...\r\n";
        ZipInputStream zis = new ZipInputStream(uploadedInputStream);
        ZipEntry ze = zis.getNextEntry();
        byte[] doc = null;
        boolean isFile = false;
        if (ze == null) {
            doc = IOUtils.toByteArray(uploadedInputStream);
            isFile = true;
        }
        while (ze != null || doc != null) {
            String fileName = null;
            if (!isFile) {
                fileName = ze.getName();
                doc = IOUtils.toByteArray(zis);
            } else {
                fileName = zipFile;
            }

            output += "Saving " + fileName + "... ";
            String fullPath = (StringUtils.isNotBlank(directory)) ? directory + "/" + fileName : fileName;

            String content = new String(doc);
            Response r = saveResource(fullPath, content);
            doc = null;

            if (Status.OK.getStatusCode() != r.getStatus()) {
                output += " ERROR: " + r.getEntity().toString() + "\r\n";
            } else {
                output += " OK\r\n";
            }
            if (!isFile)
                ze = zis.getNextEntry();
        }

        if (!isFile) {
            zis.closeEntry();
            zis.close();
        }
        uploadedInputStream.close();

        output += " SUCCESSFUL!\r\n";
        return Response.ok(output).build();

    } catch (Exception e) {
        log.error("Cannot unzip resources " + zipFile, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(output + "\r\n" + error).build();
    }
}

From source file:org.artifactory.webapp.wicket.page.importexport.repos.ImportZipPanel.java

@Override
public void onFileSaved(File file) {
    ZipInputStream zipinputstream = null;
    FileOutputStream fos = null;//from ww  w  . j av  a  2  s.  com
    File uploadedFile = null;
    File destFolder;
    try {
        uploadedFile = uploadForm.getUploadedFile();
        zipinputstream = new ZipInputStream(new FileInputStream(uploadedFile));
        ArtifactoryHome artifactoryHome = ContextHelper.get().getArtifactoryHome();
        destFolder = new File(artifactoryHome.getTempUploadDir(), uploadedFile.getName() + "_extract");
        FileUtils.deleteDirectory(destFolder);

        byte[] buf = new byte[DEFAULT_BUFF_SIZE];
        ZipEntry zipentry;

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = zipentry.getName();
            File destFile = new File(destFolder, entryName);

            if (zipentry.isDirectory()) {
                if (!destFile.exists()) {
                    if (!destFile.mkdirs()) {
                        error("Cannot create directory " + destFolder);
                        return;
                    }
                }
            } else {
                fos = new FileOutputStream(destFile);
                int n;
                while ((n = zipinputstream.read(buf, 0, DEFAULT_BUFF_SIZE)) > -1) {
                    fos.write(buf, 0, n);
                }
                fos.close();
            }
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        } //while

        setImportFromPath(destFolder);
        getImportForm().setVisible(true);
    } catch (Exception e) {
        String errorMessage = "Error during import of " + uploadedFile;
        String systemLogsPage = WicketUtils.absoluteMountPathForPage(SystemLogsPage.class);
        String logs = ". Please review the <a href=\"" + systemLogsPage + "\">log</a> for further information.";
        error(new UnescapedFeedbackMessage(errorMessage + logs));
        log.error(errorMessage, e);
        onException();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(zipinputstream);
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.TestPipeLineExecute.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    // Initialize action
    initAction(request);/*from   ww  w .  ja va 2 s . c o  m*/
    if (null == config) {
        return (mapping.findForward("noconfig"));
    }

    if (isCancelled(request)) {
        return (mapping.findForward("success"));
    }

    DynaActionForm pipeLineTestForm = (DynaActionForm) form;
    String form_adapterName = (String) pipeLineTestForm.get("adapterName");
    String form_message = (String) pipeLineTestForm.get("message");
    String form_resultText = "";
    String form_resultState = "";
    FormFile form_file = (FormFile) pipeLineTestForm.get("file");

    // if no message and no formfile, send an error
    if (StringUtils.isEmpty(form_message) && (form_file == null || form_file.getFileSize() == 0)) {

        storeFormData(null, null, null, pipeLineTestForm);
        warn("Nothing to send or test");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, null, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    if ((form_adapterName == null) || (form_adapterName.length() == 0)) {
        warn("No adapter selected");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }
    // Execute the request
    IAdapter adapter = config.getRegisteredAdapter(form_adapterName);
    if (adapter == null) {
        warn("Adapter with specified name [" + form_adapterName + "] could not be retrieved");
    }
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        storeFormData(null, null, form_message, pipeLineTestForm);
        return (new ActionForward(mapping.getInput()));
    }

    // if upload is choosen, it prevails over the message
    if ((form_file != null) && (form_file.getFileSize() > 0)) {
        log.debug("Upload of file [" + form_file.getFileName() + "] ContentType[" + form_file.getContentType()
                + "]");
        if (FileUtils.extensionEqualsIgnoreCase(form_file.getFileName(), "zip")) {
            ZipInputStream archive = new ZipInputStream(new ByteArrayInputStream(form_file.getFileData()));
            for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
                String name = entry.getName();
                int size = (int) entry.getSize();
                if (size > 0) {
                    byte[] b = new byte[size];
                    int rb = 0;
                    int chunk = 0;
                    while (((int) size - rb) > 0) {
                        chunk = archive.read(b, rb, (int) size - rb);
                        if (chunk == -1) {
                            break;
                        }
                        rb += chunk;
                    }
                    String currentMessage = XmlUtils.readXml(b, 0, rb, request.getCharacterEncoding(), false);
                    //PipeLineResult pipeLineResult = adapter.processMessage(name+"_" + Misc.createSimpleUUID(), currentMessage);
                    PipeLineResult pipeLineResult = processMessage(adapter,
                            name + "_" + Misc.createSimpleUUID(), currentMessage);
                    form_resultText += name + ":" + pipeLineResult.getState() + "\n";
                    form_resultState = pipeLineResult.getState();
                }
                archive.closeEntry();
            }
            archive.close();
            form_message = null;
        } else {
            form_message = XmlUtils.readXml(form_file.getFileData(), request.getCharacterEncoding(), false);
        }
    } else {
        form_message = new String(form_message.getBytes(), Misc.DEFAULT_INPUT_STREAM_ENCODING);
    }

    if (form_message != null && form_message.length() > 0) {
        // Execute the request
        //PipeLineResult pipeLineResult = adapter.processMessage("testmessage" + Misc.createSimpleUUID(), form_message);
        PipeLineResult pipeLineResult = processMessage(adapter, "testmessage" + Misc.createSimpleUUID(),
                form_message);
        form_resultText = pipeLineResult.getResult();
        form_resultState = pipeLineResult.getState();
    }
    storeFormData(form_resultText, form_resultState, form_message, pipeLineTestForm);

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(request, errors);
        return (new ActionForward(mapping.getInput()));
    }

    // Forward control to the specified success URI
    log.debug("forward to success");
    return (mapping.findForward("success"));

}

From source file:org.wso2.carbon.connector.util.FileUnzipUtil.java

/**
 * @param source        Location of the zip file
 * @param destDirectory Location of the destination folder
 *//*from  w  ww.  j ava  2  s  . c  o  m*/
public boolean unzip(String source, String destDirectory, MessageContext messageContext) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
    OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
    boolean resultStatus = false;
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    try {
        manager = FileConnectorUtils.getManager();
        // Create remote object
        FileObject remoteFile = manager.resolveFile(source, opts);
        FileObject remoteDesFile = manager.resolveFile(destDirectory, opts);
        // File destDir = new File(destDirectory);
        if (remoteFile.exists()) {
            if (!remoteDesFile.exists()) {
                //create a folder
                remoteDesFile.createFolder();
            }
            //open the zip file
            ZipInputStream zipIn = new ZipInputStream(remoteFile.getContent().getInputStream());
            ZipEntry entry = zipIn.getNextEntry();
            try {
                // iterates over entries in the zip file
                while (entry != null) {
                    // boolean testResult;
                    String filePath = destDirectory + File.separator + entry.getName();
                    // Create remote object
                    FileObject remoteFilePath = manager.resolveFile(filePath, opts);
                    if (log.isDebugEnabled()) {
                        log.debug("The created path is " + remoteFilePath.toString());
                    }
                    try {
                        if (!entry.isDirectory()) {
                            // if the entry is a file, extracts it
                            extractFile(zipIn, filePath, opts);
                            OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                            messageElement.setText(entry.getName() + " | status:" + "true");
                            result.addChild(messageElement);
                        } else {
                            // if the entry is a directory, make the directory
                            remoteFilePath.createFolder();
                        }
                    } catch (IOException e) {
                        log.error("Unable to process the zip file. ", e);
                    } finally {
                        zipIn.closeEntry();
                        entry = zipIn.getNextEntry();
                    }
                }
                messageContext.getEnvelope().getBody().addChild(result);
                resultStatus = true;
            } finally {
                //we must always close the zip file
                zipIn.close();
            }
        } else {
            log.error("File does not exist.");
        }
    } catch (IOException e) {
        log.error("Unable to process the zip file." + e.getMessage(), e);
    } finally {
        manager.close();
    }
    return resultStatus;
}