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:javaaxp.core.service.impl.fileaccess.XPSZipFileAccess.java

private byte[] getEntryData(ZipArchiveEntry ze) {
    return fDataCache.get(ze.getName());
}

From source file:com.naryx.tagfusion.expression.function.file.ZipList.java

private cfQueryResultData performZiplist(cfSession session, File zipfile, String charset) throws IOException {
    ZipFile zFile = null;/*  w ww. j a v  a 2s. c  o m*/
    try {
        cfQueryResultData filesQuery = new cfQueryResultData(new String[] { "name", "type", "compressedsize",
                "size", "compressedpercent", "datelastmodified", "comment" }, "CFZIP");
        zFile = new ZipFile(zipfile, charset);

        List<Map<String, cfData>> allResultRows = new ArrayList<Map<String, cfData>>();
        Map<String, cfData> resultRow;
        Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries();
        ZipArchiveEntry nextEntry = null;
        long size;
        double compressed;

        while (files.hasMoreElements()) {
            nextEntry = (ZipArchiveEntry) files.nextElement();
            resultRow = new FastMap<String, cfData>(8);
            resultRow.put("name", new cfStringData(nextEntry.getName()));
            resultRow.put("comment", new cfStringData(nextEntry.getComment()));
            resultRow.put("datelastmodified", new cfDateData(nextEntry.getTime()));

            if (nextEntry.isDirectory()) {
                resultRow.put("compressedsize", new cfNumberData(0));
                resultRow.put("size", new cfNumberData(0));
                resultRow.put("type", new cfStringData("Dir"));
                resultRow.put("compressedpercent", new cfNumberData(0));

            } else {
                size = nextEntry.getSize();
                resultRow.put("compressedsize",
                        new cfStringData(String.valueOf(nextEntry.getCompressedSize())));
                resultRow.put("size", new cfStringData(String.valueOf(size)));
                resultRow.put("type", new cfStringData("File"));
                if (size != 0) {
                    compressed = ((float) nextEntry.getCompressedSize() / (float) size);
                    resultRow.put("compressedpercent",
                            new cfStringData(String.valueOf(100 - (int) (compressed * 100))));
                } else {
                    resultRow.put("compressedpercent", new cfStringData("0"));
                }
            }

            allResultRows.add(resultRow);
        }
        filesQuery.populateQuery(allResultRows);
        return filesQuery;
    } finally {
        try {
            zFile.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Close entry.//ww  w  .j ava  2 s  .  c  o  m
 *
 * @param output the output
 * @param outEntry the out entry
 * @param crc the crc
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void closeEntry(ZipArchiveOutputStream output, ZipArchiveEntry outEntry, long crc) throws IOException {
    output.flush();
    output.closeArchiveEntry();
    if (outEntry.getCrc() != crc)
        throw new IOException("CRC mismatch for " + outEntry.getName());
}

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

public void expand(File source, File destDir) throws IOException {
    assertIsZip(source);//w  ww . j  av  a  2  s  .c o m

    try (ZipFile zf = new ZipFile(source)) {
        byte[] b = new byte[512];

        Enumeration entries = zf.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry e = (ZipArchiveEntry) entries.nextElement();
            //log.debug("Extracting zip: "+ficheroZip.getName());

            // baskslash-protection: zip format expects only 'fw' slashes
            String name = FileUtils.toCanonicalPath(e.getName());

            if (e.isDirectory()) {
                //log.debug("\tExtracting directory "+e.getName());
                File dir = new File(destDir, name);
                dir.mkdirs();
                continue;
            }

            //log.debug("\tExtracting file "+name);
            File outFile = new File(destDir, name);
            if (!outFile.getParentFile().exists()) {
                //log.warn("weird zip: had to create parent: "+outFile.getParentFile());
                outFile.getParentFile().mkdirs();
            }
            try (FileOutputStream fos = new FileOutputStream(outFile); InputStream is = zf.getInputStream(e)) {
                int len;
                while ((len = is.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
            }
        }
    }
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta./*from   w ww . j a  v a 2 s.  c  o m*/
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java

@Override
public Folder importFolder(Folder parentFolder, byte[] bytes) throws IOException {
    if (!security.isEntityOpPermitted(Folder.class, EntityOp.CREATE)) {
        throw new AccessDeniedException(PermissionType.ENTITY_OP, Folder.class.getSimpleName());
    }/*  w  w w.ja  va2s .  com*/

    Folder folder = null;
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ZipArchiveInputStream archiveReader;
    archiveReader = new ZipArchiveInputStream(byteArrayInputStream);
    ZipArchiveEntry archiveEntry;

    while (((archiveEntry = archiveReader.getNextZipEntry()) != null) && (folder == null)) {
        if (archiveEntry.getName().equals("folder.xml")) {
            String xml = new String(IOUtils.toByteArray(archiveReader), StandardCharsets.UTF_8);
            folder = (Folder) createXStream().fromXML(xml);
        }
    }

    byteArrayInputStream.close();

    if (folder != null) {
        checkImportPermissions(folder);
        folder.setParent(parentFolder);
        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            em.setSoftDeletion(false);
            Folder existingFolder = em.find(Folder.class, folder.getId());
            if (existingFolder != null) {
                checkImportPermissions(existingFolder);
                folder.setVersion(existingFolder.getVersion());
                folder.setCreateTs(existingFolder.getCreateTs());
                folder.setCreatedBy(existingFolder.getCreatedBy());
            } else {
                User user = userSessionSource.getUserSession().getUser();
                folder.setCreatedBy(user.getLoginLowerCase());
                folder.setCreateTs(timeSource.currentTimestamp());
                folder.setUpdatedBy(null);
                folder.setUpdateTs(null);
                folder.setVersion(0);
            }

            em.merge(folder);
            tx.commit();
        } finally {
            tx.end();
        }
    }
    return folder;
}

From source file:javaaxp.core.service.impl.fileaccess.XPSZipFileAccess.java

public BufferedImage getImageResource(String imageSource, IDocumentReference docRef) throws XPSError {
    ZipArchiveEntry ze = getEntry(getAbsolutePath(docRef, imageSource));

    if (fElementCache.get(ze.getName()) != null) {
        return (BufferedImage) fElementCache.get(ze.getName());
    }/*  w w  w .  j  a  v  a 2 s.c o m*/

    InputStream in = null;
    try {
        in = getInputStream(ze);
        BufferedImage bi = ImageIO.read(in);
        fElementCache.put(ze.getName(), bi);
        return bi;
    } catch (IOException e) {
        throw new XPSError(e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:javaaxp.core.service.impl.fileaccess.XPSZipFileAccess.java

private <T> T readElementFromZipArchiveEntry(ZipArchiveEntry ze) throws XPSError {
    @SuppressWarnings("unchecked")
    T elem = (T) fElementCache.get(ze.getName());
    if (elem != null) {
        return elem;
    }/*from   www .j a va2 s . c om*/

    InputStream in = null;
    try {
        byte b[] = getEntryData(ze);
        in = new ByteArrayInputStream(b);
        @SuppressWarnings("unchecked")
        T toReturn = (T) XPSJAXBElementProducer.createXPSElement(in);
        fElementCache.put(ze.getName(), toReturn);
        return toReturn;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftExporterBeanTest.java

@Test
public void testExportArchiveZip() throws Exception {
    final Project p = makeGoodProject();
    final List<PackagingInfo> infos = this.bean.getAvailablePackagingInfos(p);
    final PackagingInfo zipPi = Iterables.find(infos, new Predicate<PackagingInfo>() {
        @Override/*from  w  w w.  j  a  v a  2s  .co  m*/
        public boolean apply(PackagingInfo t) {
            return t.getMethod() == PackagingInfo.PackagingMethod.ZIP;
        }
    });
    final File f = File.createTempFile("test", zipPi.getName());
    final FileOutputStream fos = new FileOutputStream(f);

    this.bean.export(p, "http://example.com/my_experiemnt", PackagingInfo.PackagingMethod.ZIP, fos);
    fos.close();
    final ZipFile zf = new ZipFile(f);
    final Enumeration<ZipArchiveEntry> en = zf.getEntries();
    final Set<String> entries = new HashSet<String>();
    entries.addAll(java.util.Arrays.asList("test-exp-id.soft.txt", "raw_file.data", "derived_file.data",
            "supplimental.data"));
    while (en.hasMoreElements()) {
        final ZipArchiveEntry ze = en.nextElement();
        assertTrue(ze.getName() + " unexpected", entries.remove(ze.getName()));

    }
    assertTrue(entries.toString() + " not found", entries.isEmpty());
}

From source file:de.catma.ui.repository.wizard.FileTypePanel.java

private ArrayList<SourceDocumentResult> makeSourceDocumentResultsFromInputFile(TechInfoSet inputTechInfoSet)
        throws MalformedURLException, IOException {

    ArrayList<SourceDocumentResult> output = new ArrayList<SourceDocumentResult>();

    FileType inputFileType = FileType.getFileType(inputTechInfoSet.getMimeType());

    if (inputFileType != FileType.ZIP) {
        SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();

        String sourceDocumentID = repository.getIdFromURI(inputTechInfoSet.getURI());
        outputSourceDocumentResult.setSourceDocumentID(sourceDocumentID);

        SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult.getSourceDocumentInfo();
        outputSourceDocumentInfo.setTechInfoSet(new TechInfoSet(inputTechInfoSet));
        outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

        outputSourceDocumentInfo.getTechInfoSet().setFileType(inputFileType);

        output.add(outputSourceDocumentResult);
    } else { //TODO: put this somewhere sensible
        URI uri = inputTechInfoSet.getURI();
        ZipFile zipFile = new ZipFile(uri.getPath());
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

        String tempDir = ((CatmaApplication) UI.getCurrent()).getTempDirectory();
        IDGenerator idGenerator = new IDGenerator();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = FilenameUtils.getName(entry.getName());
            String fileId = idGenerator.generate();

            File entryDestination = new File(tempDir, fileId);
            if (entryDestination.exists()) {
                entryDestination.delete();
            }//from  w w  w.java  2s.  c o m

            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination));
                IOUtils.copy(bis, bos);
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(bos);

                SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();
                URI newURI = entryDestination.toURI();

                String repositoryId = repository.getIdFromURI(newURI); // we need to do this as a catma:// is appended

                outputSourceDocumentResult.setSourceDocumentID(repositoryId);

                SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult
                        .getSourceDocumentInfo();
                TechInfoSet newTechInfoSet = new TechInfoSet(fileName, null, newURI); // TODO: MimeType detection ?
                FileType newFileType = FileType.getFileTypeFromName(fileName);
                newTechInfoSet.setFileType(newFileType);

                outputSourceDocumentInfo.setTechInfoSet(newTechInfoSet);
                outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

                output.add(outputSourceDocumentResult);
            }
        }

        ZipFile.closeQuietly(zipFile);
    }

    for (SourceDocumentResult sdr : output) {
        TechInfoSet sdrTechInfoSet = sdr.getSourceDocumentInfo().getTechInfoSet();
        String sdrSourceDocumentId = sdr.getSourceDocumentID();

        ProtocolHandler protocolHandler = getProtocolHandlerForUri(sdrTechInfoSet.getURI(), sdrSourceDocumentId,
                sdrTechInfoSet.getMimeType());
        String mimeType = protocolHandler.getMimeType();

        sdrTechInfoSet.setMimeType(mimeType);
        FileType sdrFileType = FileType.getFileType(mimeType);
        sdrTechInfoSet.setFileType(sdrFileType);

        if (sdrFileType.isCharsetSupported()) {
            Charset charset = Charset.forName(protocolHandler.getEncoding());
            sdrTechInfoSet.setCharset(charset);
        } else {
            sdrTechInfoSet.setFileOSType(FileOSType.INDEPENDENT);
        }

        loadSourceDocumentAndContent(sdr);
    }

    return output;
}