Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:com.marklogic.contentpump.ZipDelimitedJSONReader.java

protected boolean hasMoreEntryInZip() throws IOException {
    ByteArrayOutputStream byteArrayOStream;
    ZipInputStream zipIStream = (ZipInputStream) zipIn;

    while ((currZipEntry = zipIStream.getNextEntry()) != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("ZipEntry: " + currZipEntry.getName());
        }/*from   w w  w.  j  a v  a  2s .  com*/
        if (currZipEntry.getSize() == 0) {
            continue;
        }
        subId = currZipEntry.getName();
        long size = currZipEntry.getSize();
        if (size == -1) {
            byteArrayOStream = new ByteArrayOutputStream();
        } else {
            byteArrayOStream = new ByteArrayOutputStream((int) size);
        }
        int numOfBytes = -1;
        while ((numOfBytes = zipIStream.read(buf, 0, buf.length)) != -1) {
            byteArrayOStream.write(buf, 0, numOfBytes);
        }
        configFileNameAsCollection(conf, file);
        instream = new InputStreamReader(new ByteArrayInputStream(byteArrayOStream.toByteArray()), encoding);
        byteArrayOStream.close();
        reader = new LineNumberReader(instream);
        return true;
    }
    return false;
}

From source file:org.vietspider.server.handler.cms.metas.EditContentHandler.java

private byte[] loadZipEntry(File file, String fileName) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipInputStream zipInput = null;
    try {/*  w  ww . j a  v a  2 s .c  o  m*/
        zipInput = new ZipInputStream(new FileInputStream(file));
        int read = -1;
        byte[] bytes = new byte[4 * 1024];

        ZipEntry entry = null;
        while (true) {
            entry = zipInput.getNextEntry();
            if (entry == null)
                break;
            if (entry.getName().equalsIgnoreCase(fileName)) {
                while ((read = zipInput.read(bytes, 0, bytes.length)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                break;
            }
        }
        zipInput.close();
    } finally {
        try {
            if (zipInput != null)
                zipInput.close();
        } catch (Exception e) {
        }
    }
    return outputStream.toByteArray();
}

From source file:util.CreationZipTool.java

/**
 * Returns the zip entries as Media beans.
 *
 * @param zipBytes//from www  . j  a  va2 s.c  o  m
 * @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.stanwood.media.util.FileHelper.java

/**
 * Used to unzip a file to a directory//from   w  w w .  ja va  2  s .c om
 * @param is The input stream containing the file
 * @param destDir The directory to unzip to
 * @throws IOException Thrown if their are any problems
 */
public static void unzip(InputStream is, File destDir) throws IOException {
    ZipInputStream zis = null;
    try {
        zis = new ZipInputStream(is);
        ZipEntry entry = null;
        while ((entry = zis.getNextEntry()) != null) {
            File file = new File(destDir, entry.getName());
            if (entry.isDirectory()) {
                if (!file.mkdir() && file.exists()) {
                    throw new IOException("Unable to create directory: " + file); //$NON-NLS-1$
                }
            } else {
                BufferedOutputStream out = null;
                try {
                    int count;
                    byte data[] = new byte[1000];
                    out = new BufferedOutputStream(new FileOutputStream(new File(destDir, entry.getName())),
                            1000);
                    if (log.isDebugEnabled()) {
                        log.debug("Unzipping " + entry.getName() + " with size " + entry.getSize()); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    while ((count = zis.read(data, 0, 1000)) != -1) {
                        out.write(data, 0, count);
                    }
                    out.flush();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        }
    } finally {
        if (zis != null) {
            zis.close();
        }
    }
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public String getEnvironmentFile(String environmentName, ApplicationPackage appPackage) {
    ZipInputStream zipStream = getNewUtf8ZipInputStream(appPackage);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {/*  www. j  av  a  2  s.c om*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (getBaseName(zipEntry.getName()).equals(environmentName)) {

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                zipStream.closeEntry();

                // Stop here because the file has been already read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackage.getPackageFile().reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return output.toString();
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public Map<String, InputStream> getPackages(ApplicationPackage appPackage) {
    Map<String, InputStream> packages = new HashMap<>();
    ZipInputStream zipStream = getNewUtf8ZipInputStream(appPackage);

    try {//from  w w w.j ava2s . c  o  m
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (zipEntry.getName().startsWith("packages/")) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                String packageFileName = zipEntry.getName().replace("packages/", "");
                packages.put(packageFileName, new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackage.getPackageFile().reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return packages;
}

From source file:org.intermine.api.lucene.KeywordSearch.java

private static FSDirectory readFSDirectory(String path, InputStream is)
        throws IOException, FileNotFoundException {
    long time = System.currentTimeMillis();
    final int bufferSize = 2048;
    File directoryPath = new File(path + File.separator + LUCENE_INDEX_DIR);
    LOG.debug("Directory path: " + directoryPath);

    // make sure we start with a new index
    if (directoryPath.exists()) {
        String[] files = directoryPath.list();
        for (int i = 0; i < files.length; i++) {
            LOG.info("Deleting old file: " + files[i]);
            new File(directoryPath.getAbsolutePath() + File.separator + files[i]).delete();
        }//from w  ww.  j  a  v  a 2  s.  com
    } else {
        directoryPath.mkdir();
    }

    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    try {
        while ((entry = zis.getNextEntry()) != null) {
            LOG.info("Extracting: " + entry.getName() + " (" + entry.getSize() + " MB)");

            FileOutputStream fos = new FileOutputStream(
                    directoryPath.getAbsolutePath() + File.separator + entry.getName());
            BufferedOutputStream bos = new BufferedOutputStream(fos, bufferSize);

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

            try {
                while ((count = zis.read(data, 0, bufferSize)) != -1) {
                    bos.write(data, 0, count);
                }
            } finally {
                bos.flush();
                bos.close();
            }
        }
    } finally {
        zis.close();
    }

    FSDirectory directory = FSDirectory.open(directoryPath);

    LOG.info("Successfully restored FS directory from database in " + (System.currentTimeMillis() - time)
            + " ms");
    return directory;
}

From source file:org.springframework.roo.addon.roobot.eclipse.client.AddOnRooBotEclipseOperationsImpl.java

private boolean verifyRepository(String repoUrl) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc = null;//  w w  w .jav  a2  s .  c o m
    try {
        URL obrUrl = null;
        obrUrl = new URL(repoUrl);
        DocumentBuilder db = dbf.newDocumentBuilder();
        if (obrUrl.toExternalForm().endsWith(".zip")) {
            ZipInputStream zip = new ZipInputStream(obrUrl.openStream());
            zip.getNextEntry();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int length = -1;
            while (zip.available() > 0) {
                length = zip.read(buffer, 0, 8192);
                if (length > 0) {
                    baos.write(buffer, 0, length);
                }
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            doc = db.parse(bais);
        } else {
            doc = db.parse(obrUrl.openStream());
        }
        Validate.notNull(doc, "RooBot was unable to parse the repository document of this add-on");
        for (Element resource : XmlUtils.findElements("resource", doc.getDocumentElement())) {
            if (resource.hasAttribute("uri")) {
                if (!resource.getAttribute("uri").startsWith("httppgp")) {
                    log.warning("Sorry, the resource " + resource.getAttribute("uri")
                            + " does not follow HTTPPGP conventions mangraded by Spring Roo so the OBR file at "
                            + repoUrl + " is unacceptable at this time");
                    return false;
                }
            }
        }
        doc = null;
    } catch (Exception e) {
        throw new IllegalStateException("RooBot was unable to parse the repository document of this add-on", e);
    }
    return true;
}

From source file:org.protocoderrunner.utils.FileIO.java

static public void extractZip(String zipFile, String location) throws IOException {

    int size;/*from  w w w  . j ava  2  s  .c om*/
    int BUFFER_SIZE = 1024;

    byte[] buffer = new byte[BUFFER_SIZE];

    try {
        if (!location.endsWith("/")) {
            location += "/";
        }
        File f = new File(location);
        if (!f.isDirectory()) {
            f.mkdirs();
        }
        ZipInputStream zin = new ZipInputStream(
                new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE));
        try {
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
                String path = location + ze.getName();
                File unzipFile = new File(path);

                if (ze.isDirectory()) {
                    if (!unzipFile.isDirectory()) {
                        unzipFile.mkdirs();
                    }
                } else {
                    // check for and create parent directories if they don't exist
                    File parentDir = unzipFile.getParentFile();
                    if (null != parentDir) {
                        if (!parentDir.isDirectory()) {
                            parentDir.mkdirs();
                        }
                    }

                    // unzip the file
                    FileOutputStream out = new FileOutputStream(unzipFile, false);
                    BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
                    try {
                        while ((size = zin.read(buffer, 0, BUFFER_SIZE)) != -1) {
                            fout.write(buffer, 0, size);
                        }

                        zin.closeEntry();
                    } finally {
                        fout.flush();
                        fout.close();
                    }
                }
            }
        } finally {
            zin.close();
        }
    } catch (Exception e) {
        Log.e(TAG, "Unzip exception", e);
    }
}

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   w  w  w.  j ava  2s . 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"));

}