Example usage for java.util.zip ZipFile getEntry

List of usage examples for java.util.zip ZipFile getEntry

Introduction

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

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();//from w  w w  .j  a v a2 s. c  om
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:org.apache.tika.parser.odf.OpenDocumentParser.java

private void handleZipFile(ZipFile zipFile, Metadata metadata, ParseContext context,
        EndDocumentShieldingContentHandler handler) throws IOException, TikaException, SAXException {
    // If we can, process the metadata first, then the
    //  rest of the file afterwards (TIKA-1353)
    // Only possible to guarantee that when opened from a file not a stream

    ZipEntry entry = zipFile.getEntry(META_NAME);
    if (entry != null) {
        handleZipEntry(entry, zipFile.getInputStream(entry), metadata, context, handler);
    }//from   w w  w . j  a  v  a2 s. co  m

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();
        if (!META_NAME.equals(entry.getName())) {
            handleZipEntry(entry, zipFile.getInputStream(entry), metadata, context, handler);
        }
    }
}

From source file:com.denimgroup.threadfix.importer.loader.ScanTypeCalculationServiceImpl.java

private String figureOutZip(String fileName) {

    String result = null;/*from   w  w  w.  ja v  a2  s  .c  o m*/
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(DiskUtils.getScratchFile(fileName));

        if (zipFile.getEntry("audit.fvdl") != null) {
            result = ScannerType.FORTIFY.getDbName();
        } else if (ZipFileUtils.getZipEntry("issue_index.js", zipFile) != null) {
            result = ScannerType.SKIPFISH.getDisplayName();
        } else if (zipFile.getEntry("index.html") != null && zipFile.getEntry("scanview.css") != null) {
            result = ScannerType.CLANG.getDisplayName();
        }
    } catch (FileNotFoundException e) {
        log.warn("Unable to find zip file.", e);
    } catch (IOException e) {
        log.warn("Exception encountered while trying to identify zip file.", e);
    } finally {
        closeQuietly(zipFile);
    }

    return result;
}

From source file:net.minecraftforge.fml.server.FMLServerHandler.java

@Override
public void addModAsResource(ModContainer container) {
    String langFile = "assets/" + container.getModId().toLowerCase() + "/lang/en_US.lang";
    File source = container.getSource();
    InputStream stream = null;//w w  w  .  j a va 2 s .  c o m
    ZipFile zip = null;
    try {
        if (source.isDirectory() && (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
            stream = new FileInputStream(new File(source.toURI().resolve(langFile).getPath()));
        } else {
            zip = new ZipFile(source);
            ZipEntry entry = zip.getEntry(langFile);
            if (entry == null)
                throw new FileNotFoundException();
            stream = zip.getInputStream(entry);
        }
        LanguageMap.inject(stream);
    } catch (IOException e) {
        // hush
    } catch (Exception e) {
        FMLLog.getLogger().error(e);
    } finally {
        IOUtils.closeQuietly(stream);
        try {
            if (zip != null)
                zip.close();
        } catch (IOException e) {
            // shush
        }
    }
}

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Extract the files related to the configuration of the given name.
 * //from   w  ww.j  av  a 2  s  .c  o  m
 * @param zipFile
 * @param configurationName
 * @return
 * @throws IOException
 */
private boolean extract(ZipFile zipFile, String configurationName) throws IOException {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());
    File file;
    ZipEntry entry;
    int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING, XMLConfigurationDAO.FILE_NAME_TRANSFORM,
            XMLConfigurationDAO.FILE_NAME_CONFIG };
    for (int type : types) {
        file = xmlConfigurationDAO.getConfigurationFile(configurationName, type);
        entry = zipFile.getEntry(file.getName());
        if (entry == null)
            return false;

        copy(zipFile.getInputStream(entry), FileUtils.openOutputStream(file));
    }

    return true;
}

From source file:org.nuxeo.ecm.platform.filemanager.service.extension.CSVZipImporter.java

@Override
public DocumentModel create(CoreSession documentManager, Blob content, String path, boolean overwrite,
        String filename, TypeManager typeService) throws IOException {
    ZipFile zip = null;
    try (CloseableFile source = content.getCloseableFile()) {
        zip = getArchiveFileIfValid(source.getFile());
        if (zip == null) {
            return null;
        }//from w  w  w. ja va 2  s  .c o  m

        DocumentModel container = documentManager.getDocument(new PathRef(path));

        ZipEntry index = zip.getEntry(MARKER);
        try (Reader reader = new InputStreamReader(zip.getInputStream(index));
                CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader());) {

            Map<String, Integer> header = csvParser.getHeaderMap();
            for (CSVRecord csvRecord : csvParser) {
                String type = null;
                String id = null;
                Map<String, String> stringValues = new HashMap<>();
                for (String headerValue : header.keySet()) {
                    String lineValue = csvRecord.get(headerValue);
                    if ("type".equalsIgnoreCase(headerValue)) {
                        type = lineValue;
                    } else if ("id".equalsIgnoreCase(headerValue)) {
                        id = lineValue;
                    } else {
                        stringValues.put(headerValue, lineValue);
                    }
                }

                boolean updateDoc = false;
                // get doc for update
                DocumentModel targetDoc = null;
                if (id != null) {
                    // update ?
                    String targetPath = new Path(path).append(id).toString();
                    if (documentManager.exists(new PathRef(targetPath))) {
                        targetDoc = documentManager.getDocument(new PathRef(targetPath));
                        updateDoc = true;
                    }
                }

                // create doc if needed
                if (targetDoc == null) {
                    if (type == null) {
                        log.error("Can not create doc without a type, skipping line");
                        continue;
                    }

                    if (id == null) {
                        id = IdUtils.generateStringId();
                    }
                    targetDoc = documentManager.createDocumentModel(path, id, type);
                }

                // update doc properties
                DocumentType targetDocType = targetDoc.getDocumentType();
                for (String fname : stringValues.keySet()) {

                    String stringValue = stringValues.get(fname);
                    Field field = null;
                    boolean usePrefix = false;
                    String schemaName = null;
                    String fieldName = null;

                    if (fname.contains(":")) {
                        if (targetDocType.hasField(fname)) {
                            field = targetDocType.getField(fname);
                            usePrefix = true;
                        }
                    } else if (fname.contains(".")) {
                        String[] parts = fname.split("\\.");
                        schemaName = parts[0];
                        fieldName = parts[1];
                        if (targetDocType.hasSchema(schemaName)) {
                            field = targetDocType.getField(fieldName);
                            usePrefix = false;
                        }
                    } else {
                        if (targetDocType.hasField(fname)) {
                            field = targetDocType.getField(fname);
                            usePrefix = false;
                            schemaName = field.getDeclaringType().getSchemaName();
                        }
                    }

                    if (field != null) {
                        Serializable fieldValue = getFieldValue(field, stringValue, zip);

                        if (fieldValue != null) {
                            if (usePrefix) {
                                targetDoc.setPropertyValue(fname, fieldValue);
                            } else {
                                targetDoc.setProperty(schemaName, fieldName, fieldValue);
                            }
                        }
                    }
                }
                if (updateDoc) {
                    documentManager.saveDocument(targetDoc);
                } else {
                    documentManager.createDocument(targetDoc);
                }
            }
        }
        return container;
    } finally {
        IOUtils.closeQuietly(zip);
    }
}

From source file:org.n52.geoar.codebase.resources.InfoResource.java

private void extractPluginImage(File pluginFile, File pluginImageFile) throws IOException {
    ZipFile zipFile = new ZipFile(pluginFile);
    ZipEntry pluginIconEntry = zipFile.getEntry(GEOAR_IMAGE_NAME);
    if (pluginIconEntry == null) {
        return;/*ww w. java 2s  .co  m*/
    }

    InputStream inputStream = zipFile.getInputStream(pluginIconEntry);
    OutputStream outputStream = new FileOutputStream(pluginImageFile);

    int read = 0;
    byte[] bytes = new byte[4096];
    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }

    zipFile.close();
    outputStream.flush();
    outputStream.close();
}

From source file:io.frictionlessdata.datapackage.Package.java

/**
 * Load from String representation of JSON object or from a zip file path.
 * @param jsonStringSource/*ww  w .j a v  a2s .  c om*/
 * @param strict
 * @throws IOException
 * @throws DataPackageException
 * @throws ValidationException
 */
public Package(String jsonStringSource, boolean strict)
        throws IOException, DataPackageException, ValidationException {
    this.strictValidation = strict;

    // If zip file is given.
    if (jsonStringSource.toLowerCase().endsWith(".zip")) {
        // Read in memory the file inside the zip.
        ZipFile zipFile = new ZipFile(jsonStringSource);
        ZipEntry entry = zipFile.getEntry(DATAPACKAGE_FILENAME);

        // Throw exception if expected datapackage.json file not found.
        if (entry == null) {
            throw new DataPackageException(
                    "The zip file does not contain the expected file: " + DATAPACKAGE_FILENAME);
        }

        // Read the datapackage.json file inside the zip
        try (InputStream is = zipFile.getInputStream(entry)) {
            StringBuilder out = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                }
            }

            // Create and set the JSONObject for the datapackage.json that was read from inside the zip file.
            this.setJson(new JSONObject(out.toString()));

            // Validate.
            this.validate();
        }

    } else {
        // Create and set the JSONObject fpr the String representation of desriptor JSON object.
        this.setJson(new JSONObject(jsonStringSource));

        // If String representation of desriptor JSON object is provided.
        this.validate();
    }
}

From source file:org.sakaiproject.nakamura.importer.ImportSiteArchiveServlet.java

private Node copyFile(String zipEntryName, String fileName, String sitePath, String contentType,
        Session session, ZipFile zip) {
    final String id = uniqueId();
    final String path = FilesConstants.USER_FILESTORE + "/" + id;
    Node node = null;/* ww w  .j a va2  s  .co m*/
    try {
        final InputStream in = zip.getInputStream(zip.getEntry(zipEntryName));
        node = makeNode(path, session);
        node.setProperty(JcrConstants.JCR_NAME, fileName);
        node.setProperty(JcrConstants.JCR_MIMETYPE, contentType);
        ValueFactory valueFactory = session.getValueFactory();
        Binary content = valueFactory.createBinary(in);
        node.setProperty(JcrConstants.JCR_CONTENT, content);
        final String linkPath = sitePath + "/_files/" + fileName;
        FileUtils.createLink(node, linkPath, slingRepository);
    } catch (RepositoryException e) {
        throw new Error(e);
    } catch (IOException e) {
        throw new Error(e);
    }
    return node;
}

From source file:parser.axml.ManifestParser.java

/**
 * ? AndroidManifest.xml  <code>ManifestInfo </code>.
 *
 * @param pFile apk /* w w w .j a  va  2s .  c o  m*/
 * @return ??????? null
 */
public ManifestInfo parse(File pFile) throws IOException {
    ManifestInfo manifestInfo = new ManifestInfo();
    m_noback = false;

    ZipFile zipFile;
    InputStream aXMLInputStream = null;
    InputStream arscInputStream = null;
    try {
        zipFile = new ZipFile(pFile);
        ZipEntry zipEntry = zipFile.getEntry("AndroidManifest.xml");

        if (zipEntry != null) {
            aXMLInputStream = zipFile.getInputStream(zipEntry);
        } else {
            manifestInfo = null;
        }

        zipEntry = zipFile.getEntry("resources.arsc");
        if (zipEntry != null) {
            arscInputStream = zipFile.getInputStream(zipEntry);
        }

        if (arscInputStream != null) {
            m_arsc = IOUtils.toByteArray(arscInputStream);
        }
    } catch (IOException e) {
        throw new IOException(e.getMessage());
    }

    if (aXMLInputStream != null) {
        try {
            parseManifest(aXMLInputStream, manifestInfo);
            manifestInfo.back = !m_noback;
            manifestInfo.xml = (m_xml == null) ? null : m_xml.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    try {
        zipFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (aXMLInputStream != null) {
        try {
            aXMLInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (arscInputStream != null) {
        try {
            arscInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return manifestInfo;
}