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:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Entry to new name.//  w w  w . j  av a2 s .  com
 *
 * @param source the source
 * @param name the name
 * @return the zip archive entry
 * @throws ZipException the zip exception
 */
private ZipArchiveEntry copyEntry(ZipArchiveEntry source) throws ZipException {
    ZipArchiveEntry ret = new ZipArchiveEntry(source.getName());
    byte[] extra = source.getExtra();
    if (extra != null) {
        ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ));
    } else {
        ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true)));
    }
    ret.setInternalAttributes(source.getInternalAttributes());
    ret.setExternalAttributes(source.getExternalAttributes());
    ret.setExtraFields(source.getExtraFields(true));
    return ret;
}

From source file:com.nabla.wapp.report.server.handler.AddReportHandler.java

@Override
protected int add(AddReport record, IUserSessionContext ctx) throws DispatchException, SQLException {
    int id;/* w w w.  ja  v a2  s . co m*/
    final Connection conn = ctx.getWriteConnection();
    final PreparedStatement stmt = StatementFormat.prepare(ctx.getReadConnection(),
            "SELECT * FROM import_data WHERE id=?;", record.getFileId());
    try {
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next())
                throw new ActionException(CommonServerErrors.NO_DATA);
            if (!ctx.getSessionId().equals(rs.getString("userSessionId")))
                throw new ActionException(CommonServerErrors.ACCESS_DENIED);

            final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
            try {
                if (ReportZipFile.acceptContentType(rs.getString("content_type"))) {
                    final ReportZipFile zip = new ReportZipFile(rs.getBinaryStream("content"));
                    try {
                        final ZipArchiveEntry design = zip.getReportDesign();
                        if (design == null)
                            throw new DispatchException(ReportErrors.ADD_REPORT_NO_REPORT_DESIGN_FOUND);
                        id = reportManager.addReport(conn, design.getName(), zip.getInputStream(design),
                                zip.getInputStream(design));
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.PROPERTIES_FILE_EXTENSION); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadLocaleReportName(conn, id, e.getName(), zip.getInputStream(e));
                        }
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.RESOURCE_FILE_EXTENSIONS); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadReportResource(conn, id, e.getName(), zip.getInputStream(e));
                        }
                    } finally {
                        zip.close();
                    }
                } else {
                    id = reportManager.addReport(conn, FilenameUtils.getBaseName(rs.getString("file_name")),
                            rs.getBinaryStream("content"), rs.getBinaryStream("content"));
                }
                guard.setSuccess();
            } finally {
                guard.close();
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    Database.executeUpdate(conn, "DELETE FROM import_data WHERE id=?;", record.getFileId());
    return id;
}

From source file:adams.core.io.ZipUtils.java

/**
 * Unzips the files in a ZIP file. Files can be filtered based on their
 * filename, using a regular expression (the matching sense can be inverted).
 *
 * @param input   the ZIP file to unzip// w  w w  .j a  v  a2  s  . c  o m
 * @param outputDir   the directory where to store the extracted files
 * @param createDirs   whether to re-create the directory structure from the
 *          ZIP file
 * @param match   the regular expression that the files are matched against
 * @param invertMatch   whether to invert the matching sense
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      the successfully extracted files
 */
@MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html")
public static List<File> decompress(File input, File outputDir, boolean createDirs, BaseRegExp match,
        boolean invertMatch, int bufferSize, StringBuilder errors) {
    List<File> result;
    ZipFile archive;
    Enumeration<ZipArchiveEntry> enm;
    ZipArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    BufferedInputStream in;
    BufferedOutputStream out;
    FileOutputStream fos;
    int len;
    String error;
    long read;

    result = new ArrayList<>();
    archive = null;
    try {
        // unzip archive
        buffer = new byte[bufferSize];
        archive = new ZipFile(input.getAbsoluteFile());
        enm = archive.getEntries();
        while (enm.hasMoreElements()) {
            entry = enm.nextElement();

            if (entry.isDirectory() && !createDirs)
                continue;

            // does name match?
            if (!match.isMatchAll() && !match.isEmpty()) {
                if (invertMatch && match.isMatch(entry.getName()))
                    continue;
                else if (!invertMatch && !match.isMatch(entry.getName()))
                    continue;
            }

            // extract
            if (entry.isDirectory() && createDirs) {
                outFile = new File(outputDir.getAbsolutePath() + File.separator + entry.getName());
                if (!outFile.mkdirs()) {
                    error = "Failed to create directory '" + outFile.getAbsolutePath() + "'!";
                    System.err.println(error);
                    errors.append(error + "\n");
                }
            } else {
                in = null;
                out = null;
                fos = null;
                outName = null;
                try {
                    // assemble output name
                    outName = outputDir.getAbsolutePath() + File.separator;
                    if (createDirs)
                        outName += entry.getName();
                    else
                        outName += new File(entry.getName()).getName();

                    // create directory, if necessary
                    outFile = new File(outName).getParentFile();
                    if (!outFile.exists()) {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            continue;
                        }
                    }

                    // extract data
                    in = new BufferedInputStream(archive.getInputStream(entry));
                    fos = new FileOutputStream(outName);
                    out = new BufferedOutputStream(fos, bufferSize);
                    read = 0;
                    while (read < entry.getSize()) {
                        len = in.read(buffer);
                        read += len;
                        out.write(buffer, 0, len);
                    }
                    result.add(new File(outName));
                } catch (Exception e) {
                    error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                    System.err.println(error);
                    errors.append(error + "\n");
                } finally {
                    FileUtils.closeQuietly(in);
                    FileUtils.closeQuietly(out);
                    FileUtils.closeQuietly(fos);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

From source file:com.nabla.wapp.report.server.handler.UpgradeReportHandler.java

@Override
protected void update(UpgradeReport record, IUserSessionContext ctx) throws DispatchException, SQLException {
    final Connection conn = ctx.getWriteConnection();
    final PreparedStatement stmt = StatementFormat.prepare(ctx.getReadConnection(),
            "SELECT * FROM import_data WHERE id=?;", record.getFileId());
    try {//from   ww  w . jav  a 2  s . com
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next())
                throw new ActionException(CommonServerErrors.NO_DATA);
            if (!ctx.getSessionId().equals(rs.getString("userSessionId")))
                throw new ActionException(CommonServerErrors.ACCESS_DENIED);
            final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn);
            try {
                Database.executeUpdate(conn, "DELETE FROM report_resource WHERE report_id=?;",
                        record.getReportId());
                Database.executeUpdate(conn, "DELETE FROM report_name_localized WHERE report_id=?;",
                        record.getReportId());
                if (ReportZipFile.acceptContentType(rs.getString("content_type"))) {
                    final ReportZipFile zip = new ReportZipFile(rs.getBinaryStream("content"));
                    try {
                        final ZipArchiveEntry design = zip.getReportDesign();
                        if (design == null)
                            throw new DispatchException(ReportErrors.ADD_REPORT_NO_REPORT_DESIGN_FOUND);
                        reportManager.upgradeReport(conn, record.getReportId(), design.getName(),
                                zip.getInputStream(design));
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.PROPERTIES_FILE_EXTENSION); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadLocaleReportName(conn, record.getReportId(), e.getName(),
                                    zip.getInputStream(e));
                        }
                        for (Enumeration<ZipArchiveEntry> iter = zip
                                .getEntries(ReportManager.RESOURCE_FILE_EXTENSIONS); iter.hasMoreElements();) {
                            final ZipArchiveEntry e = iter.nextElement();
                            reportManager.loadReportResource(conn, record.getReportId(), e.getName(),
                                    zip.getInputStream(e));
                        }
                    } finally {
                        zip.close();
                    }
                } else
                    reportManager.upgradeReport(conn, record.getReportId(),
                            FilenameUtils.getBaseName(rs.getString("file_name")),
                            rs.getBinaryStream("content"));
                guard.setSuccess();
            } finally {
                guard.close();
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    Database.executeUpdate(conn, "DELETE FROM import_data WHERE id=?;", record.getFileId());
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OPCKeySelector.java

@Override
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method,
        XMLCryptoContext context) throws KeySelectorException {
    try {//w w  w  . ja v  a2s  . c  o m
        return super.select(keyInfo, purpose, method, context);
    } catch (KeySelectorException e) {
        LOG.debug("no key found via ds:KeyInfo key selector");
    }
    LOG.debug("signature resource name: " + this.signatureResourceName);
    String signatureSegment = this.signatureResourceName.substring(0,
            this.signatureResourceName.lastIndexOf("/"));
    LOG.debug("signature segment: " + signatureSegment);
    String signatureBase = this.signatureResourceName
            .substring(this.signatureResourceName.lastIndexOf("/") + 1);
    LOG.debug("signature base: " + signatureBase);
    String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels";
    LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName);

    ZipArchiveInputStream zipInputStream;
    try {
        zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    ZipArchiveEntry zipEntry;
    try {
        while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
            if (signatureRelationshipResourceName.equals(zipEntry.getName())) {
                break;
            }
        }
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    if (null == zipEntry) {
        LOG.warn("relationship part not present: " + signatureRelationshipResourceName);
        throw new KeySelectorException("no key found");
    }
    LOG.debug("signature relationship part found");

    JAXBElement<CTRelationships> signatureRelationshipsElement;
    try {
        signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller
                .unmarshal(zipInputStream);
    } catch (JAXBException e) {
        throw new KeySelectorException(e);
    }
    CTRelationships signatureRelationships = signatureRelationshipsElement.getValue();
    List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship();
    List<String> certificateResourceNames = new LinkedList<String>();
    for (CTRelationship signatureRelationship : signatureRelationshipList) {
        if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) {
            String certificateResourceName = signatureRelationship.getTarget().substring(1);
            certificateResourceNames.add(certificateResourceName);
        }
    }

    X509Certificate endEntityCertificate = null;

    for (String certificateResourceName : certificateResourceNames) {
        try {
            zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        try {
            while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
                if (certificateResourceName.equals(zipEntry.getName())) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        if (null == zipEntry) {
            LOG.warn("certificate part not present: " + certificateResourceName);
            continue;
        }
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream);
        } catch (CertificateException e) {
            throw new KeySelectorException(e);
        }
        LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
        if (-1 != certificate.getBasicConstraints()) {
            LOG.debug("skipping CA certificate");
            continue;
        }
        if (null != endEntityCertificate) {
            throw new KeySelectorException("two possible end entity certificates");
        }
        endEntityCertificate = certificate;
    }
    if (null == endEntityCertificate) {
        throw new KeySelectorException("no key found");
    }
    this.certificate = endEntityCertificate;
    return this;
}

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

public boolean extractOne(File source, String path, File dest) throws IOException {
    assertIsZip(source);//from w  ww  .j  av  a2  s. com

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

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

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

            //                System.err.println(" "+name+" =? "+path);
            if (!name.equals(path) || e.isDirectory())
                continue;

            if (!dest.getParentFile().exists()) {
                //log.warn("weird zip: had to create parent: "+outFile.getParentFile());
                dest.getParentFile().mkdirs();
            }

            try (FileOutputStream fos = new FileOutputStream(dest); InputStream is = zf.getInputStream(e)) {
                int len;
                while ((len = is.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
                return true;
            }
        }
    }
    return false;
}

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

/**
 * Find best source.//  w  ww .  j  a v  a 2  s .c  om
 *
 * @param source the source
 * @param target the target
 * @param targetEntry the target entry
 * @return the zip archive entry
 * @throws IOException Signals that an I/O exception has occurred.
 */
public ZipArchiveEntry findBestSource(ZipFile source, ZipFile target, ZipArchiveEntry targetEntry)
        throws IOException {
    ArrayList<ZipArchiveEntry> ret = new ArrayList<>();
    for (ZipArchiveEntry next : source.getEntries(targetEntry.getName())) {
        if (next.getCrc() == targetEntry.getCrc())
            return next;
        ret.add(next);
    }
    if (ret.size() == 0)
        return null;
    if (ret.size() == 1 || targetEntry.isDirectory())
        return ret.get(0);
    //More than one and no matching crc --- need to calculate xdeltas and pick the  shortest
    ZipArchiveEntry retEntry = null;
    for (ZipArchiveEntry sourceEntry : ret) {
        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);
            byte[] nextDiff = outbytes.toByteArray();
            if (calculatedDelta == null || calculatedDelta.length > nextDiff.length) {
                retEntry = sourceEntry;
                calculatedDelta = nextDiff;
            }
        }
    }
    return retEntry;
}

From source file:com.kalix.tools.kibana.KibanaController.java

/**
 * download kibana from remote server/* w  w w. j a v a 2 s . c o  m*/
 *
 * @throws Exception
 */
public void download() throws Exception {
    File target = new File(workingDirectory, KIBANA_FOLDER);
    if (target.exists()) {
        LOGGER.warn("Kibana folder already exists, download is skipped");
        return;
    }
    LOGGER.debug("Downloading Kibana from {}", KIBANA_LOCATION);
    if (isWindows()) {
        try (ZipArchiveInputStream inputStream = new ZipArchiveInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            ZipArchiveEntry entry;
            while ((entry = (ZipArchiveEntry) inputStream.getNextEntry()) != null) {
                File file = new File(workingDirectory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    int read;
                    byte[] buffer = new byte[4096];
                    try (FileOutputStream outputStream = new FileOutputStream(file)) {
                        while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                            outputStream.write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    } else {
        try (GzipCompressorInputStream gzInputStream = new GzipCompressorInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            try (TarArchiveInputStream inputStream = new TarArchiveInputStream(gzInputStream)) {
                TarArchiveEntry entry;
                while ((entry = (TarArchiveEntry) inputStream.getNextEntry()) != null) {
                    File file = new File(workingDirectory, entry.getName());
                    if (entry.isDirectory()) {
                        file.mkdirs();
                    } else {
                        int read;
                        byte[] buffer = new byte[4096];
                        try (FileOutputStream outputStream = new FileOutputStream(file)) {
                            while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                                outputStream.write(buffer, 0, read);
                            }
                        }
                        file.setLastModified(entry.getLastModifiedDate().getTime());
                        if (entry instanceof TarArchiveEntry) {
                            int mode = ((TarArchiveEntry) entry).getMode();
                            if ((mode & 00100) > 0) {
                                file.setExecutable(true, (mode & 00001) == 0);
                            }
                        }
                    }
                }
            }
        }
    }
    overrideConfig();
}

From source file:autoupdater.FileDAO.java

/**
 * Unzips a zip archive./*from www .  ja va 2  s .  c o m*/
 *
 * @param zip the zipfile to unzip
 * @param fileLocationOnDiskToDownloadTo the folder to unzip in
 * @return true if successful
 * @throws IOException
 */
public boolean unzipFile(ZipFile zip, File fileLocationOnDiskToDownloadTo) throws IOException {
    FileOutputStream dest = null;
    InputStream inStream = null;
    Enumeration<ZipArchiveEntry> zipFileEnum = zip.getEntries();
    while (zipFileEnum.hasMoreElements()) {
        ZipArchiveEntry entry = zipFileEnum.nextElement();
        File destFile = new File(fileLocationOnDiskToDownloadTo, entry.getName());
        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                throw new IOException("could not create the folders to unzip in");
            }
        }
        if (!entry.isDirectory()) {
            try {
                dest = new FileOutputStream(destFile);
                inStream = zip.getInputStream(entry);
                IOUtils.copyLarge(inStream, dest);
            } finally {
                if (dest != null) {
                    dest.close();
                }
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            if (!destFile.exists()) {
                if (!destFile.mkdirs()) {
                    throw new IOException("could not create folders to unzip file");
                }
            }
        }
    }
    zip.close();
    return true;
}

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

private void performUnzip(cfSession _session, File _zipfile, File _destination, String charset,
        boolean _flatten, boolean overwrite) throws cfmRunTimeException {
    ZipFile zFile = null;//from   w  ww.ja va  2 s.c  om
    try {
        zFile = new ZipFile(_zipfile, charset);
    } catch (IOException ze) {
        throwException(_session, "Failed to extract zip file. Check the file is a valid zip file.");
    }

    BufferedInputStream in = null;
    InputStream zIn = null;
    FileOutputStream fout = null;
    File nextFile = null;
    String destinationFilename;
    byte[] buffer = new byte[4096];
    int read;

    try {
        Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries();

        if (files == null) {
            throwException(_session, "Failed to extract zip file. Check the file is a valid zip file.");
        }

        ZipArchiveEntry nextEntry;

        // while unzip stuff goes here
        while (files.hasMoreElements()) {
            nextEntry = files.nextElement();
            destinationFilename = nextEntry.getName();
            File checkFile = new File(
                    _destination.getAbsolutePath() + File.separatorChar + destinationFilename);

            if (checkFile.exists() && !overwrite) {
                throwException(_session, "File already exist");

            } else {
                if (!nextEntry.isDirectory()) {

                    if (_flatten) {
                        int pathEnd = destinationFilename.lastIndexOf('/');
                        if (pathEnd != -1)
                            destinationFilename = destinationFilename.substring(pathEnd + 1);
                    }

                    nextFile = new File(
                            _destination.getAbsolutePath() + File.separatorChar + destinationFilename);
                    try {
                        nextFile = nextFile.getCanonicalFile();
                    } catch (IOException ignore) {
                    } // use original nextFile if getCanonicalFile() fails

                    File parent = nextFile.getParentFile();
                    if (parent != null) {
                        parent.mkdirs(); // create the parent directory structure if needed
                    }

                    try {
                        zIn = zFile.getInputStream(nextEntry);
                        in = new BufferedInputStream(zIn);
                        fout = new FileOutputStream(nextFile, false);
                        while ((read = in.read(buffer)) != -1) {
                            fout.write(buffer, 0, read);
                        }

                        fout.flush();
                    } catch (IOException ioe) {
                        throwException(_session, "Failed to extract entry [" + nextEntry.getName()
                                + "] from zip file to " + nextFile.getAbsolutePath()
                                + ". Check the permissions are suitable to allow this file to be written.");
                    } finally {
                        StreamUtil.closeStream(in);
                        StreamUtil.closeStream(zIn);
                        StreamUtil.closeStream(fout);
                    }

                } else if (!_flatten) {
                    destinationFilename = nextEntry.getName();
                    nextFile = new File(
                            _destination.getAbsolutePath() + File.separatorChar + destinationFilename);
                    try {
                        nextFile = nextFile.getCanonicalFile();
                    } catch (IOException ignore) {
                        // use original nextFile if getCanonicalFile() fails
                    }
                    nextFile.mkdirs();
                }
            }
        }
    } finally {
        try {
            zFile.close();
        } catch (IOException ignored) {
        }
    }

}