Example usage for java.util.zip ZipInputStream getNextEntry

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

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:net.geoprism.data.importer.ShapefileImporter.java

@Request
public void run(InputStream iStream) throws InvocationTargetException {
    // create a buffer to improve copy performance later.
    byte[] buffer = new byte[2048];

    File directory = null;//from ww w  . j a  v  a  2  s .  c  o m

    File first = null;

    try {
        directory = new File(FileUtils.getTempDirectory(),
                new Long(configuration.getGenerator().next()).toString());
        directory.mkdirs();

        ZipInputStream zstream = new ZipInputStream(iStream);

        ZipEntry entry;

        while ((entry = zstream.getNextEntry()) != null) {
            File file = new File(directory, entry.getName());

            if (first == null && file.getName().endsWith("dbf")) {
                first = file;
            }

            FileOutputStream output = null;

            try {
                output = new FileOutputStream(file);

                int len = 0;

                while ((len = zstream.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
            } finally {
                if (output != null) {
                    output.close();
                }
            }
        }

        if (first != null) {
            this.createFeatures(first.toURI().toURL());
        } else {
            // TODO Change exception type
            throw new RuntimeException("Empty zip file");
        }
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    } finally {
        if (directory != null) {
            try {
                FileUtils.deleteDirectory(directory);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   extract()//  ww  w. j av a  2 s . c om
** Input:  String zipFileName  --  The name of the zip file to be used
**         Sting  extractedFile  --  The name of the file to be extracted 
**                                   from the zip    
** Output:   none
**
** Description: This method takes in the name of a zip file and a file to
**              be extracted from the zip format.  The method locates the
**              file and extracts into the '.' directory.
**              
*****************************************************************************/
public static String extract(String zipFileName, String extractedFile, String pathOfExtract) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in extract()           ");
        System.out.println("***********************");
        System.out.println("zip file: " + zipFileName);
        System.out.println("file to extract: " + extractedFile);
    }

    String nameOfExtractedFile = new String("");
    System.out.println("-----LMSPackageHandler-extract()----");
    System.out.println("zipFileName=" + zipFileName);
    System.out.println("extractedFile=" + extractedFile);
    System.out.println("pathOfExtract=" + pathOfExtract);
    try {
        String pathAndName = new String("");
        int index = zipFileName.lastIndexOf("\\") + 1;
        zipFileName = zipFileName.substring(index);
        System.out.println("---zipFileName=" + zipFileName);
        //  Input stream for the zip file (package)
        ZipInputStream in = new ZipInputStream(new FileInputStream(pathOfExtract + "\\" + zipFileName));

        //  Cut the path off of the name of the file. (for writing the file)
        int indexOfFileBeginning = extractedFile.lastIndexOf("/") + 1;
        System.out.println("---indexOfFileBeginning=" + indexOfFileBeginning);
        nameOfExtractedFile = extractedFile.substring(indexOfFileBeginning);
        System.out.println("---nameOfExtractedFile=" + nameOfExtractedFile);
        pathAndName = pathOfExtract + "\\" + nameOfExtractedFile;
        System.out.println("pathAndName=" + pathAndName);
        //  Ouput stream for the extracted file
        //*************************************
        //*************************************
        OutputStream out = new FileOutputStream(pathAndName);
        //OutputStream out = new FileOutputStream(nameOfExtractedFile);

        ZipEntry entry;
        byte[] buf = new byte[1024];
        int len;
        int flag = 0;

        while (flag != 1) {
            entry = in.getNextEntry();

            if ((entry.getName()).equalsIgnoreCase(extractedFile)) {
                if (_Debug) {
                    System.out.println("Found file to extract...  extracting to " + pathOfExtract);
                }
                flag = 1;
            }
        }

        while ((len = in.read(buf)) > 0) {

            out.write(buf, 0, len);
        }

        out.close();
        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
        e.printStackTrace();
    }
    return nameOfExtractedFile;
}

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

@Override
public DeploymentConfiguration getDeploymentConfiguration(InputStream appPackageInputStream) {
    DeploymentConfiguration deploymentConfig = null;
    ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(appPackageInputStream),
            Charset.forName("UTF-8"));

    try {/*from  w ww  . ja  v a2  s .com*/
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

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

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

            if (zipEntry.getName().startsWith(SLEDGEFILE_XML)) {
                ByteArrayOutputStream output = new ByteArrayOutputStream();

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

                DeploymentConfigurationReader deploymentConfigReader = new DeploymentConfigurationReaderXml();
                deploymentConfig = deploymentConfigReader
                        .parseDeploymentConfiguration(new ByteArrayInputStream(output.toByteArray()));

                zipStream.closeEntry();

                // Stop here, the file is read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackageInputStream.reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return deploymentConfig;
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private ZipOutputStream copyOOXMLContent(final String signatureZipEntryName,
        final OutputStream signedOOXMLOutputStream)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    final ZipOutputStream zipOutputStream = new ZipOutputStream(signedOOXMLOutputStream);
    final ZipInputStream zipInputStream = new ZipInputStream(
            new ByteArrayInputStream(this.getOfficeOpenXMLDocument()));
    ZipEntry zipEntry;//from w w w.j ava2  s. c  om
    boolean hasOriginSigsRels = false;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
        if ("[Content_Types].xml".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document contentTypesDocument = loadDocumentNoClose(zipInputStream);
            final Element typesElement = contentTypesDocument.getDocumentElement();

            // We need to add an Override element.
            final Element overrideElement = contentTypesDocument.createElementNS(
                    "http://schemas.openxmlformats.org/package/2006/content-types", "Override"); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("PartName", "/" + signatureZipEntryName); //$NON-NLS-1$ //$NON-NLS-2$
            overrideElement.setAttribute("ContentType", //$NON-NLS-1$
                    "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"); //$NON-NLS-1$
            typesElement.appendChild(overrideElement);

            final Element nsElement = contentTypesDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/content-types"); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument,
                    "/tns:Types/tns:Default[@Extension='sigs']", nsElement); //$NON-NLS-1$
            if (0 == nodeList.getLength()) {
                // Add Default element for 'sigs' extension.
                final Element defaultElement = contentTypesDocument.createElementNS(
                        "http://schemas.openxmlformats.org/package/2006/content-types", "Default"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("Extension", "sigs"); //$NON-NLS-1$ //$NON-NLS-2$
                defaultElement.setAttribute("ContentType", //$NON-NLS-1$
                        "application/vnd.openxmlformats-package.digital-signature-origin"); //$NON-NLS-1$
                typesElement.appendChild(defaultElement);
            }

            writeDocumentNoClosing(contentTypesDocument, zipOutputStream, false);
        } else if ("_rels/.rels".equals(zipEntry.getName())) { //$NON-NLS-1$
            final Document relsDocument = loadDocumentNoClose(zipInputStream);

            final Element nsElement = relsDocument.createElement("ns"); //$NON-NLS-1$
            nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
            final NodeList nodeList = XPathAPI.selectNodeList(relsDocument,
                    "/tns:Relationships/tns:Relationship[@Type='http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin']", //$NON-NLS-1$
                    nsElement);
            if (0 == nodeList.getLength()) {
                final Element relationshipElement = relsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                        "Relationship"); //$NON-NLS-1$
                relationshipElement.setAttribute("Id", "rel-id-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
                relationshipElement.setAttribute("Type", //$NON-NLS-1$
                        "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"); //$NON-NLS-1$
                relationshipElement.setAttribute("Target", "_xmlsignatures/origin.sigs"); //$NON-NLS-1$ //$NON-NLS-2$

                relsDocument.getDocumentElement().appendChild(relationshipElement);
            }

            writeDocumentNoClosing(relsDocument, zipOutputStream, false);
        } else if (zipEntry.getName().startsWith("_xmlsignatures/_rels/") //$NON-NLS-1$
                && zipEntry.getName().endsWith(".rels")) { //$NON-NLS-1$

            hasOriginSigsRels = true;
            final Document originSignRelsDocument = loadDocumentNoClose(zipInputStream);

            final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
                    "Relationship"); //$NON-NLS-1$
            relationshipElement.setAttribute("Id", "rel-" + UUID.randomUUID().toString()); //$NON-NLS-1$ //$NON-NLS-2$
            relationshipElement.setAttribute("Type", //$NON-NLS-1$
                    "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

            relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
            originSignRelsDocument.getDocumentElement().appendChild(relationshipElement);

            writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
        } else {
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }

    if (!hasOriginSigsRels) {
        // Add signature relationships document.
        addOriginSigsRels(signatureZipEntryName, zipOutputStream);
        addOriginSigs(zipOutputStream);
    }

    // Return.
    zipInputStream.close();
    return zipOutputStream;
}

From source file:org.nebulaframework.deployment.classloading.GridArchiveClassLoader.java

/**
 * Searches given JAR file stream within the {@code GridArchive} to
 * locate a specified class file. // ww  w . ja  v a2 s .  co  m
 * <p>
 * Note that as it is implemented to read from Zip file stream, 
 * this requires each entry with in the JAR to be matched 
 * against the required class file's expected path.
 * <p>
 * An alternate implementation would be to implement this to write each
 * JAR file as a temporary file and then use direct path to find the 
 * class file. However, this implementation proved to be much slower
 * than the current implementation, due to slow disk access times.
 *  
 * @param inStream {@code InputStream} for the JAR file
 * @param fileName expected filename of the Class to be found
 * 
 * @return The {@code byte[]} for the class file, if found, or {@code null}
 * 
 * @throws IOException if an IO error occurs during operation
 */
protected byte[] findInJarStream(InputStream inStream, String fileName) throws IOException {

    // Get ZipInputStream to unzip content
    ZipInputStream zipInStream = new ZipInputStream(inStream);

    ZipEntry entry = null;

    // Compare against each entry
    while ((entry = zipInStream.getNextEntry()) != null) {
        // If match found
        if (entry.getName().equals(fileName)) {
            log.debug("Match Found");
            return IOSupport.readBytes(zipInStream, entry.getSize());
        }
    }

    // Not Found, return null
    return null;
}

From source file:com.taobao.android.builder.tasks.app.databinding.AwbDataBindingMergeArtifactsTask.java

private void extractBinFilesFromJar(File outFolder, File jarFile) throws IOException {
    File jarOutFolder = getOutFolderForJarFile(outFolder, jarFile);
    FileUtils.deleteQuietly(jarOutFolder);
    FileUtils.forceMkdir(jarOutFolder);/*from   w  ww  .j  a v  a2 s .  c  o m*/

    try (Closer localCloser = Closer.create()) {
        FileInputStream fis = localCloser.register(new FileInputStream(jarFile));
        ZipInputStream zis = localCloser.register(new ZipInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }

            String name = entry.getName();

            if (!isResource(name)) {
                continue;
            }
            // get rid of the path. We don't need it since the file name includes the domain
            name = new File(name).getName();
            File out = new File(jarOutFolder, name);
            //noinspection ResultOfMethodCallIgnored
            FileOutputStream fos = localCloser.register(new FileOutputStream(out));
            ByteStreams.copy(zis, fos);
            zis.closeEntry();
        }
    }
}

From source file:com.jadarstudios.rankcapes.bukkit.RankCapesBukkit.java

/**
 * Validates a cape pack and returns true if it is valid.
 *
 * @param pack to validate//from  www  .j  a v  a 2  s .c  o m
 */
private void validatePack(byte[] pack) throws IOException, InvalidCapePackException, ParseException {
    boolean foundMetadata = false;

    if (pack == null) {
        throw new InvalidCapePackException("The cape pack was null");
    }

    if (!CapePackValidator.isZipFile(pack)) {
        throw new InvalidCapePackException("The cape pack is not a ZIP file.");
    }

    ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(pack));
    ZipEntry entry;

    // reads the zip and finds the files. if the pack config file is not found, return false.
    while ((entry = zipIn.getNextEntry()) != null)
    // if the zip contains a file names "pack.mcmeta"
    {
        if (entry.getName().equals("pack.mcmeta")) {
            foundMetadata = true;
            try {
                this.parseMetadata(zipIn);
            } finally {
                zipIn.close();
            }

            break;
        }
    }

    if (!foundMetadata) {
        throw new InvalidCapePackException("The Cape Pack metadata was not found.");
    }
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

private String decompressSVMWithSGDModel(String archiveName) throws IOException {

    URL scmArchive = getClass().getClassLoader().getResource(archiveName);
    if (scmArchive == null) {
        throw new IOException("Unable to locate " + archiveName + " as a classpath resource.");
    }//ww  w .jav  a  2 s  .  com
    File tempDir = Files.createTempDirectory("mudrod").toFile();
    assert tempDir.setWritable(true);
    File archiveFile = new File(tempDir, archiveName);
    FileUtils.copyURLToFile(scmArchive, archiveFile);

    // Decompress archive
    int BUFFER_SIZE = 512000;
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(archiveFile));
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        File f = new File(tempDir, entry.getName());
        // If the entry is a directory, create the directory.
        if (entry.isDirectory() && !f.exists()) {
            boolean created = f.mkdirs();
            if (!created) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getAbsolutePath());
            }
        } else if (!entry.isDirectory()) {
            boolean created = f.getParentFile().mkdirs();
            if (!created && !f.getParentFile().exists()) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getParentFile().getAbsolutePath());
            }
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(new File(tempDir, entry.getName()), false);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
            }
        }
    }

    return new File(tempDir, StringUtils.removeEnd(archiveName, ".zip")).toURI().toString();
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectSamplesActionTest.java

@Test
public void testDownload() throws Exception {
    assertEquals("noSampleData", this.action.download());

    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Sample s = new Sample();
    final Extract e = new Extract();
    s.getExtracts().add(e);/*  w w  w  .j a  v a  2  s.  c  o  m*/
    final LabeledExtract le = new LabeledExtract();
    e.getLabeledExtracts().add(le);
    final Hybridization h = new Hybridization();
    le.getHybridizations().add(h);
    final RawArrayData raw = new RawArrayData();
    h.addArrayData(raw);
    final DerivedArrayData derived = new DerivedArrayData();
    h.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentSample(s);
    this.action.setProject(p);
    final List<CaArrayFile> files = new ArrayList<CaArrayFile>(s.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(2, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    assertEquals("missing_term_source.sdrf", files.get(1).getName());

    this.action.download();
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.sdrf", ze.getName());
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request/*from  ww w  .  java  2s. co m*/
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}