Example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get this entry's name.

Usage

From source file:io.syndesis.project.converter.DefaultProjectGeneratorTest.java

private Path generate(GenerateProjectRequest request, ProjectGeneratorProperties generatorProperties)
        throws IOException {
    try (InputStream is = new DefaultProjectGenerator(new ConnectorCatalog(CATALOG_PROPERTIES),
            generatorProperties, registry).generate(request)) {
        Path ret = Files.createTempDirectory("integration-runtime");
        try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) {

            TarArchiveEntry tarEntry = tis.getNextTarEntry();
            // tarIn is a TarArchiveInputStream
            while (tarEntry != null) {// create a file with the same name as the tarEntry
                File destPath = new File(ret.toFile(), tarEntry.getName());
                if (tarEntry.isDirectory()) {
                    destPath.mkdirs();/*from w ww  . j a  v  a  2s  .c  o  m*/
                } else {
                    destPath.getParentFile().mkdirs();
                    destPath.createNewFile();
                    byte[] btoRead = new byte[8129];
                    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                    int len = tis.read(btoRead);
                    while (len != -1) {
                        bout.write(btoRead, 0, len);
                        len = tis.read(btoRead);
                    }
                    bout.close();
                }
                tarEntry = tis.getNextTarEntry();
            }
        }
        return ret;
    }
}

From source file:cpcc.vvrte.services.VirtualVehicleMigratorImpl.java

/**
 * @param inStream the input stream containing a virtual vehicle chunk.
 * @param entry the previously read archive entry.
 * @param virtualVehicleHolder the holder object for the virtual vehicle read.
 * @throws IOException thrown in case of errors.
 *///  ww w.jav a 2  s . co  m
private boolean storeVirtualVehicleEntry(InputStream inStream, TarArchiveEntry entry,
        VirtualVehicleHolder virtualVehicleHolder) throws IOException {
    boolean lastChunk = false;

    if (DATA_VV_PROPERTIES.equals(entry.getName())) {
        Properties props = new Properties();
        props.load(inStream);

        lastChunk |= Boolean.parseBoolean(props.getProperty("last.chunk", "false"));

        VirtualVehicle vv = vvRepository.findVirtualVehicleByUUID(props.getProperty("uuid"));
        if (vv == null) {
            vv = createVirtualVehicle(props);
        } else {
            updateVirtualVehicle(props, vv);
        }

        virtualVehicleHolder.setVirtualVehicle(vv);
        sessionManager.getSession().saveOrUpdate(vv);
    } else if (DATA_VV_CONTINUATION_JS.equals(entry.getName())) {
        byte[] continuation = IOUtils.toByteArray(inStream);
        virtualVehicleHolder.getVirtualVehicle().setContinuation(continuation);
        sessionManager.getSession().saveOrUpdate(virtualVehicleHolder.getVirtualVehicle());
    } else if (DATA_VV_SOURCE_JS.equals(entry.getName())) {
        byte[] source = IOUtils.toByteArray(inStream);
        virtualVehicleHolder.getVirtualVehicle().setCode(new String(source, "UTF-8"));
        sessionManager.getSession().saveOrUpdate(virtualVehicleHolder.getVirtualVehicle());
    } else {
        throw new IOException("Can not store unknown virtual vehicle entry " + entry.getName());
    }

    return lastChunk;
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

private File makeTarball(final Map<String, byte[]> entries) throws IOException {
    File tgz = temporaryFolder.newFile();
    try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(
            new GzipCompressorOutputStream(new FileOutputStream(tgz)))) {
        entries.forEach((name, content) -> {
            try {
                File entryFile = temporaryFolder.newFile();
                FileUtils.writeByteArrayToFile(entryFile, content);

                TarArchiveEntry entry = new TarArchiveEntry(entryFile, name);
                //                entry.setSize( content.length );
                //                entry.setMode( 0644 );
                //                entry.setGroupId( 1000 );
                //                entry.setUserId( 1000 );

                tarOut.putArchiveEntry(entry);

                System.out.printf("Entry: %s mode: '0%s'\n", entry.getName(),
                        Integer.toString(entry.getMode(), 8));

                tarOut.write(content);/*from   w w  w . ja va  2 s .  c o m*/
                tarOut.closeArchiveEntry();
            } catch (IOException e) {
                e.printStackTrace();
                fail("Failed to write tarball");
            }
        });

        tarOut.flush();
    }

    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(tgz)))) {
        TarArchiveEntry entry = null;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            byte[] entryData = new byte[(int) entry.getSize()];
            int read = tarIn.read(entryData, 0, entryData.length);
            assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize()));
            assertThat(entry.getName() + ": data doesn't match input",
                    Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true));
        }
    }

    return tgz;
}

From source file:com.platform.APIClient.java

public boolean tryExtractTar(File inputFile) {
    String extractFolderName = MainActivity.app.getFilesDir().getAbsolutePath() + bundlesFileName + "/"
            + extractedFolder;//w w  w.  ja v  a  2 s. c  o m
    boolean result = false;
    TarArchiveInputStream debInputStream = null;
    try {
        final InputStream is = new FileInputStream(inputFile);
        debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {

            final String outPutFileName = entry.getName().replace("./", "");
            final File outputFile = new File(extractFolderName, outPutFileName);
            if (!entry.isDirectory()) {
                FileUtils.writeByteArrayToFile(outputFile,
                        org.apache.commons.compress.utils.IOUtils.toByteArray(debInputStream));
            }
        }

        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (debInputStream != null)
                debInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;

}

From source file:com.streamsets.datacollector.restapi.StageLibraryResource.java

@POST
@Path("/stageLibraries/install")
@ApiOperation(value = "Install Stage libraries", response = Object.class, authorizations = @Authorization(value = "basic"))
@Produces(MediaType.APPLICATION_JSON)//  w  w w  .j  av a 2  s . c  o m
@RolesAllowed({ AuthzRole.ADMIN, AuthzRole.ADMIN_REMOTE })
public Response installLibraries(List<String> libraryIdList) throws IOException {
    String runtimeDir = runtimeInfo.getRuntimeDir();
    String version = buildInfo.getVersion();

    List<String> libraryUrlList = new ArrayList<>();
    List<RepositoryManifestJson> repoManifestList = stageLibrary.getRepositoryManifestList();
    repoManifestList.forEach(repositoryManifestJson -> {
        List<String> libraryFilePathList = repositoryManifestJson.getStageLibraries().stream()
                .filter(stageLibrariesJson -> stageLibrariesJson.getStageLibraryManifest() != null
                        && libraryIdList.contains(stageLibrariesJson.getStageLibraryManifest().getStageLibId()))
                .map(stageLibrariesJson -> stageLibrariesJson.getStageLibraryManifest().getStageLibFile())
                .collect(Collectors.toList());
        libraryUrlList.addAll(libraryFilePathList);
    });

    if (libraryUrlList.size() != libraryIdList.size()) {
        throw new RuntimeException(Utils
                .format("Unable to find to stage library {} in configured repository list", libraryIdList));
    }

    for (String libraryUrl : libraryUrlList) {
        try (Response response = ClientBuilder.newClient().target(libraryUrl).request().get()) {

            String runtimeDirParent = runtimeDir + "/..";
            String[] runtimeDirStrSplitArr = runtimeDir.split("/");
            String installDirName = runtimeDirStrSplitArr[runtimeDirStrSplitArr.length - 1];
            String tarDirRootName = STREAMSETS_ROOT_DIR_PREFIX + version;

            InputStream inputStream = response.readEntity(InputStream.class);

            TarArchiveInputStream myTarFile = new TarArchiveInputStream(
                    new GzipCompressorInputStream(inputStream));

            TarArchiveEntry entry = myTarFile.getNextTarEntry();

            String directory = null;

            while (entry != null) {
                if (entry.isDirectory()) {
                    entry = myTarFile.getNextTarEntry();
                    if (directory == null) {
                        // Initialize root folder
                        if (entry.getName().startsWith(STREAMSETS_LIBS_FOLDER_NAME)) {
                            directory = runtimeDir;
                        } else {
                            directory = runtimeDirParent;
                        }
                    }
                    continue;
                }

                File curFile = new File(directory, entry.getName().replace(tarDirRootName, installDirName));
                File parent = curFile.getParentFile();
                if (!parent.exists() && !parent.mkdirs()) {
                    // Failed to create directory
                    throw new RuntimeException(
                            Utils.format("Failed to create directory: {}", parent.getPath()));
                }
                OutputStream out = new FileOutputStream(curFile);
                IOUtils.copy(myTarFile, out);
                out.close();
                entry = myTarFile.getNextTarEntry();
            }
            myTarFile.close();

        }
    }

    return Response.ok().build();
}

From source file:hudson.gridmaven.MavenBuilder.java

public void getAndUntar(FileSystem fs, String src, String targetPath)
        throws FileNotFoundException, IOException {
    BufferedOutputStream dest = null;
    InputStream tarArchiveStream = new FSDataInputStream(fs.open(new Path(src)));
    TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(tarArchiveStream));
    TarArchiveEntry entry = null;
    try {//from www .j av a 2s . c o  m
        while ((entry = tis.getNextTarEntry()) != null) {
            int count;
            File outputFile = new File(targetPath, entry.getName());

            if (entry.isDirectory()) { // entry is a directory
                if (!outputFile.exists()) {
                    outputFile.mkdirs();
                }
            } else { // entry is a file
                byte[] data = new byte[BUFFER_MAX];
                FileOutputStream fos = new FileOutputStream(outputFile);
                dest = new BufferedOutputStream(fos, BUFFER_MAX);
                while ((count = tis.read(data, 0, BUFFER_MAX)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dest != null) {
            dest.flush();
            dest.close();
        }
        tis.close();
    }
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean downloadAPKFromNPK() {
    try {/*from w  ww .  j  a va 2  s  . c om*/
        String apkName = apkUpdatePath.path.replace("/", "");
        GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl));
        //FileInputStream npkFile = new FileInputStream(baseUrl);
        TarArchiveInputStream input = new TarArchiveInputStream(npkFile);
        TarArchiveEntry ae;
        while ((ae = input.getNextTarEntry()) != null) {
            if (!ae.isDirectory() && ae.getName().equalsIgnoreCase(apkName)) {
                String apkPath = tmpDir + apkUpdatePath.path;
                boolean status = downloadFile(apkUpdatePath, apkPath, input, ae);
                input.close();
                return status;
            }
        }
        input.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

From source file:com.codemarvels.ant.aptrepotask.AptRepoTask.java

public void execute() {
    if (repoDir == null) {
        log("repoDir attribute is empty !", LogLevel.ERR.getLevel());
        throw new RuntimeException("Bad attributes for apt-repo task");
    }//  w  w  w. j ava2 s.  co  m
    log("repo dir: " + repoDir);
    File repoFolder = new File(repoDir);
    if (!repoFolder.exists()) {
        repoFolder.mkdirs();
    }
    File[] files = repoFolder.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(FILE_DEB_EXT)) {
                return true;
            }
            return false;
        }
    });
    Packages packages = new Packages();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        PackageEntry packageEntry = new PackageEntry();
        packageEntry.setSize(file.length());
        packageEntry.setSha1(Utils.getDigest("SHA-1", file));
        packageEntry.setSha256(Utils.getDigest("SHA-256", file));
        packageEntry.setMd5sum(Utils.getDigest("MD5", file));
        String fileName = file.getName();
        packageEntry.setFilename(fileName);
        log("found deb: " + fileName);
        try {
            ArchiveInputStream control_tgz;
            ArArchiveEntry entry;
            TarArchiveEntry control_entry;
            ArchiveInputStream debStream = new ArchiveStreamFactory().createArchiveInputStream("ar",
                    new FileInputStream(file));
            while ((entry = (ArArchiveEntry) debStream.getNextEntry()) != null) {
                if (entry.getName().equals("control.tar.gz")) {
                    ControlHandler controlHandler = new ControlHandler();
                    GZIPInputStream gzipInputStream = new GZIPInputStream(debStream);
                    control_tgz = new ArchiveStreamFactory().createArchiveInputStream("tar", gzipInputStream);
                    while ((control_entry = (TarArchiveEntry) control_tgz.getNextEntry()) != null) {
                        log("control entry: " + control_entry.getName(), LogLevel.DEBUG.getLevel());
                        if (control_entry.getName().trim().equals(CONTROL_FILE_NAME)) {
                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(control_tgz, outputStream);
                            String content_string = outputStream.toString("UTF-8");
                            outputStream.close();
                            controlHandler.setControlContent(content_string);
                            log("control cont: " + outputStream.toString("utf-8"), LogLevel.DEBUG.getLevel());
                            break;
                        }
                    }
                    control_tgz.close();
                    if (controlHandler.hasControlContent()) {
                        controlHandler.handle(packageEntry);
                    } else {
                        throw new RuntimeException("no control content found for: " + file.getName());
                    }
                    break;
                }
            }
            debStream.close();
            packages.addPackageEntry(packageEntry);
        } catch (Exception e) {
            String msg = FAILED_TO_CREATE_APT_REPO + " " + file.getName();
            log(msg, e, LogLevel.ERR.getLevel());
            throw new RuntimeException(msg, e);
        }
    }
    try {
        File packagesFile = new File(repoDir, PACKAGES_GZ);
        packagesWriter = new BufferedWriter(
                new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(packagesFile))));
        packagesWriter.write(packages.toString());
        DefaultHashes hashes = Utils.getDefaultDigests(packagesFile);
        ReleaseInfo pinfo = new ReleaseInfo(PACKAGES_GZ, packagesFile.length(), hashes);
        Release release = new Release();
        release.addInfo(pinfo);
        final File releaseFile = new File(repoDir, RELEASE);
        FileUtils.fileWrite(releaseFile, release.toString());
    } catch (IOException e) {
        throw new RuntimeException("writing files failed", e);
    } finally {
        if (packagesWriter != null) {
            try {
                packagesWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("writing files failed", e);
            }
        }
    }
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private String getMetaFromNPK() {
    try {//from  ww  w.j av a 2  s  . co  m
        GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl));
        //FileInputStream npkFile = new FileInputStream(baseUrl);
        TarArchiveInputStream input = new TarArchiveInputStream(npkFile);
        TarArchiveEntry ae;
        while ((ae = input.getNextTarEntry()) != null) {
            if (ae.isDirectory())
                Log.e("[neoUpdate]", "Dir: " + ae.getName());
            else
                Log.e("[neoUpdate]", "File: " + ae.getName());
            if (ae.getName().equalsIgnoreCase("neoupdate.json")) {
                byte buff[] = new byte[(int) ae.getSize()];
                input.read(buff);
                input.close();
                return new String(buff);
            }
        }
        input.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private String processFromNPK() {
    try {//  ww  w.j a v a 2s.c o m
        GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl));
        //FileInputStream npkFile = new FileInputStream(baseUrl);
        TarArchiveInputStream input = new TarArchiveInputStream(npkFile);
        TarArchiveEntry ae;
        while ((ae = input.getNextTarEntry()) != null && filesToDownload.size() > 0 && !stopped) {
            if (ae.isDirectory()) {
                Log.e("[neoUpdate]", "Dir: " + ae.getName());
            } else {
                Log.e("[neoUpdate]", "File: " + ae.getName());
                String filename = ae.getName();
                NewAsset asset = findAndGetAsset(filename);
                if (asset != null) {
                    downloadFile(asset, null, input, ae);
                    publishProgress((float) (totalFilesToDownload - filesToDownload.size())
                            / (float) totalFilesToDownload);
                }
            }
        }
        input.close();
    } catch (Exception e) {
        e.printStackTrace();
        return "Unknown Error: Update Failed!";
    }
    return "Success";
}