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:hu.sztaki.lpds.pgportal.services.dspace.DSpaceUtil.java

/**
 * Extracts any file from <code>inputFile</code> that begins with
 * 'bitstream' to <code>outputFile</code>.
 * Adapted from examples on/*from  w ww. j ava  2s. c om*/
 * http://java.sun.com/developer/technicalArticles/Programming/compression/
 *
 * @param inputFile  File to extract 'bitstream...' from
 * @param outputFile  File to extract 'bitstream...' to
 */
private static void unzipBitstream(InputStream is, File outputFile) throws IOException {
    final int BUFFER = 2048;
    BufferedOutputStream dest = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    try {

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.getName().matches("bitstream.*")) {
                int count;
                byte data[] = new byte[BUFFER];

                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(outputFile.getAbsoluteFile());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                    //System.out.println("Writing: " + outputFile.getAbsoluteFile());
                }
                dest.flush();
                dest.close();
            }
        }
    } finally {
        zis.close();
        try {
            dest.close();
        } catch (Exception e) {
        }
    }
}

From source file:mitm.common.security.JCEPolicyManager.java

/**
 * Installs the jce policy into the current JRE (JRE is found using java.home system property). The input must
 * /*from   w  w  w  . j  a  v a2  s.  c  o  m*/
 * @param jcePolicy an input stream to the policy file in zip format as downloaded from SUN site.
 * @param copyScript path to the shell script that will copy the jar file to the correct location
 * @throws IOException 
 */
public void installJCEPolicy(InputStream jcePolicy) throws IOException {
    /*
     * decodedPolicy should now contain a zip file with the policy files
     */
    ZipInputStream zis = new ZipInputStream(jcePolicy);

    ZipEntry zipEntry;

    boolean exportFound = false;
    boolean localPolicyFound = false;

    while ((zipEntry = zis.getNextEntry()) != null) {
        String name = zipEntry.getName();

        if (name == null) {
            continue;
        }

        if (name.endsWith("/" + US_EXPORT_POLICY_FILE)) {
            installJCEPolicy(zis, US_EXPORT_POLICY_FILE);

            exportFound = true;
        }

        if (name.endsWith("/" + LOCAL_POLICY_FILE)) {
            installJCEPolicy(zis, LOCAL_POLICY_FILE);

            localPolicyFound = true;
        }
    }

    if (!exportFound || !localPolicyFound) {
        throw new IOException("Not all policy files were found in the zip.");
    }
}

From source file:com.cip.crane.agent.utils.FileExtractUtils.java

/**
 * Unzip an input file into an output file.
 * <p>/*from  w  w  w .  j  a v a2 s  . com*/
 * The output file is created in the output folder, having the same name
 * as the input file, minus the '.zip' extension. 
 * 
 * @param inputFile     the input .zip file
 * @param outputDir     the output directory file. 
 * @throws IOException 
 * @throws FileNotFoundException
 *  
 * @return  The {@File} with the ungzipped content.
 */
public static void unZip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {
    LOG.debug(
            String.format("Unzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;
    zipinputstream = new ZipInputStream(new FileInputStream(inputFile));

    zipentry = zipinputstream.getNextEntry();
    while (zipentry != null) {
        //for each entry to be extracted
        String entryName = outputDir + "/" + zipentry.getName();
        entryName = entryName.replace('/', File.separatorChar);
        entryName = entryName.replace('\\', File.separatorChar);
        int n;
        FileOutputStream fileoutputstream;
        File newFile = new File(entryName);

        if (zipentry.isDirectory()) {
            if (!newFile.mkdirs()) {
                break;
            }
            zipentry = zipinputstream.getNextEntry();
            continue;
        }
        fileoutputstream = new FileOutputStream(entryName);

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

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

    } //while
    zipinputstream.close();
}

From source file:hoot.services.controllers.ogr.OgrAttributesResource.java

/**
 * This rest endpoint uploads multipart data from UI and then generates attribute output
 * Example: http://localhost:8080//hoot-services/ogr/info/upload?INPUT_TYPE=DIR
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb"}
 * //from  w w  w  .jav a2  s.co m
 * After getting the jobId, one can track the progress through job status rest end point
 * Example: http://localhost:8080/hoot-services/job/status/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb","statusDetail":null,"status":"complete"}
 * 
 * Once status is "complete"
 * Result attribute can be obtained through
 * Example:http://localhost:8080/hoot-services/ogr/info/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * output: JSON of attributes
 * 
 * @param inputType : [FILE | DIR] where FILE type should represents zip,shp or OMS and DIR represents FGDB
 * @param request
 * @return
 */
@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
public Response processUpload(@QueryParam("INPUT_TYPE") final String inputType,
        @Context HttpServletRequest request) {
    JSONObject res = new JSONObject();
    String jobId = UUID.randomUUID().toString();

    try {
        log.debug("Starting file upload for ogr attribute Process");
        Map<String, String> uploadedFiles = new HashMap<String, String>();
        ;
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

        MultipartSerializer ser = new MultipartSerializer();
        ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request);

        List<String> filesList = new ArrayList<String>();
        List<String> zipList = new ArrayList<String>();

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            String inputFileName = "";

            inputFileName = uploadedFilesPaths.get(fName);

            JSONObject param = new JSONObject();
            // If it is zip file then we crack open to see if it contains FGDB.
            // If so then we add the folder location and desired output name which is fgdb name in the zip
            if (ext.equalsIgnoreCase("ZIP")) {
                zipList.add(fName);
                String zipFilePath = homeFolder + "/upload/" + jobId + "/" + inputFileName;
                ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
                ZipEntry ze = zis.getNextEntry();

                while (ze != null) {

                    String zipName = ze.getName();
                    if (ze.isDirectory()) {

                        if (zipName.toLowerCase().endsWith(".gdb/") || zipName.toLowerCase().endsWith(".gdb")) {
                            String fgdbZipName = zipName;
                            if (zipName.toLowerCase().endsWith(".gdb/")) {
                                fgdbZipName = zipName.substring(0, zipName.length() - 1);
                            }
                            filesList.add("\"" + fName + "/" + fgdbZipName + "\"");
                        }
                    } else {
                        if (zipName.toLowerCase().endsWith(".shp")) {
                            filesList.add("\"" + fName + "/" + zipName + "\"");
                        }

                    }
                    ze = zis.getNextEntry();
                }

                zis.closeEntry();
                zis.close();
            } else {
                filesList.add("\"" + inputFileName + "\"");
            }

        }

        String mergeFilesList = StringUtils.join(filesList.toArray(), ' ');
        String mergedZipList = StringUtils.join(zipList.toArray(), ';');
        JSONArray params = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("INPUT_FILES", mergeFilesList);
        params.add(param);
        param = new JSONObject();
        param.put("INPUT_ZIPS", mergedZipList);
        params.add(param);

        String argStr = createPostBody(params);
        postJobRquest(jobId, argStr);

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log);
    }
    res.put("jobId", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

/**
 * ??/*ww  w  .j  a  v  a2s . c om*/
 */
private void fuckNotDefinedRes_clearAddRes(File apkFile) throws IOException, ShakaException {
    if (notDefinedRes.size() <= 0) {
        return;
    }

    File tempFile = File.createTempFile(apkFile.getName(), null);
    tempFile.delete();
    tempFile.deleteOnExit();
    boolean renameOk = apkFile.renameTo(tempFile);
    if (!renameOk) {
        throw new ShakaException(
                "could not rename the file " + apkFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    try (ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
            ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(apkFile))) {
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean toBeDeleted = false;
            for (String f : notDefinedRes) {
                if (f.equals(name)) {
                    toBeDeleted = true;
                    LogHelper.warning("Delete temp res : " + f);
                    break;
                }
            }
            if (!toBeDeleted) {
                // Add ZIP entry to output stream.
                zout.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                IOUtils.copy(zin, zout);
            }
            entry = zin.getNextEntry();
        }
    }

    tempFile.delete();
    notDefinedRes.clear();
}

From source file:com.amalto.core.storage.hibernate.TypeMapping.java

private static Object _deserializeValue(Object value, FieldMetadata sourceField, FieldMetadata targetField) {
    if (targetField == null) {
        return value;
    }/*from ww w  .ja  v  a 2s .  c  o m*/
    if (!targetField.isMany()) {
        Boolean targetZipped = targetField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        Boolean sourceZipped = sourceField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        if (Boolean.TRUE.equals(sourceZipped) && targetZipped == null) {
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(String.valueOf(value).getBytes("UTF-8")); //$NON-NLS-1$
                ZipInputStream zis = new ZipInputStream(new Base64InputStream(bis));
                byte[] buffer = new byte[1024];
                int read;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                while (zis.getNextEntry() != null) {
                    while ((read = zis.read(buffer, 0, buffer.length)) > -1) {
                        bos.write(buffer, 0, read);
                    }
                }
                return new String(bos.toByteArray(), "UTF-8"); //$NON-NLS-1$
            } catch (IOException e) {
                throw new RuntimeException("Unexpected deflate exception", e); //$NON-NLS-1$
            }
        }
        String targetSQLType = sourceField.getType().getData(TypeMapping.SQL_TYPE);
        if (value != null && targetSQLType != null && SQL_TYPE_CLOB.equals(targetSQLType)) {
            try {
                Reader characterStream = ((Clob) value).getCharacterStream();
                return new String(IOUtils.toCharArray(characterStream)); // No need to close (Hibernate seems to
                                                                         // handle this).
            } catch (Exception e) {
                throw new RuntimeException("Unexpected read from clob exception", e); //$NON-NLS-1$
            }
        }
    }
    return value;
}

From source file:com.jsonstore.util.JSONStoreUtil.java

public static void unpack(InputStream in, File targetDir) throws IOException {
    ZipInputStream zin = new ZipInputStream(in);

    ZipEntry entry;//  w  w w . ja va2  s . c o  m
    while ((entry = zin.getNextEntry()) != null) {
        String extractFilePath = entry.getName();
        if (extractFilePath.startsWith("/") || extractFilePath.startsWith("\\")) {
            extractFilePath = extractFilePath.substring(1);
        }
        File extractFile = new File(targetDir.getPath() + File.separator + extractFilePath);
        if (entry.isDirectory()) {
            if (!extractFile.exists()) {
                extractFile.mkdirs();
            }
            continue;
        } else {
            File parent = extractFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
        }

        // if not directory instead of the previous check and continue
        OutputStream os = new BufferedOutputStream(new FileOutputStream(extractFile));
        copyFile(zin, os);
        os.flush();
        os.close();
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public String loadTouchOscXML(String zipTouchoscFilePath) {
    List<String> touchoscFilePathList = new ArrayList<String>();
    IPath path = new Path(zipTouchoscFilePath);
    String xml = "";
    try {/*from  w  ww. ja v a  2s  . c o m*/
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);
        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.flip();

            xml = charBuffer.toString();

        }

        fileIS.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    return xml;
}

From source file:com.cloudera.oryx.app.serving.AbstractOryxResource.java

protected static InputStream maybeDecompress(Part item) throws IOException {
    InputStream in = item.getInputStream();
    String contentType = item.getContentType();
    if (contentType != null) {
        switch (contentType) {
        case "application/zip":
            in = new ZipInputStream(in);
            break;
        case "application/gzip":
        case "application/x-gzip":
            in = new GZIPInputStream(in);
            break;
        }//from w  w w . ja  v a 2 s. c o m
    }
    return in;
}