Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName.

Prototype

public String getName() 

Source Link

Document

Get the name of the entry.

Usage

From source file:net.sf.regain.crawler.preparator.ZipPreparator.java

/**
 * Prepares the document for indexing//from www .j av  a  2s.c o  m
 *
 * @param rawDocument the document
 * @throws RegainException if preparation goes wrong
 */
@Override
public void prepare(RawDocument rawDocument) throws RegainException {
    ArchiveInputStream ain = null;
    ZipInputStream zipInputStream = new ZipInputStream(rawDocument.getContentAsStream());

    PreparatorFactory preparatorFactory = new PreparatorFactory(new DummyCrawlerConfig());
    try {
        ain = new ArchiveStreamFactory().createArchiveInputStream("zip", rawDocument.getContentAsStream());
        ZipArchiveEntry entry;
        while ((entry = (ZipArchiveEntry) ain.getNextEntry()) != null) {
            String s = String.format("Entry: %s len %d added %TD", entry.getName(), entry.getSize(),
                    new Date(entry.getTime()));
            System.out.println(s);

            Preparator preparator = null;
            ByteArrayOutputStream byteArrayOutputStream = null;

            RawDocument rawZipDocument = new RawDocument(null, null, null, null);
            rawZipDocument.setUrl(new File(entry.getName()).toURI().toString());

            try {
                byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(zipInputStream, byteArrayOutputStream);
                rawZipDocument.setContent(byteArrayOutputStream.toByteArray());
                preparator = preparatorFactory.get(rawZipDocument);

            } finally {
                IOUtils.closeQuietly(byteArrayOutputStream);
            }

            if (preparator != null) {
                preparator.prepare(rawZipDocument);
                // concatenates contents
                setCleanedContent(new StringBuilder().append(getCleanedContent()).append("\n")
                        .append(preparator.getCleanedContent()).toString());
                setTitle(getTitle() + " " + preparator.getTitle());
                setSummary(getSummary() + " " + preparator.getSummary());
                setCleanedMetaData(getCleanedMetaData() + " " + preparator.getCleanedMetaData());
                setHeadlines(getHeadlines() + " " + preparator.getHeadlines());
                preparator.cleanUp();
            }
        }

    } catch (IOException | ArchiveException e) {
        e.printStackTrace();
    } finally {
        //IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(ain);
    }

}

From source file:brut.directory.ZipRODirectory.java

private void loadAll() {
    mFiles = new LinkedHashSet<String>();
    mDirs = new LinkedHashMap<String, AbstractDirectory>();

    int prefixLen = getPath().length();
    Enumeration<? extends ZipArchiveEntry> entries = getZipFile().getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();

        // ignore general purpose bit, since AOSP does
        entry.getGeneralPurposeBit().useEncryption(false);
        String name = entry.getName();

        if (name.equals(getPath()) || !name.startsWith(getPath())) {
            continue;
        }/*from w w w .j  a  va2s.co m*/

        String subname = name.substring(prefixLen);

        int pos = subname.indexOf(separator);
        if (pos == -1) {
            if (!entry.isDirectory()) {
                mFiles.add(subname);
                continue;
            }
        } else {
            subname = subname.substring(0, pos);
        }

        if (!mDirs.containsKey(subname)) {
            AbstractDirectory dir = new ZipRODirectory(getZipFile(), getPath() + subname + separator);
            mDirs.put(subname, dir);
        }
    }
}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

public ArrayList<String> list(File source) throws IOException {
    assertIsZip(source);/* w  w w.jav a 2  s.co  m*/

    ArrayList<String> paths = new ArrayList<String>();
    try (ZipFile zf = new ZipFile(source)) {
        Enumeration entries = zf.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry e = (ZipArchiveEntry) entries.nextElement();

            String name = FileUtils.toCanonicalPath(e.getName());
            if (e.isDirectory()) {
                continue;
            }

            paths.add(name);
        }
    }
    return paths;
}

From source file:info.magnolia.ui.framework.command.ImportZipCommand.java

protected void handleFileEntry(ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
    String fileName = entry.getName();
    if (StringUtils.contains(fileName, "/")) {
        fileName = StringUtils.substringAfterLast(fileName, "/");
    }/*  www .  j ava  2s.c o m*/

    String extension = StringUtils.substringAfterLast(fileName, ".");
    InputStream stream = zip.getInputStream(entry);
    FileOutputStream os = null;
    try {
        UploadReceiver receiver = createReceiver();

        String folderPath = extractEntryPath(entry);
        if (folderPath.startsWith("/")) {
            folderPath = folderPath.substring(1);
        }
        Node folder = getJCRNode(context);
        if (StringUtils.isNotBlank(folderPath)) {
            if (folder.hasNode(folderPath)) {
                folder = folder.getNode(folderPath);
            } else {
                folder = NodeUtil.createPath(folder, folderPath, NodeTypes.Folder.NAME, true);
            }
        }
        receiver.setFieldType(UploadField.FieldType.BYTE_ARRAY);
        receiver.receiveUpload(fileName,
                StringUtils.defaultIfEmpty(MIMEMapping.getMIMEType(extension), DEFAULT_MIME_TYPE));
        receiver.setValue(IOUtils.toByteArray(stream));

        doHandleEntryFromReceiver(folder, receiver);
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(os);
    }
}

From source file:be.fedict.eid.applet.service.signer.xps.XPSSignatureVerifier.java

private Document loadDocument(URL url, String signatureResourceName)
        throws IOException, ParserConfigurationException, SAXException {
    ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true);
    ZipArchiveEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
        if (false == signatureResourceName.equals(zipEntry.getName())) {
            continue;
        }/*  ww  w .java2s .  c  om*/
        Document document = loadDocument(zipInputStream);
        return document;
    }
    return null;
}

From source file:br.com.thiaguten.archive.ZipArchive.java

/**
 * Override to make use of the ZipFile class instead of the ZipArchiveInputStream class.
 * https://commons.apache.org/proper/commons-compress/zip.html
 *//*from w  w w .  j  ava2 s . c  o  m*/
@Override
public Path decompress(Path path) throws IOException {
    Path decompressDir = removeExtension(path);

    logger.debug("reading archive file " + path);

    try (ZipFile zipFile = new ZipFile(path.toString())) {

        // creates a new decompress folder to not override if already exists
        // if you do not want this behavior, just comment this line
        decompressDir = createFile(ArchiveAction.DECOMPRESS, decompressDir.getParent(), decompressDir);

        createDirectories(decompressDir);

        logger.debug("creating the decompress destination directory " + decompressDir);

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            final ZipArchiveEntry zipArchiveEntry = entries.nextElement();

            if (zipFile.canReadEntryData(zipArchiveEntry)) {
                final String entryName = zipArchiveEntry.getName();
                final InputStream archiveInputStream = zipFile.getInputStream(zipArchiveEntry);
                final Path target = Paths.get(decompressDir.toString(), entryName);
                final Path parent = target.getParent();

                if (parent != null && !exists(parent)) {
                    createDirectories(parent);
                }

                logger.debug("reading compressed path " + entryName);

                if (!zipArchiveEntry.isDirectory()) {
                    try (OutputStream outputStream = new BufferedOutputStream(newOutputStream(target))) {

                        logger.debug("writting compressed " + entryName + " file in the decompress directory");

                        //                            byte[] content = new byte[(int) zipArchiveEntry.getSize()];
                        //                            outputStream.write(content);
                        IOUtils.copy(archiveInputStream, outputStream);
                    }
                }
            }
        }

        logger.debug("finishing the decompress in the directory: " + decompressDir);

    }

    return decompressDir;
}

From source file:io.wcm.maven.plugins.contentpackage.unpacker.ContentUnpacker.java

private void unpackEntry(ZipFile zipFile, ZipArchiveEntry entry, File outputDirectory)
        throws IOException, MojoExecutionException {
    if (entry.isDirectory()) {
        File directory = FileUtils.getFile(outputDirectory, entry.getName());
        directory.mkdirs();//  w  w  w  .  j a v  a2 s  . c  o m
    } else {
        InputStream entryStream = null;
        FileOutputStream fos = null;
        try {
            entryStream = zipFile.getInputStream(entry);
            File outputFile = FileUtils.getFile(outputDirectory, entry.getName());
            if (outputFile.exists()) {
                outputFile.delete();
            }
            File directory = outputFile.getParentFile();
            directory.mkdirs();
            fos = new FileOutputStream(outputFile);
            if (applyXmlExcludes(entry.getName())) {
                // write file with XML filtering
                try {
                    writeXmlWithExcludes(entryStream, fos);
                } catch (JDOMException ex) {
                    throw new MojoExecutionException("Unable to parse XML file: " + entry.getName(), ex);
                }
            } else {
                // write file directly without XML filtering
                IOUtils.copy(entryStream, fos);
            }
        } finally {
            IOUtils.closeQuietly(entryStream);
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.nit.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*w ww .  j av  a2 s .  c o  m*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipArchiveEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    // Log.i(AnkiDroidApp.TAG, "uncompress " + name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e);
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e);
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e);
        }
    }
    return true;
}

From source file:be.fedict.eid.applet.service.signer.xps.XPSSignatureVerifier.java

private List<String> getSignatureResourceNames(URL url)
        throws IOException, ParserConfigurationException, SAXException, TransformerException, JAXBException {
    List<String> signatureResourceNames = new LinkedList<String>();
    ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true);
    ZipArchiveEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
        if ("_rels/.rels".equals(zipEntry.getName())) {
            break;
        }/*from w w  w .  ja v  a  2s  . com*/
    }
    if (null == zipEntry) {
        LOG.debug("no _rels/.rels relationship part present");
        return signatureResourceNames;
    }

    String dsOriginPart = null;
    JAXBElement<CTRelationships> packageRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller
            .unmarshal(zipInputStream);
    CTRelationships packageRelationships = packageRelationshipsElement.getValue();
    List<CTRelationship> packageRelationshipList = packageRelationships.getRelationship();
    for (CTRelationship packageRelationship : packageRelationshipList) {
        if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_ORIGIN_REL_TYPE.equals(packageRelationship.getType())) {
            dsOriginPart = packageRelationship.getTarget();
            break;
        }
    }
    if (null == dsOriginPart) {
        LOG.debug("no Digital Signature Origin part present");
        return signatureResourceNames;
    }
    LOG.debug("Digital Signature Origin part: " + dsOriginPart);
    String dsOriginName = dsOriginPart.substring(dsOriginPart.lastIndexOf("/") + 1);
    LOG.debug("Digital Signature Origin base: " + dsOriginName);
    String dsOriginSegment = dsOriginPart.substring(0, dsOriginPart.lastIndexOf("/")) + "/";
    LOG.debug("Digital Signature Origin segment: " + dsOriginSegment);
    String dsOriginRels = dsOriginSegment + "_rels/" + dsOriginName + ".rels";
    LOG.debug("Digital Signature Origin relationship part: " + dsOriginRels);
    if (dsOriginRels.startsWith("/")) {
        dsOriginRels = dsOriginRels.substring(1);
    }

    zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true);
    while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
        if (dsOriginRels.equals(zipEntry.getName())) {
            break;
        }
    }
    if (null == zipEntry) {
        LOG.debug("no Digital Signature Origin relationship part present");
        return signatureResourceNames;
    }

    JAXBElement<CTRelationships> dsoRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller
            .unmarshal(zipInputStream);
    CTRelationships dsoRelationships = dsoRelationshipsElement.getValue();
    List<CTRelationship> dsoRelationshipList = dsoRelationships.getRelationship();
    for (CTRelationship dsoRelationship : dsoRelationshipList) {
        if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_REL_TYPE.equals(dsoRelationship.getType())) {
            String signatureResourceName;
            if (dsoRelationship.getTarget().startsWith("/")) {
                signatureResourceName = dsoRelationship.getTarget();
            } else {
                signatureResourceName = dsOriginSegment + dsoRelationship.getTarget();
            }
            if (signatureResourceName.startsWith("/")) {
                signatureResourceName = signatureResourceName.substring(1);
            }
            LOG.debug("signature resource name: " + signatureResourceName);
            signatureResourceNames.add(signatureResourceName);
        }
    }

    return signatureResourceNames;
}

From source file:algorithm.ZipPackaging.java

@Override
protected List<RestoredFile> restore(File zipFile) throws IOException {
    List<RestoredFile> extractedFiles = new ArrayList<RestoredFile>();
    try {//from ww  w .ja  v a  2s  .c o  m
        InputStream inputStream = new FileInputStream(zipFile);
        ArchiveInputStream archiveInputStream = new ArchiveStreamFactory()
                .createArchiveInputStream(ArchiveStreamFactory.ZIP, inputStream);
        ZipArchiveEntry entry = (ZipArchiveEntry) archiveInputStream.getNextEntry();
        while (entry != null) {
            RestoredFile extractedFile = new RestoredFile(RESTORED_DIRECTORY + entry.getName());
            OutputStream outputStream = new FileOutputStream(extractedFile);
            IOUtils.copy(archiveInputStream, outputStream);
            outputStream.close();
            extractedFiles.add(extractedFile);
            entry = (ZipArchiveEntry) archiveInputStream.getNextEntry();
        }
        archiveInputStream.close();
        inputStream.close();
    } catch (ArchiveException e) {
    }
    for (RestoredFile file : extractedFiles) {
        file.algorithm = this;
        file.checksumValid = true;
        file.restorationNote = "The algorithm doesn't alter these files, so they are brought to its original state. No checksum validation executed.";
        // every file in a .zip archive is a payload file!
        file.wasPayload = true;
        /*
         * Checksum validation isn't executed, because the PayloadSegment
         * class isn't used and therewith the checksums of the original
         * files are unknown.
         */
        for (RestoredFile relatedFile : extractedFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return extractedFiles;
}