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:es.eucm.mokap.backend.controller.insert.MokapInsertController.java

/**
 * Processes a temp file stored in Cloud Storage: -It analyzes its contents
 * -Processes the descriptor.json file and stores the entity in Datastore
 * -Finally it stores the thumbnails and contents.zip in Cloud Storage
 * /*ww  w.ja v  a2  s  .  c o m*/
 * @param tempFileName
 *            name of the temp file we are going to process
 * @return The Datastore Key id for the entity we just created (entityRef in
 *         RepoElement)
 * @throws IOException
 *             If the file is not accessible or Cloud Storage is not
 *             available ServerError If a problem is found with the internal
 *             structure of the file
 */
private long processUploadedTempFile(String tempFileName) throws IOException, ServerError {
    long assignedKeyId;
    // Read the cloud storage file
    byte[] content = null;
    String descriptor = "";
    Map<String, byte[]> tns = new HashMap<String, byte[]>();
    InputStream is = st.readFile(tempFileName);
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        String filename = entry.getName();
        if (UploadZipStructure.isContentsFile(filename)) {
            content = IOUtils.toByteArray(zis);
        } else if (UploadZipStructure.isDescriptorFile(filename)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(zis, "UTF-8"));
            String str;
            while ((str = br.readLine()) != null) {
                descriptor += str;
            }
        } else if (entry.isDirectory()) {
            continue;
        }
        // Should be a thumbnail
        else if (UploadZipStructure.checkThumbnailImage(filename)) {
            byte[] img = IOUtils.toByteArray(zis);
            tns.put(filename, img);
        }
        zis.closeEntry();
    }

    try {
        if (descriptor != null && !descriptor.equals("") && content != null) {
            // Analizar json
            Map<String, Object> entMap = Utils.jsonToMap(descriptor);
            // Parse the map into an entity
            Entity ent = new Entity("Resource");
            for (String key : entMap.keySet()) {
                ent.setProperty(key, entMap.get(key));
            }
            // Store the entity (GDS) and get the Id
            Key k = db.storeEntity(ent);
            assignedKeyId = k.getId();

            // Store the contents file with the Id in the name
            ByteArrayInputStream bis = new ByteArrayInputStream(content);
            st.storeFile(bis, assignedKeyId + UploadZipStructure.ZIP_EXTENSION);

            // Store the thumbnails in a folder with the id as the name
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.storeFile(imgs, assignedKeyId + "/" + key);
            }
            // Create the Search Index Document
            db.addToSearchIndex(ent, k);

            // Everything went ok, so we delete the temp file
            st.deleteFile(tempFileName);
        } else {
            assignedKeyId = 0;
            if (descriptor == null || descriptor.equals("")) {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_DESCRIPTOR);
            } else {
                throw new ServerError(ServerReturnMessages.INVALID_UPLOAD_CONTENT);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
        assignedKeyId = 0;
        // Force rollback if anything failed
        try {
            st.deleteFile(tempFileName);
            for (String key : tns.keySet()) {
                ByteArrayInputStream imgs = new ByteArrayInputStream(tns.get(key));
                st.deleteFile(assignedKeyId + "/" + key);
            }
            db.deleteEntity(assignedKeyId);
        } catch (Exception ex) {
        }
    }
    return assignedKeyId;
}

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }/*www  . ja va2s. c o m*/
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.moss.fskit.Unzipper.java

public boolean isDirectoryWrapper(File zipFile) throws UnzipException {
    try {//from   w  w w .  jav a2s.  co m
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile));

        boolean firstEntryWasDirectory = false;
        int numEntries = 0;
        for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
            String name = entry.getName().trim();
            if (name.startsWith("/"))
                name = name.substring(1);
            if (name.endsWith("/"))
                name = name.substring(0, name.length() - 2);

            if (name.indexOf('/') == -1) {
                // This is at the 'root' level.
                numEntries++;
                if (numEntries == 1 && entry.isDirectory()) {
                    firstEntryWasDirectory = true;
                }
            }
        }
        in.close();
        return (numEntries == 1) && firstEntryWasDirectory;
    } catch (IOException e) {
        throw new UnzipException("Error processing " + zipFile.getAbsolutePath(), e);
    }

}

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  . j a v a2  s.c om
            @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:mj.ocraptor.extraction.tika.parser.odf.OpenDocumentParser.java

public void parse(InputStream stream, ContentHandler baseHandler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    // TODO: reuse the already opened ZIPFile, if
    // present//from  w w  w  . j  a  v  a2  s . c  om

    /*
     * ZipFile zipFile; if (stream instanceof TikaInputStream) { TikaInputStream
     * tis = (TikaInputStream) stream; Object container = ((TikaInputStream)
     * stream).getOpenContainer(); if (container instanceof ZipFile) { zipFile =
     * (ZipFile) container; } else if (tis.hasFile()) { zipFile = new
     * ZipFile(tis.getFile()); } }
     */

    // TODO: if incoming IS is a TIS with a file
    // associated, we should open ZipFile so we can
    // visit metadata, mimetype first; today we lose
    // all the metadata if meta.xml is hit after
    // content.xml in the stream. Then we can still
    // read-once for the content.xml.

    XHTMLContentHandler xhtml = new XHTMLContentHandler(baseHandler, metadata);

    // As we don't know which of the metadata or the content
    // we'll hit first, catch the endDocument call initially
    EndDocumentShieldingContentHandler handler = new EndDocumentShieldingContentHandler(xhtml);

    TikaImageHelper helper = new TikaImageHelper(metadata);
    try {
        // Process the file in turn
        ZipInputStream zip = new ZipInputStream(stream);
        ZipEntry entry = zip.getNextEntry();
        while (entry != null) {
            // TODO: images
            String entryExtension = null;
            try {
                entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension)
                    && Config.inst().getProp(ConfigBool.ENABLE_IMAGE_OCR)) {
                File imageFile = null;
                try {
                    imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry);
                    helper.addImage(imageFile);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (imageFile != null) {
                        imageFile.delete();
                    }
                }
            } else if (entry.getName().equals("mimetype")) {
                String type = IOUtils.toString(zip, "UTF-8");
                metadata.set(Metadata.CONTENT_TYPE, type);
            } else if (entry.getName().equals("meta.xml")) {
                meta.parse(zip, new DefaultHandler(), metadata, context);
            } else if (entry.getName().endsWith("content.xml")) {
                if (content instanceof OpenDocumentContentParser) {
                    ((OpenDocumentContentParser) content).parseInternal(zip, handler, metadata, context);
                } else {
                    // Foreign content parser was set:
                    content.parse(zip, handler, metadata, context);
                }
            } else if (entry.getName().endsWith("styles.xml")) {
                if (content instanceof OpenDocumentContentParser) {
                    ((OpenDocumentContentParser) content).parseInternal(zip, handler, metadata, context);
                } else {
                    // Foreign content parser was set:
                    content.parse(zip, handler, metadata, context);
                }
            }
            entry = zip.getNextEntry();
        }
        helper.addTextToHandler(xhtml);
    } catch (Exception e) {
        LOG.info("Extract error", e);
    } finally {
        if (helper != null) {
            helper.close();
        }
    }

    // Only now call the end document
    if (handler.getEndDocumentWasCalled()) {
        handler.reallyEndDocument();
    }
}

From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;//from w  w w.  j a va  2s  .  c o m
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS,
                    "Signature");

            XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);

            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Element signatureElement = (Element) signatureNodeList.item(idx);

                //LOG.debug("signatureValue: "+signatureElement.getTextContent());

                xadesValidation.prepareDocument(signatureElement);
                KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
                DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
                ODFURIDereferencer dereferencer = new ODFURIDereferencer(document);
                domValidateContext.setURIDereferencer(dereferencer);

                XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
                XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
                boolean valid = xmlSignature.validate(domValidateContext);
                if (!valid) {
                    LOG.debug("invalid signature");
                    continue;
                }

                checkIntegrity(xmlSignature, document, originalDocument);

                X509Certificate signingCertificate = keySelector.getCertificate();
                SignatureInfo signatureInfo = xadesValidation.validate(documentSignatures, xmlSignature,
                        signatureElement, signingCertificate);
                signatureInfos.add(signatureInfo);
            }
            return signatureInfos;
        }
    }
    return signatureInfos;
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*  ww  w  .j  a  v a 2  s.com*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:org.atomspace.pi2c.runtime.Server.java

/**
 * Loading Jars with the ClassLoader and Unzip the included Jar-Files from libs folder
 * @throws SecurityException//from  w  w  w  . ja v a  2s  .  c  om
 * @throws NoSuchMethodException
 * @throws IOException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private void loadingJars() throws SecurityException, NoSuchMethodException, IOException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    // Prepair Classloader Reflextion
    Method m = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    m.setAccessible(true);

    ClassLoader cl = Server.class.getClassLoader();

    // Create Temp Dir
    File appTmp = new File(System.getProperty("java.io.tmpdir") + "/"
            + location.toString().substring(location.toString().lastIndexOf("/")));
    System.err.println("::: use temporary dir path '" + appTmp.getAbsolutePath() + "'");
    if (!appTmp.exists()) {
        appTmp.mkdir();
    }

    ZipInputStream zip = new ZipInputStream(location.openStream());
    ZipEntry entry = zip.getNextEntry();
    while (entry != null) {
        if (entry.getName().startsWith("libs/") && entry.getName().endsWith(".jar")
                || (entry.getName().endsWith("MANIFEST.MF"))) {
            System.err.println("::: " + new Date() + " ::: Extracting " + entry.getName() + " :::");
            InputStream is = cl.getResourceAsStream(entry.getName());
            File tmpJar = new File(appTmp + "/" + entry.getName().substring(entry.getName().lastIndexOf("/")));
            unzip(is, tmpJar);
            m.invoke(cl, new Object[] { tmpJar.toURI().toURL() });
        } else {
            System.err.println("::: " + new Date() + " ::: ignore " + entry.getName() + " :::");

        }
        entry = zip.getNextEntry();
    }
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Gets all files in jar.//from   w w w  .  j  ava 2s  .c om
 *
 * @param clazz the clazz
 * @return the list of files and paths in jar
 */
default List<String> getAllFilesInJar(Class<?> clazz) {

    List<String> list = new ArrayList<>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src != null) {
        try {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            while (true) {
                ZipEntry e = zip.getNextEntry();
                if (e == null)
                    break;
                String name = e.getName();
                if (name.contains(".properties")) {
                    list.add(name);
                    System.out.println(name);
                }

            }
            zip.close();
            jar = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return list;
}

From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Read from compressed file//from  ww w . j  ava  2s.  c  om
 * 
 * @param srcPath
 *            path of compressed file
 * @param fileCompressor
 *            FileCompressor object
 * @throws Exception
 */
@Override
public void read(String srcPath, FileCompressor fileCompressor) throws Exception {
    long t1 = System.currentTimeMillis();
    byte[] data = FileUtil.convertFileToByte(srcPath);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    BZip2CompressorInputStream cis = new BZip2CompressorInputStream(bais);
    ZipInputStream zis = new ZipInputStream(cis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[1024];
        int readByte;
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            long t2 = System.currentTimeMillis();
            baos = new ByteArrayOutputStream();
            readByte = zis.read(buffer);
            while (readByte != -1) {
                baos.write(buffer, 0, readByte);
                readByte = zis.read(buffer);
            }
            zis.closeEntry();
            BinaryFile binaryFile = new BinaryFile(entry.getName(), baos.toByteArray());
            fileCompressor.addBinaryFile(binaryFile);
            LogUtil.createAddFileLog(fileCompressor, binaryFile, t2, System.currentTimeMillis());
            entry = zis.getNextEntry();
        }
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on get compressor file", e);
    } finally {
        baos.close();
        zis.close();
        cis.close();
        bais.close();
    }
    LogUtil.createReadLog(fileCompressor, srcPath, data.length, t1, System.currentTimeMillis());
}