Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:edu.ucla.loni.server.Upload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*from www  . ja  va  2  s.c o  m*/
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(req);

            // Go through the items and get the root and package
            String rootPath = "";
            String packageName = "";

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("root")) {
                        rootPath = item.getString();
                    } else if (item.getFieldName().equals("packageName")) {
                        packageName = item.getString();
                    }
                }
            }

            if (rootPath.equals("")) {
                res.getWriter().println("error :: Root directory has not been found.");
                return;
            }

            Directory root = Database.selectDirectory(rootPath);

            // Go through items and process urls and files
            for (FileItem item : items) {
                // Uploaded File
                if (item.isFormField() == false) {
                    String filename = item.getName();
                    ;
                    if (filename.equals("") == true)
                        continue;
                    try {
                        InputStream in = item.getInputStream();
                        //determine if it is pipefile or zipfile
                        //if it is pipefile => feed directly to writeFile function
                        //otherwise, uncompresse it first and then one-by-one feed to writeFile
                        if (filename.endsWith(".zip")) {
                            ZipInputStream zip = new ZipInputStream(in);
                            ZipEntry entry = zip.getNextEntry();
                            while (entry != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                if (baos != null) {
                                    byte[] arr = new byte[4096];
                                    int index = 0;
                                    while ((index = zip.read(arr, 0, 4096)) != -1) {
                                        baos.write(arr, 0, index);
                                    }
                                }
                                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                                writeFile(root, packageName, is);
                                entry = zip.getNextEntry();
                            }
                            zip.close();
                        } else {
                            writeFile(root, packageName, in);

                        }

                        in.close();
                    } catch (Exception e) {
                        res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage());
                    }
                }
                // URLs               
                if (item.isFormField() && item.getFieldName().equals("urls")
                        && item.getString().equals("") == false) {
                    String urlListAsStr = item.getString();
                    String[] urlList = urlListAsStr.split("\n");

                    for (String urlStr : urlList) {
                        try {
                            URL url = new URL(urlStr);
                            URLConnection urlc = url.openConnection();

                            InputStream in = urlc.getInputStream();

                            writeFile(root, packageName, in);

                            in.close();
                        } catch (Exception e) {
                            res.getWriter().println("Failed to upload " + urlStr);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
        }
    }
}

From source file:net.ftb.util.FileUtils.java

public static void backupExtract(String zipLocation, String outputLocation) {
    Logger.logInfo("Extracting (Backup way)");
    byte[] buffer = new byte[1024];
    ZipInputStream zis = null;/*from   w w  w.j  a  v  a2s . c  om*/
    ZipEntry ze;
    try {
        File folder = new File(outputLocation);
        if (!folder.exists()) {
            folder.mkdir();
        }
        zis = new ZipInputStream(new FileInputStream(zipLocation));
        ze = zis.getNextEntry();
        while (ze != null) {
            File newFile = new File(outputLocation, ze.getName());
            newFile.getParentFile().mkdirs();
            if (!ze.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
                fos.close();
            }
            ze = zis.getNextEntry();
        }
    } catch (IOException ex) {
        Logger.logError("Error while extracting zip", ex);
    } finally {
        try {
            zis.closeEntry();
            zis.close();
        } catch (IOException e) {
        }
    }
}

From source file:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

public DocumentVisualization findDocument(byte[] parentDocument, String resourceId) throws Exception {

    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(parentDocument));
    ZipEntry zipEntry;/*  w  w  w . jav  a2  s. c om*/

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

        if (getResourceId(zipEntry).equals(resourceId)) {

            LOG.debug("Found file: " + resourceId);

            byte[] data = IOUtils.toByteArray(zipInputStream);
            return new DocumentVisualization(new MimetypesFileTypeMap().getContentType(zipEntry.getName()),
                    data);
        }
    }

    return null;
}

From source file:com.dv.util.DataViewerZipUtil.java

/**
 * ?.//www .  ja v  a 2s . c  o  m
 *
 * @param is ??
 * @param destFile ?
 * @throws IOException
 */
public static void unzipFile(InputStream is, File destFile) throws IOException {
    try {
        if (is instanceof ZipInputStream) {
            doUnzipFile((ZipInputStream) is, destFile);
        } else {
            doUnzipFile(new ZipInputStream(is), destFile);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.founder.fix.fixflow.service.impl.ProcessDefinitionServiceImpl.java

public void deployByZip(Map<String, Object> params) throws Exception {
    String userid = StringUtil.getString(params.get("userId"));
    FileItem file = (FileItem) params.get("ProcessFile");
    ProcessEngine processEngine = null;//  ww  w. j  a v a  2 s.  co  m
    try {
        processEngine = getProcessEngine(userid);
        String deploymentId = StringUtil.getString(params.get("deploymentId"));
        //deploymentID?
        if (deploymentId != null && !"".equals(deploymentId)) {
            processEngine.getModelService().updateDeploymentByZip(new ZipInputStream(file.getInputStream()),
                    deploymentId);
        } else {
            processEngine.getModelService().deploymentByZip(new ZipInputStream(file.getInputStream()));
        }
    } finally {
        closeProcessEngine();
    }
}

From source file:com.griddynamics.deming.ecommerce.api.endpoint.catalog.CatalogManagerEndpoint.java

@POST
@Path("import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response importCatalog(@FormDataParam("file") InputStream uploadInputStream)
        throws ServiceException, IOException {
    removeCatalog();/* ww  w .  j  a v a2s.c  o  m*/

    try {
        ZipInputStream inputStream = new ZipInputStream(uploadInputStream);

        try {
            byte[] buf = new byte[1024];

            for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
                    .getNextEntry()) {
                try {
                    String entryName = entry.getName();
                    entryName = entryName.replace('/', File.separatorChar);
                    entryName = entryName.replace('\\', File.separatorChar);

                    LOGGER.debug("Entry name: {}", entryName);

                    if (entry.isDirectory()) {
                        LOGGER.debug("Entry ({}) is directory", entryName);
                    } else if (PRODUCT_CATALOG_FILE.equals(entryName)) {
                        ByteArrayOutputStream jsonBytes = new ByteArrayOutputStream(1024);

                        for (int n = inputStream.read(buf, 0, 1024); n > -1; n = inputStream.read(buf, 0,
                                1024)) {
                            jsonBytes.write(buf, 0, n);
                        }

                        byte[] bytes = jsonBytes.toByteArray();

                        ObjectMapper mapper = new ObjectMapper();

                        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
                        mapper.registerModule(jaxbAnnotationModule);

                        ImportCategoryWrapper catalog = mapper.readValue(bytes, ImportCategoryWrapper.class);
                        escape(catalog);
                        saveCategoryTree(catalog);
                    } else {
                        MultipartFile file = new MultipartFileAdapter(inputStream, entryName);
                        dmgStaticAssetStorageService.createStaticAssetStorageFromFile(file);
                    }

                } finally {
                    inputStream.closeEntry();
                }
            }
        } finally {
            inputStream.close();
        }

    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Unable load catalog.\n").build();
    }

    Thread rebuildSearchIndex = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
                searchService.rebuildIndex();
            } catch (Exception e) {
                /* nothing */}
        }
    });
    rebuildSearchIndex.start();

    return Response.status(Response.Status.OK).entity("Catalog was imported successfully!\n").build();
}

From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java

private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;//from   w  w w  . j  a va 2 s  .  c o  m
    ZipOutputStream outJar = null;

    try {
        try {
            inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        ZipEntry entry;
        while ((entry = inJar.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                outJar.putNextEntry(entry);
                continue;
            }

            byte[] data = new byte[4096];
            ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();

            int len;
            do {
                len = inJar.read(data);
                if (len > 0) {
                    entryBuffer.write(data, 0, len);
                }
            } while (len != -1);

            byte[] entryData = entryBuffer.toByteArray();

            String entryName = entry.getName();

            if (entryName.endsWith(".class") && !entryName.startsWith(".")) {
                ClassNode cls = new ClassNode();
                ClassReader rdr = new ClassReader(entryData);
                rdr.accept(cls, 0);
                String name = cls.name.replace('/', '.').replace('\\', '.');

                for (MarkerTransformer trans : transformers) {
                    entryData = trans.transform(name, name, entryData);
                }
            }

            ZipEntry newEntry = new ZipEntry(entryName);
            outJar.putNextEntry(newEntry);
            outJar.write(entryData);
        }
    } finally {
        IOUtils.closeQuietly(outJar);
        IOUtils.closeQuietly(inJar);
    }
}

From source file:net.sf.jasperreports.samples.wizards.SampleNewWizard.java

public static void unpackArchive(File theFile, File targetDir, IProgressMonitor monitor, Set<String> cpaths,
        Set<String> lpaths) {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = null;//w  w w  .j a  v  a2  s.c  o m
    try {
        zis = new ZipInputStream(new FileInputStream(theFile));

        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            File file = new File(targetDir, File.separator + ze.getName());

            new File(file.getParent()).mkdirs();
            String fname = file.getName();
            if (ze.isDirectory()) {
                if (fname.equals("src"))
                    cpaths.add(ze.getName());
            } else {
                FileOutputStream fos = new FileOutputStream(file);
                int len;
                while ((len = zis.read(buffer)) > 0)
                    fos.write(buffer, 0, len);

                fos.close();
            }
            if (file.getParentFile().getName().equals("lib")
                    && (fname.endsWith(".jar") || fname.endsWith(".zip")))
                lpaths.add(ze.getName());
            if (monitor.isCanceled()) {
                zis.close();
                return;
            }
            ze = zis.getNextEntry();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            zis.closeEntry();
            zis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.xpn.xwiki.plugin.zipexplorer.ZipExplorerPlugin.java

/**
 * For ZIP URLs of the format <code>http://[...]/zipfile.zip/SomeDirectory/SomeFile.txt</code> return a new
 * attachment containing the file pointed to inside the ZIP. If the original attachment does not point to a ZIP file
 * or if it doesn't specify a location inside the ZIP then do nothing and return the original attachment.
 * //from  w ww .  ja  v a 2  s .com
 * @param attachment the original attachment
 * @param context the XWiki context, used to get the request URL corresponding to the download request
 * @return a new attachment pointing to the file pointed to by the URL inside the ZIP or the original attachment if
 *         the requested URL doesn't specify a file inside a ZIP
 * @see com.xpn.xwiki.plugin.XWikiDefaultPlugin#downloadAttachment
 */
@Override
public XWikiAttachment downloadAttachment(XWikiAttachment attachment, XWikiContext context) {
    String url = context.getRequest().getRequestURI();

    // Verify if we should return the original attachment. This will happen if the requested
    // download URL doesn't point to a zip or if the URL doesn't point to a file inside the ZIP.
    if (!isValidZipURL(url, context.getAction().trim())) {
        return attachment;
    }

    String filename = getFileLocationFromZipURL(url, context.getAction().trim());

    // Create the new attachment pointing to the file inside the ZIP
    XWikiAttachment newAttachment = new XWikiAttachment();
    newAttachment.setDoc(attachment.getDoc());
    newAttachment.setAuthor(attachment.getAuthor());
    newAttachment.setDate(attachment.getDate());

    InputStream stream = null;
    try {
        stream = new BufferedInputStream(attachment.getContentInputStream(context));

        if (!isZipFile(stream)) {
            return attachment;
        }

        ZipInputStream zis = new ZipInputStream(stream);
        ZipEntry entry;

        while ((entry = zis.getNextEntry()) != null) {
            String entryName = entry.getName();

            if (entryName.equals(filename)) {
                newAttachment.setFilename(entryName);

                if (entry.getSize() == -1) {
                    // Note: We're copying the content of the file in the ZIP in memory. This is
                    // potentially going to cause an error if the file's size is greater than the
                    // maximum size of a byte[] array in Java or if there's not enough memomry.
                    byte[] data = IOUtils.toByteArray(zis);

                    newAttachment.setContent(data);
                } else {
                    newAttachment.setContent(zis, (int) entry.getSize());
                }
                break;
            }
        }
    } catch (XWikiException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return newAttachment;
}

From source file:com.diffplug.gradle.ZipMisc.java

/**
 * Unzips a directory to a folder./*w  ww  .j  av  a 2 s. c  o  m*/
 *
 * @param input            a zip file
 * @param destinationDir   where the zip will be extracted to
 */
public static void unzip(File input, File destinationDir) throws IOException {
    try (ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream(new FileInputStream(input)))) {
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            File dest = new File(destinationDir, entry.getName());
            if (entry.isDirectory()) {
                FileMisc.mkdirs(dest);
            } else {
                FileMisc.mkdirs(dest.getParentFile());
                try (OutputStream output = new BufferedOutputStream(new FileOutputStream(dest))) {
                    copy(zipInput, output);
                }
            }
        }
    }
}