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

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

Introduction

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

Prototype

public void setMode(int mode) 

Source Link

Document

Set the mode for this entry

Usage

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GitProfileReader.java

@Override
public InputStream readArchiveProfile(String artifactName, String version, String profileName)
        throws IOException {
    Path profilePath = Paths.get(profilePath(artifactName, version, profileName));

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        int permissions = FileModeUtils.getFileMode(Files.getPosixFilePermissions(path));
        permissions = FileModeUtils.setFileBit(permissions);
        tarEntry.setMode(permissions);
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();//from   w w  w  .java2  s.c  o m
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.mobilesorcery.sdk.builder.linux.deb.DebBuilder.java

/**
 * Adds the files in the file list in a tar+gz
 *
 * @param o Output file//  w  w w  . j  a  va2s  . c  o  m
 *
 * @throws IOException If error occurs during writing
 * @throws FileNotFoundException If the output file could not be opened.
 */
private void doAddFilesToTarGZip(File o) throws IOException, FileNotFoundException

{
    FileOutputStream os = new FileOutputStream(o);
    GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(os);
    TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos);

    // Add files
    for (SimpleEntry<File, SimpleEntry<String, Integer>> fileEntry : m_fileList) {
        File file = fileEntry.getKey();
        String name = fileEntry.getValue().getKey();
        int mode = fileEntry.getValue().getValue();
        TarArchiveEntry e = new TarArchiveEntry(file, name);

        // Add to tar, user/group id 0 is always root
        e.setMode(mode);
        e.setUserId(0);
        e.setUserName("root");
        e.setGroupId(0);
        e.setGroupName("root");
        tos.putArchiveEntry(e);

        // Write bytes
        if (file.isFile())
            BuilderUtil.getInstance().copyFileToOutputStream(tos, file);
        tos.closeArchiveEntry();
    }

    // Done
    tos.close();
    gzos.close();
    os.close();
}

From source file:com.moss.simpledeb.core.action.CopyAction.java

@Override
public void run(final DebState state) throws Exception {

    File target = new File(targetDir);
    LinkedList<File> pathsNeeded = new LinkedList<File>();

    File f = target;/*from w ww. ja  v a 2 s  . c om*/
    while (f != null) {
        pathsNeeded.addFirst(f);
        f = f.getParentFile();
    }

    for (int i = 0; i < assumedTargetPathLevel; i++) {
        pathsNeeded.removeFirst();
    }

    for (File e : pathsNeeded) {
        String p = "./" + e.getPath();

        if (!p.endsWith("/")) {
            p = p + "/";
        }

        TarArchiveEntry tarEntry = new TarArchiveEntry(p);
        tarEntry.setGroupId(0);
        tarEntry.setGroupName("root");
        tarEntry.setIds(0, 0);
        tarEntry.setModTime(System.currentTimeMillis());
        tarEntry.setSize(0);
        tarEntry.setUserId(0);
        tarEntry.setUserName("root");
        tarEntry.setMode(Integer.parseInt("755", 8));

        ArchivePath path = new DirArchivePath(tarEntry);
        state.addPath(component, path);
    }

    files.visit(new FileVisitor() {
        public void file(File file) {
            try {
                copyFile(file, state);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {/*from   w  w w.ja v  a 2s . com*/
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:com.moss.simpledeb.core.action.LaunchScriptAction.java

@Override
public void run(DebState state) throws Exception {

    {//ww w  .  j  a  v  a  2s  . com
        File target = new File(targetFile).getParentFile();
        LinkedList<File> pathsNeeded = new LinkedList<File>();

        File f = target;
        while (f != null) {
            pathsNeeded.addFirst(f);
            f = f.getParentFile();
        }

        for (int i = 0; i < pathLevel; i++) {
            pathsNeeded.removeFirst();
        }

        for (File e : pathsNeeded) {
            String p = "./" + e.getPath();

            if (!p.endsWith("/")) {
                p = p + "/";
            }

            TarArchiveEntry tarEntry = new TarArchiveEntry(p);
            tarEntry.setGroupId(0);
            tarEntry.setGroupName("root");
            tarEntry.setIds(0, 0);
            tarEntry.setModTime(System.currentTimeMillis());
            tarEntry.setSize(0);
            tarEntry.setUserId(0);
            tarEntry.setUserName("root");
            tarEntry.setMode(Integer.parseInt("755", 8));

            ArchivePath path = new DirArchivePath(tarEntry);
            state.addPath(DebComponent.CONTENT, path);
        }
    }

    String cp;
    {
        StringBuffer sb = new StringBuffer();
        for (String path : state.classpath) {
            if (sb.length() == 0) {
                sb.append(path);
            } else {
                sb.append(":");
                sb.append(path);
            }
        }
        cp = sb.toString();
    }

    StringBuilder sb = new StringBuilder();
    sb.append("#!/bin/bash\n");
    sb.append("CP=\"");
    sb.append(cp);
    sb.append("\"\n");
    sb.append("/usr/bin/java -cp $CP ");
    sb.append(className);
    sb.append(" $@\n");

    byte[] data = sb.toString().getBytes();

    String entryName = "./" + targetFile;

    TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
    tarEntry.setGroupId(0);
    tarEntry.setGroupName("root");
    tarEntry.setIds(0, 0);
    tarEntry.setModTime(System.currentTimeMillis());
    tarEntry.setSize(data.length);
    tarEntry.setUserId(0);
    tarEntry.setUserName("root");
    tarEntry.setMode(Integer.parseInt("755", 8));

    ArchivePath path = new BytesArchivePath(tarEntry, data);
    state.addPath(DebComponent.CONTENT, path);
}

From source file:com.moss.simpledeb.core.action.CopyAction.java

private void copyFile(File file, DebState state) throws Exception {

    String entryName = "./" + targetDir + "/" + file.getName();

    if (!file.isDirectory()) {

        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tarEntry.setGroupId(0);/* w  w w . jav  a 2  s.  co m*/
        tarEntry.setGroupName("root");
        tarEntry.setIds(0, 0);
        tarEntry.setModTime(System.currentTimeMillis());
        tarEntry.setSize(file.length());
        tarEntry.setUserId(0);
        tarEntry.setUserName("root");
        tarEntry.setMode(Integer.parseInt(fileMode, 8));

        ArchivePath path = new FileArchivePath(tarEntry, file);
        state.addPath(component, path);

        if (appendToClasspath) {
            state.classpath.add("/" + targetDir + "/" + file.getName());
        }
    } else {
        entryName = entryName + "/";

        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tarEntry.setGroupId(0);
        tarEntry.setGroupName("root");
        tarEntry.setIds(0, 0);
        tarEntry.setModTime(System.currentTimeMillis());
        tarEntry.setSize(0);
        tarEntry.setUserId(0);
        tarEntry.setUserName("root");
        tarEntry.setMode(Integer.parseInt(dirMode, 8));

        ArchivePath path = new DirArchivePath(tarEntry);
        state.addPath(component, path);
    }
}

From source file:com.st.maven.debian.DebianPackageMojo.java

private void fillControlTar(Config config, ArFileOutputStream output) throws MojoExecutionException {
    TarArchiveOutputStream tar = null;/*from w w  w  .j  av  a2 s .  c o m*/
    try {
        tar = new TarArchiveOutputStream(new GZIPOutputStream(new ArWrapper(output)));
        tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        TarArchiveEntry rootDir = new TarArchiveEntry("./");
        tar.putArchiveEntry(rootDir);
        tar.closeArchiveEntry();

        byte[] controlData = processTemplate(freemarkerConfig, config, "control.ftl");
        TarArchiveEntry controlEntry = new TarArchiveEntry("./control");
        controlEntry.setSize(controlData.length);
        tar.putArchiveEntry(controlEntry);
        tar.write(controlData);
        tar.closeArchiveEntry();

        byte[] preinstBaseData = processTemplate("preinst", freemarkerConfig, config,
                combine("preinst.ftl", BASE_DIR + File.separator + "preinst", false));
        long size = preinstBaseData.length;
        TarArchiveEntry preinstEntry = new TarArchiveEntry("./preinst");
        preinstEntry.setSize(size);
        preinstEntry.setMode(0755);
        tar.putArchiveEntry(preinstEntry);
        tar.write(preinstBaseData);
        tar.closeArchiveEntry();

        byte[] postinstBaseData = processTemplate("postinst", freemarkerConfig, config,
                combine("postinst.ftl", BASE_DIR + File.separator + "postinst", true));
        size = postinstBaseData.length;
        TarArchiveEntry postinstEntry = new TarArchiveEntry("./postinst");
        postinstEntry.setSize(size);
        postinstEntry.setMode(0755);
        tar.putArchiveEntry(postinstEntry);
        tar.write(postinstBaseData);
        tar.closeArchiveEntry();

        byte[] prermBaseData = processTemplate("prerm", freemarkerConfig, config,
                combine("prerm.ftl", BASE_DIR + File.separator + "prerm", false));
        size = prermBaseData.length;
        TarArchiveEntry prermEntry = new TarArchiveEntry("./prerm");
        prermEntry.setSize(size);
        prermEntry.setMode(0755);
        tar.putArchiveEntry(prermEntry);
        tar.write(prermBaseData);
        tar.closeArchiveEntry();

        byte[] postrmBaseData = processTemplate("postrm", freemarkerConfig, config,
                combine("postrm.ftl", BASE_DIR + File.separator + "postrm", false));
        size = postrmBaseData.length;
        TarArchiveEntry postrmEntry = new TarArchiveEntry("./postrm");
        postrmEntry.setSize(size);
        postrmEntry.setMode(0755);
        tar.putArchiveEntry(postrmEntry);
        tar.write(postrmBaseData);
        tar.closeArchiveEntry();

    } catch (Exception e) {
        throw new MojoExecutionException("unable to create control tar", e);
    } finally {
        if (tar != null) {
            try {
                tar.close();
            } catch (IOException e) {
                getLog().error("unable to finish tar", e);
            }
        }
    }
}

From source file:com.st.maven.debian.DebianPackageMojo.java

private void fillDataTar(Config config, ArFileOutputStream output) throws MojoExecutionException {
    TarArchiveOutputStream tar = null;/* w ww .ja  v  a  2s .  c o  m*/
    try {
        tar = new TarArchiveOutputStream(new GZIPOutputStream(new ArWrapper(output)));
        tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        if (Boolean.TRUE.equals(javaServiceWrapper)) {
            byte[] daemonData = processTemplate(freemarkerConfig, config, "daemon.ftl");
            TarArchiveEntry initScript = new TarArchiveEntry("etc/init.d/" + project.getArtifactId());
            initScript.setSize(daemonData.length);
            initScript.setMode(040755);
            tar.putArchiveEntry(initScript);
            tar.write(daemonData);
            tar.closeArchiveEntry();
        }
        String packageBaseDir = "home/" + unixUserId + "/" + project.getArtifactId() + "/";
        if (fileSets != null && !fileSets.isEmpty()) {
            writeDirectory(tar, packageBaseDir);

            Collections.sort(fileSets, MappingPathComparator.INSTANCE);
            for (Fileset curPath : fileSets) {
                curPath.setTarget(packageBaseDir + curPath.getTarget());
                addRecursively(config, tar, curPath);
            }
        }

    } catch (Exception e) {
        throw new MojoExecutionException("unable to create data tar", e);
    } finally {
        IOUtils.closeQuietly(tar);
    }
}

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

public Tar() {
    setFactory(new TarStreamFactory() {
        public ArchiveOutputStream getArchiveStream(OutputStream stream, String encoding) throws IOException {
            TarArchiveOutputStream o = (TarArchiveOutputStream) super.getArchiveStream(stream, encoding);
            if (format.equals(Format.OLDGNU)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            } else if (format.equals(Format.GNU)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            } else if (format.equals(Format.STAR)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            } else if (format.equals(Format.PAX)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
                o.setAddPaxHeadersForNonAsciiNames(true);
            }// w w  w .j av a  2  s  .  c  o  m
            return o;
        }
    });
    setEntryBuilder(new ArchiveBase.EntryBuilder() {
        public ArchiveEntry buildEntry(ArchiveBase.ResourceWithFlags r) {
            boolean isDir = r.getResource().isDirectory();
            String name = r.getName();
            if (isDir && !name.endsWith("/")) {
                name += "/";
            } else if (!isDir && name.endsWith("/")) {
                name = name.substring(0, name.length() - 1);
            }
            TarArchiveEntry ent = new TarArchiveEntry(name, getPreserveLeadingSlashes());
            ent.setModTime(round(r.getResource().getLastModified(), 1000));
            ent.setSize(isDir ? 0 : r.getResource().getSize());

            if (!isDir && r.getCollectionFlags().hasModeBeenSet()) {
                ent.setMode(r.getCollectionFlags().getMode());
            } else if (isDir && r.getCollectionFlags().hasDirModeBeenSet()) {
                ent.setMode(r.getCollectionFlags().getDirMode());
            } else if (r.getResourceFlags().hasModeBeenSet()) {
                ent.setMode(r.getResourceFlags().getMode());
            } else {
                ent.setMode(isDir ? ArchiveFileSet.DEFAULT_DIR_MODE : ArchiveFileSet.DEFAULT_FILE_MODE);
            }

            if (r.getResourceFlags().hasUserIdBeenSet()) {
                ent.setUserId(r.getResourceFlags().getUserId());
            } else if (r.getCollectionFlags().hasUserIdBeenSet()) {
                ent.setUserId(r.getCollectionFlags().getUserId());
            }

            if (r.getResourceFlags().hasGroupIdBeenSet()) {
                ent.setGroupId(r.getResourceFlags().getGroupId());
            } else if (r.getCollectionFlags().hasGroupIdBeenSet()) {
                ent.setGroupId(r.getCollectionFlags().getGroupId());
            }

            if (r.getResourceFlags().hasUserNameBeenSet()) {
                ent.setUserName(r.getResourceFlags().getUserName());
            } else if (r.getCollectionFlags().hasUserNameBeenSet()) {
                ent.setUserName(r.getCollectionFlags().getUserName());
            }

            if (r.getResourceFlags().hasGroupNameBeenSet()) {
                ent.setGroupName(r.getResourceFlags().getGroupName());
            } else if (r.getCollectionFlags().hasGroupNameBeenSet()) {
                ent.setGroupName(r.getCollectionFlags().getGroupName());
            }

            return ent;
        }
    });
    setFileSetBuilder(new ArchiveBase.FileSetBuilder() {
        public ArchiveFileSet buildFileSet(Resource dest) {
            ArchiveFileSet afs = new TarFileSet();
            afs.setSrcResource(dest);
            return afs;
        }
    });
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToTarGz(TarArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tOut.putArchiveEntry(tarEntry);/* w w  w  .j av  a  2  s. co m*/
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToTarGz(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
        tarEntry.setLinkName(Files.readSymbolicLink(f).toString());
        tOut.putArchiveEntry(tarEntry);
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tarEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin/"))) {
            if (entryName.endsWith(".bat")) {
                tarEntry.setMode(0644);
            } else {
                tarEntry.setMode(0755);
            }
        }
        tOut.putArchiveEntry(tarEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}