Example usage for org.apache.commons.compress.archivers ArchiveEntry getName

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

Introduction

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

Prototype

public String getName();

Source Link

Document

The name of the entry in the archive.

Usage

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * check if an archive is valid by reading it.
 * @throws RuntimeException if trying to run this with no archive
 *///from   ww  w.  j  a v  a2  s. c  om
private void verifyArchiveIntegrity() throws RuntimeException, KeyException {
    File f;
    long total;
    short old_percentage, percentage;
    CountingInputStream counter;
    ArchiveInputStream is;
    byte[] buffer;
    boolean dirToExtractFound;

    Logger.info("verifying archive integrity");

    if (mCurrentTask == null || mCurrentTask.path == null)
        throw new RuntimeException("no archive to test");

    mBuilder.setContentTitle(getString(R.string.checking)).setSmallIcon(android.R.drawable.ic_popup_sync)
            .setContentText("").setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    f = new File(mCurrentTask.path);
    try {
        counter = new CountingInputStream(new FileInputStream(f));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("archive '%s' does not exists", mCurrentTask.path));
    }

    dirToExtractFound = mCurrentTask.dirToExtract == null;

    try {
        is = openArchiveStream(counter);
        ArchiveEntry entry;
        buffer = new byte[2048];
        total = f.length();
        old_percentage = -1;
        // consume the archive
        while (mRunning && (entry = is.getNextEntry()) != null)
            if (!dirToExtractFound && entry.getName().startsWith(mCurrentTask.dirToExtract))
                dirToExtractFound = true;
        while (mRunning && is.read(buffer) > 0) {
            percentage = (short) (((double) counter.getBytesRead() / total) * 100);
            if (percentage != old_percentage) {
                mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                old_percentage = percentage;
            }
        }
    } catch (IOException e) {
        throw new KeyException("corrupted archive: " + e.getMessage());
    }

    if (!mRunning)
        throw new CancellationException("archive integrity check cancelled");

    if (!dirToExtractFound)
        throw new KeyException(String.format("archive '%s' does not contains required '%s' directory",
                mCurrentTask.path, mCurrentTask.dirToExtract));
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * extract an archive into a directory// w  ww. j a v a 2  s .com
 *
 * @throws IOException if some I/O error occurs
 * @throws java.util.concurrent.CancellationException if task is cancelled by user
 * @throws java.lang.InterruptedException when the the running thread get cancelled.
 */
private void extract() throws CancellationException, RuntimeException, IOException, InterruptedException {
    ArchiveInputStream is = null;
    ArchiveEntry entry;
    CountingInputStream counter;
    File f, inFile;
    File[] list;
    String name;
    FileOutputStream fos = null;
    byte data[] = new byte[2048];
    int mode;
    int count;
    long total;
    short percentage, old_percentage;

    if (mCurrentTask.path == null || mCurrentTask.outputDir == null)
        return;

    mBuilder.setContentTitle(getString(R.string.extracting)).setContentText("").setContentInfo("")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(100, 0, false);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    Logger.info(String.format("extracting '%s' to '%s'", mCurrentTask.path, mCurrentTask.outputDir));

    try {
        inFile = new File(mCurrentTask.path);
        total = inFile.length();
        counter = new CountingInputStream(new FileInputStream(inFile));
        is = openArchiveStream(counter);
        old_percentage = -1;

        f = new File(mCurrentTask.outputDir);
        if (f.exists() && f.isDirectory() && (list = f.listFiles()) != null && list.length > 2)
            wipe();

        if (is instanceof TarArchiveInputStream && mCurrentTask.modeMap == null)
            mCurrentTask.modeMap = new HashMap<Integer, String>();

        while (mRunning && (entry = is.getNextEntry()) != null) {
            name = entry.getName().replaceFirst("^\\./?", "");

            if (mCurrentTask.dirToExtract != null) {
                if (!name.startsWith(mCurrentTask.dirToExtract))
                    continue;
                else
                    name = name.substring(mCurrentTask.dirToExtract.length());
            }

            f = new File(mCurrentTask.outputDir, name);

            if (entry.isDirectory()) {
                if (!f.exists()) {
                    if (!f.mkdirs()) {
                        throw new IOException(
                                String.format("Couldn't create directory '%s'.", f.getAbsolutePath()));
                    }
                }
            } else {
                BufferedOutputStream bof = new BufferedOutputStream(new FileOutputStream(f));

                while (mRunning && (count = is.read(data)) != -1) {
                    bof.write(data, 0, count);
                    percentage = (short) (((double) counter.getBytesRead() / total) * 100);
                    if (percentage != old_percentage) {
                        mBuilder.setProgress(100, percentage, false).setContentInfo(percentage + "%");
                        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                        old_percentage = percentage;
                    }
                }
                bof.flush();
                bof.close();
            }
            // Zip does not store file permissions.
            if (entry instanceof TarArchiveEntry) {
                mode = ((TarArchiveEntry) entry).getMode();

                if (!mCurrentTask.modeMap.containsKey(mode))
                    mCurrentTask.modeMap.put(mode, entry.getName() + " ");
                else
                    mCurrentTask.modeMap.put(mode,
                            mCurrentTask.modeMap.get(mode).concat(entry.getName() + " "));
            }
        }

        if (!mRunning)
            throw new CancellationException("extraction cancelled.");

        Logger.info("extraction completed");

        f = new File(mCurrentTask.outputDir, ".nomedia");
        if (f.createNewFile())
            Logger.info(".nomedia created");

        if (mCurrentTask.versionString != null && !mCurrentTask.versionString.isEmpty()) {
            f = new File(mCurrentTask.outputDir, "VERSION");
            fos = new FileOutputStream(f);
            fos.write(mCurrentTask.versionString.getBytes());
        } else
            Logger.warning("version string not found");

        mBuilder.setContentInfo("").setProgress(100, 100, true);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    } finally {
        if (is != null)
            is.close();
        if (fos != null)
            fos.close();
    }
}

From source file:net.staticsnow.nexus.repository.apt.internal.hosted.AptHostedFacet.java

@Transactional(retryOn = { ONeedRetryException.class })
public void ingestAsset(Payload body) throws IOException, PGPException {
    AptFacet aptFacet = getRepository().facet(AptFacet.class);
    StorageTx tx = UnitOfWork.currentTx();
    Bucket bucket = tx.findBucket(getRepository());

    ControlFile control = null;//from  w  ww.  jav  a  2  s .  c o  m
    try (TempStreamSupplier supplier = new TempStreamSupplier(body.openInputStream());
            ArArchiveInputStream is = new ArArchiveInputStream(supplier.get())) {
        ArchiveEntry debEntry;
        while ((debEntry = is.getNextEntry()) != null) {
            InputStream controlStream;
            switch (debEntry.getName()) {
            case "control.tar":
                controlStream = new CloseShieldInputStream(is);
                break;
            case "control.tar.gz":
                controlStream = new GZIPInputStream(new CloseShieldInputStream(is));
                break;
            case "control.tar.xz":
                controlStream = new XZCompressorInputStream(new CloseShieldInputStream(is));
            default:
                continue;
            }

            try (TarArchiveInputStream controlTarStream = new TarArchiveInputStream(controlStream)) {
                ArchiveEntry tarEntry;
                while ((tarEntry = controlTarStream.getNextEntry()) != null) {
                    if (tarEntry.getName().equals("control") || tarEntry.getName().equals("./control")) {
                        control = new ControlFileParser().parseControlFile(controlTarStream);
                    }
                }
            }
        }

        if (control == null) {
            throw new IllegalOperationException("Invalid Debian package supplied");
        }

        String name = control.getField("Package").map(f -> f.value).get();
        String version = control.getField("Version").map(f -> f.value).get();
        String architecture = control.getField("Architecture").map(f -> f.value).get();

        String assetName = name + "_" + version + "_" + architecture + ".deb";
        String assetPath = "pool/" + name.substring(0, 1) + "/" + name + "/" + assetName;

        Content content = aptFacet.put(assetPath,
                new StreamPayload(() -> supplier.get(), body.getSize(), body.getContentType()));
        Asset asset = Content.findAsset(tx, bucket, content);
        String indexSection = buildIndexSection(control, asset.size(),
                asset.getChecksums(FacetHelper.hashAlgorithms), assetPath);
        asset.formatAttributes().set(P_ARCHITECTURE, architecture);
        asset.formatAttributes().set(P_PACKAGE_NAME, name);
        asset.formatAttributes().set(P_PACKAGE_VERSION, version);
        asset.formatAttributes().set(P_INDEX_SECTION, indexSection);
        asset.formatAttributes().set(P_ASSET_KIND, "DEB");
        tx.saveAsset(asset);

        List<AssetChange> changes = new ArrayList<>();
        changes.add(new AssetChange(AssetAction.ADDED, asset));

        for (Asset removed : selectOldPackagesToRemove(name, architecture)) {
            tx.deleteAsset(removed);
            changes.add(new AssetChange(AssetAction.REMOVED, removed));
        }

        rebuildIndexesInTransaction(tx, changes.stream().toArray(AssetChange[]::new));
    }
}

From source file:org.apache.ant.compress.resources.CommonsCompressArchiveResource.java

/**
 * Return an InputStream for reading the contents of this Resource.
 * @return an InputStream object.//  w  w  w.  ja  v a2  s . c  o  m
 * @throws IOException if the archive cannot be opened,
 *         or the entry cannot be read.
 */
public InputStream getInputStream() throws IOException {
    if (isReference()) {
        return ((Resource) getCheckedRef()).getInputStream();
    }
    final ArchiveInputStream i = getStream();
    ArchiveEntry ae = null;
    while ((ae = i.getNextEntry()) != null) {
        if (ae.getName().equals(getName())) {
            return i;
        }
    }

    FileUtils.close(i);
    throw new BuildException("no entry " + getName() + " in " + getArchive());
}

From source file:org.apache.ant.compress.resources.CommonsCompressArchiveResource.java

/**
 * fetches information from the named entry inside the archive.
 *///from  w w  w . j  a v  a  2 s. c  om
protected void fetchEntry() {
    ArchiveInputStream i = null;
    try {
        i = getStream();
        ArchiveEntry ae = null;
        while ((ae = i.getNextEntry()) != null) {
            if (ae.getName().equals(getName())) {
                setEntry(ae);
                return;
            }
        }
    } catch (IOException e) {
        log(e.getMessage(), Project.MSG_DEBUG);
        throw new BuildException(e);
    } finally {
        if (i != null) {
            FileUtils.close(i);
        }
    }
    setEntry(null);
}

From source file:org.apache.ant.compress.resources.CommonsCompressArchiveResource.java

protected void setEntry(ArchiveEntry e) {
    if (e == null) {
        setExists(false);//ww  w .ja v  a  2 s.  c o  m
        return;
    }
    setName(e.getName());
    setExists(true);
    setLastModified(e.getLastModifiedDate().getTime());
    setDirectory(e.isDirectory());
    setSize(e.getSize());
    setMode(EntryHelper.getMode(e));
    uid = EntryHelper.getUserId(e);
    gid = EntryHelper.getGroupId(e);
}

From source file:org.apache.ant.compress.resources.CommonsCompressArchiveScanner.java

/**
 * Fills the file and directory maps with resources read from the
 * archive.//from   w  ww .  j a  v  a  2 s.c  om
 *
 * @param src the archive to scan.
 * @param encoding encoding used to encode file names inside the archive.
 * @param fileEntries Map (name to resource) of non-directory
 * resources found inside the archive.
 * @param matchFileEntries Map (name to resource) of non-directory
 * resources found inside the archive that matched all include
 * patterns and didn't match any exclude patterns.
 * @param dirEntries Map (name to resource) of directory
 * resources found inside the archive.
 * @param matchDirEntries Map (name to resource) of directory
 * resources found inside the archive that matched all include
 * patterns and didn't match any exclude patterns.
 */
protected void fillMapsFromArchive(Resource src, String encoding, Map fileEntries, Map matchFileEntries,
        Map dirEntries, Map matchDirEntries) {
    ArchiveEntry entry = null;
    ArchiveInputStream ai = null;

    try {
        try {
            ai = StreamHelper.getInputStream(factory, src, encoding);
            if (ai == null) {
                ai = factory.getArchiveStream(new BufferedInputStream(src.getInputStream()), encoding);
            }
        } catch (IOException ex) {
            throw new BuildException("problem opening " + src, ex);
        }
        while ((entry = ai.getNextEntry()) != null) {
            if (skipUnreadable && !ai.canReadEntryData(entry)) {
                log(Messages.skippedIsUnreadable(entry));
                continue;
            }
            Resource r = builder.buildResource(src, encoding, entry);
            String name = entry.getName();
            if (entry.isDirectory()) {
                name = trimSeparator(name);
                dirEntries.put(name, r);
                if (match(name)) {
                    matchDirEntries.put(name, r);
                }
            } else {
                fileEntries.put(name, r);
                if (match(name)) {
                    matchFileEntries.put(name, r);
                }
            }
        }
    } catch (IOException ex) {
        throw new BuildException("problem reading " + src, ex);
    } finally {
        FileUtils.close(ai);
    }
}

From source file:org.apache.ant.compress.taskdefs.ExpandBase.java

private void expandArchiveStream(String name, ArchiveInputStream is, File dir) throws IOException {
    FileNameMapper mapper = getMapper();
    log("Expanding: " + name + " into " + dir, Project.MSG_INFO);
    boolean empty = true;
    ArchiveEntry ent = null;
    while ((ent = is.getNextEntry()) != null) {
        if (skipUnreadable && !is.canReadEntryData(ent)) {
            log(Messages.skippedIsUnreadable(ent));
            continue;
        }//from www .j av a2 s .  c  o  m
        empty = false;
        log("extracting " + ent.getName(), Project.MSG_DEBUG);
        extractFile(FileUtils.getFileUtils(), null, dir, is, ent.getName(), ent.getLastModifiedDate(),
                ent.isDirectory(), mapper);
    }
    if (empty && getFailOnEmptyArchive()) {
        throw new BuildException("archive '" + name + "' is empty");
    }
    log("expand complete", Project.MSG_VERBOSE);
}

From source file:org.apache.ant.compress.util.Messages.java

/**
 * Message to log when Commons Compress knows it cannot handle a given
 * entry.// w  w w  .  j av a2s.c  o m
 */
public static String skippedIsUnreadable(ArchiveEntry ent) {
    return MessageFormat.format("skipping {0}, Apache Commons Compress " + "cannot read it.",
            new Object[] { ent.getName() });
}

From source file:org.apache.flex.utilities.converter.flash.FlashConverter.java

/**
 * This method generates those artifacts that resemble the runtime part of the Flash SDK.
 *
 * @throws ConverterException/*from ww  w .j  av a 2  s.c o m*/
 */
protected void generateRuntimeArtifacts() throws ConverterException {
    // Create a list of all libs that should belong to the Flash SDK runtime.
    final File directory = new File(rootSourceDirectory, "runtimes" + File.separator + "player");
    if (!directory.exists() || !directory.isDirectory()) {
        System.out.println("Skipping runtime generation.");
        return;
    }
    final List<File> playerVersions = new ArrayList<File>();
    playerVersions.addAll(Arrays.asList(directory.listFiles(new FlashRuntimeFilter())));

    // In really old SDKs the flash-player was installed in the players directory directly.
    if (new File(directory, "win").exists()) {
        playerVersions.add(directory);
    }

    // Generate artifacts for every jar in the input directories.
    for (final File versionDir : playerVersions) {
        // The flash-player 9 is installed directly in the player directory.
        String playerVersionString;
        if (versionDir == directory) {
            playerVersionString = "9.0";
        } else {
            playerVersionString = versionDir.getName();
        }

        final double playerVersion = Double.valueOf(playerVersionString);
        final NumberFormat doubleFormat = NumberFormat.getInstance(Locale.US);
        doubleFormat.setMinimumFractionDigits(1);
        doubleFormat.setMaximumFractionDigits(1);
        final String version = doubleFormat.format(playerVersion);

        final MavenArtifact playerArtifact = new MavenArtifact();
        playerArtifact.setGroupId("com.adobe.flash");
        playerArtifact.setArtifactId("runtime");
        playerArtifact.setVersion(version);
        playerArtifact.setPackaging("exe");

        // Deploy Windows binaries.
        final File windowsDirectory = new File(versionDir, "win");
        if (windowsDirectory.exists()) {
            // Find out if a flash-player binary exists.
            File flashPlayerBinary = null;
            if (new File(windowsDirectory, "FlashPlayerDebugger.exe").exists()) {
                flashPlayerBinary = new File(windowsDirectory, "FlashPlayerDebugger.exe");
            } else if (new File(windowsDirectory, "FlashPlayer.exe").exists()) {
                flashPlayerBinary = new File(windowsDirectory, "FlashPlayer.exe");
            }

            // If a binary exists, copy it to the target and create a pom for it.
            if (flashPlayerBinary != null) {
                playerArtifact.addBinaryArtifact("win", flashPlayerBinary);
            }
        }

        // Deploy Mac binaries.
        final File macDirectory = new File(versionDir, "mac");
        if (macDirectory.exists()) {
            // Find out if a flash-player binary exists.
            File flashPlayerBinary = null;
            if (new File(macDirectory, "Flash Player.app.zip").exists()) {
                flashPlayerBinary = new File(macDirectory, "Flash Player.app.zip");
            } else if (new File(macDirectory, "Flash Player Debugger.app.zip").exists()) {
                flashPlayerBinary = new File(macDirectory, "Flash Player Debugger.app.zip");
            }

            // If a binary exists, copy it to the target and create a pom for it.
            if (flashPlayerBinary != null) {
                playerArtifact.addBinaryArtifact("mac", flashPlayerBinary);
            }
        }

        // Deploy Linux binaries.
        final File lnxDirectory = new File(versionDir, "lnx");
        if (lnxDirectory.exists()) {
            // Find out if a flash-player binary exists.
            File flashPlayerBinary;
            if (new File(lnxDirectory, "flashplayer.tar.gz").exists()) {
                flashPlayerBinary = new File(lnxDirectory, "flashplayer.tar.gz");
            } else if (new File(lnxDirectory, "flashplayerdebugger.tar.gz").exists()) {
                flashPlayerBinary = new File(lnxDirectory, "flashplayerdebugger.tar.gz");
            } else {
                throw new ConverterException("Couldn't find player archive.");
            }

            // Decompress the archive.
            // First unzip it.
            final FileInputStream fin;
            try {
                fin = new FileInputStream(flashPlayerBinary);
                final BufferedInputStream in = new BufferedInputStream(fin);
                final File tempTarFile = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                        ".tar");
                final FileOutputStream out = new FileOutputStream(tempTarFile);
                final GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
                final byte[] buffer = new byte[1024];
                int n;
                while (-1 != (n = gzIn.read(buffer))) {
                    out.write(buffer, 0, n);
                }
                out.close();
                gzIn.close();

                // Then untar it.
                File uncompressedBinary = null;
                final FileInputStream tarFileInputStream = new FileInputStream(tempTarFile);
                final TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(
                        tarFileInputStream);
                ArchiveEntry entry;
                while ((entry = tarArchiveInputStream.getNextEntry()) != null) {
                    if ("flashplayer".equals(entry.getName())) {
                        uncompressedBinary = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                                ".uexe");
                        final FileOutputStream uncompressedBinaryOutputStream = new FileOutputStream(
                                uncompressedBinary);
                        while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                            uncompressedBinaryOutputStream.write(buffer, 0, n);
                        }
                        uncompressedBinaryOutputStream.close();
                    } else if ("flashplayerdebugger".equals(entry.getName())) {
                        uncompressedBinary = File.createTempFile("flex-sdk-linux-flashplayer-binary-" + version,
                                ".uexe");
                        final FileOutputStream uncompressedBinaryOutputStream = new FileOutputStream(
                                uncompressedBinary);
                        while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                            uncompressedBinaryOutputStream.write(buffer, 0, n);
                        }
                        uncompressedBinaryOutputStream.close();
                    }
                }
                tarFileInputStream.close();

                // If a binary exists, copy it to the target and create a pom for it.
                if (uncompressedBinary != null) {
                    playerArtifact.addBinaryArtifact("linux", flashPlayerBinary);
                }
            } catch (FileNotFoundException e) {
                throw new ConverterException("Error processing the linux player tar file", e);
            } catch (IOException e) {
                throw new ConverterException("Error processing the linux player tar file", e);
            }
        }

        // Write this artifact to file.
        writeArtifact(playerArtifact);
    }
}