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

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

Introduction

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

Prototype

public void setGroupName(String groupName) 

Source Link

Document

Set this entry's group name.

Usage

From source file:org.eclipse.scada.utils.pkg.deb.DebianPackageWriter.java

private static void applyInfo(final TarArchiveEntry entry, final EntryInformation entryInformation,
        TimestampProvider timestampProvider) {
    if (entryInformation == null) {
        return;//from   w ww  .  jav  a2s.  c o m
    }

    if (entryInformation.getUser() != null) {
        entry.setUserName(entryInformation.getUser());
    }
    if (entryInformation.getGroup() != null) {
        entry.setGroupName(entryInformation.getGroup());
    }
    entry.setMode(entryInformation.getMode());
    entry.setModTime(timestampProvider.getModTime());
}

From source file:org.eclipse.scada.utils.pkg.deb.DebianPackageWriter.java

private void addControlContent(final TarArchiveOutputStream out, final String name,
        final ContentProvider content, final int mode) throws IOException {
    if (content == null || !content.hasContent()) {
        return;/* ww w . j  a va  2  s .c om*/
    }

    final TarArchiveEntry entry = new TarArchiveEntry(name);
    if (mode >= 0) {
        entry.setMode(mode);
    }

    entry.setUserName("root");
    entry.setGroupName("root");
    entry.setSize(content.getSize());
    entry.setModTime(this.getTimestampProvider().getModTime());
    out.putArchiveEntry(entry);
    try (InputStream stream = content.createInputStream()) {
        ByteStreams.copy(stream, out);
    }
    out.closeArchiveEntry();
}

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiver.java

private TarArchiveEntry createTarEntry(File tarRootDir, File source) throws IOException {
    String pathInTar = slashify(tarRootDir.toPath().relativize(source.toPath()));
    log.debug("Adding entry " + pathInTar);
    TarArchiveEntry tarEntry;
    if (isSymbolicLink(source) && resolvesBelow(source, tarRootDir)) {
        // only create symlink entry if link target is inside archive
        tarEntry = new TarArchiveEntry(pathInTar, TarArchiveEntry.LF_SYMLINK);
        tarEntry.setLinkName(slashify(getRelativeSymLinkTarget(source, source.getParentFile())));
    } else {// w w w  .  j ava 2s.  c o m
        tarEntry = new TarArchiveEntry(source, pathInTar);
    }
    PosixFileAttributes attrs = getAttributes(source);
    if (attrs != null) {
        tarEntry.setUserName(attrs.owner().getName());
        tarEntry.setGroupName(attrs.group().getName());
        tarEntry.setMode(FilePermissionHelper.toOctalFileMode(attrs.permissions()));
    }
    tarEntry.setModTime(source.lastModified());
    return tarEntry;
}

From source file:org.savantbuild.io.tar.TarBuilder.java

/**
 * Builds the TAR file using the fileSets and Directories provided.
 *
 * @return The number of entries added to the TAR file including the directories.
 * @throws IOException If the build fails.
 *//*from w  w  w  . j ava2  s  . c  om*/
public int build() throws IOException {
    if (Files.exists(file)) {
        Files.delete(file);
    }

    if (!Files.isDirectory(file.getParent())) {
        Files.createDirectories(file.getParent());
    }

    // Sort the file infos and add the directories
    Set<FileInfo> fileInfos = new TreeSet<>();
    for (FileSet fileSet : fileSets) {
        Set<Directory> dirs = fileSet.toDirectories();
        dirs.removeAll(directories);
        for (Directory dir : dirs) {
            directories.add(dir);
        }

        fileInfos.addAll(fileSet.toFileInfos());
    }

    int count = 0;
    OutputStream os = Files.newOutputStream(file);
    try (TarArchiveOutputStream tos = new TarArchiveOutputStream(compress ? new GZIPOutputStream(os) : os)) {
        tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

        for (Directory directory : directories) {
            String name = directory.name;
            TarArchiveEntry entry = new TarArchiveEntry(name.endsWith("/") ? name : name + "/");
            if (directory.lastModifiedTime != null) {
                entry.setModTime(directory.lastModifiedTime.toMillis());
            }
            if (directory.mode != null) {
                entry.setMode(FileTools.toMode(directory.mode));
            }
            if (storeGroupName && directory.groupName != null) {
                entry.setGroupName(directory.groupName);
            }
            if (storeUserName && directory.userName != null) {
                entry.setUserName(directory.userName);
            }
            tos.putArchiveEntry(entry);
            tos.closeArchiveEntry();
            count++;
        }

        for (FileInfo fileInfo : fileInfos) {
            TarArchiveEntry entry = new TarArchiveEntry(fileInfo.relative.toString());
            entry.setModTime(fileInfo.lastModifiedTime.toMillis());
            if (storeGroupName) {
                entry.setGroupName(fileInfo.groupName);
            }
            if (storeUserName) {
                entry.setUserName(fileInfo.userName);
            }
            entry.setSize(fileInfo.size);
            entry.setMode(fileInfo.toMode());
            tos.putArchiveEntry(entry);
            Files.copy(fileInfo.origin, tos);
            tos.closeArchiveEntry();
            count++;
        }
    }

    return count;
}

From source file:org.vafer.jdeb.DataBuilder.java

/**
 * Build the data archive of the deb from the provided DataProducers
 *
 * @param producers/*from www  . ja v a  2s.  c o m*/
 * @param output
 * @param checksums
 * @param compression the compression method used for the data file
 * @return
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.io.IOException
 * @throws org.apache.commons.compress.compressors.CompressorException
 */
BigInteger buildData(Collection<DataProducer> producers, File output, final StringBuilder checksums,
        Compression compression) throws NoSuchAlgorithmException, IOException, CompressorException {

    final File dir = output.getParentFile();
    if (dir != null && (!dir.exists() || !dir.isDirectory())) {
        throw new IOException("Cannot write data file at '" + output.getAbsolutePath() + "'");
    }

    final TarArchiveOutputStream tarOutputStream = new TarArchiveOutputStream(
            compression.toCompressedOutputStream(new FileOutputStream(output)));
    tarOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    final MessageDigest digest = MessageDigest.getInstance("MD5");

    final Total dataSize = new Total();

    final List<String> addedDirectories = new ArrayList<String>();
    final DataConsumer receiver = new DataConsumer() {
        public void onEachDir(String dirname, String linkname, String user, int uid, String group, int gid,
                int mode, long size) throws IOException {
            dirname = fixPath(dirname);

            createParentDirectories(dirname, user, uid, group, gid);

            // The directory passed in explicitly by the caller also gets the passed-in mode.  (Unlike
            // the parent directories for now.  See related comments at "int mode =" in
            // createParentDirectories, including about a possible bug.)
            createDirectory(dirname, user, uid, group, gid, mode, 0);

            console.info("dir: " + dirname);
        }

        public void onEachFile(InputStream inputStream, String filename, String linkname, String user, int uid,
                String group, int gid, int mode, long size) throws IOException {
            filename = fixPath(filename);

            createParentDirectories(filename, user, uid, group, gid);

            final TarArchiveEntry entry = new TarArchiveEntry(filename, true);

            entry.setUserName(user);
            entry.setUserId(uid);
            entry.setGroupName(group);
            entry.setGroupId(gid);
            entry.setMode(mode);
            entry.setSize(size);

            tarOutputStream.putArchiveEntry(entry);

            dataSize.add(size);
            digest.reset();

            Utils.copy(inputStream, new DigestOutputStream(tarOutputStream, digest));

            final String md5 = Utils.toHex(digest.digest());

            tarOutputStream.closeArchiveEntry();

            console.info("file:" + entry.getName() + " size:" + entry.getSize() + " mode:" + entry.getMode()
                    + " linkname:" + entry.getLinkName() + " username:" + entry.getUserName() + " userid:"
                    + entry.getUserId() + " groupname:" + entry.getGroupName() + " groupid:"
                    + entry.getGroupId() + " modtime:" + entry.getModTime() + " md5: " + md5);

            // append to file md5 list
            checksums.append(md5).append(" ").append(entry.getName()).append('\n');
        }

        public void onEachLink(String path, String linkName, boolean symlink, String user, int uid,
                String group, int gid, int mode) throws IOException {
            path = fixPath(path);

            createParentDirectories(path, user, uid, group, gid);

            final TarArchiveEntry entry = new TarArchiveEntry(path,
                    symlink ? TarArchiveEntry.LF_SYMLINK : TarArchiveEntry.LF_LINK);
            entry.setLinkName(linkName);

            entry.setUserName(user);
            entry.setUserId(uid);
            entry.setGroupName(group);
            entry.setGroupId(gid);
            entry.setMode(mode);

            tarOutputStream.putArchiveEntry(entry);
            tarOutputStream.closeArchiveEntry();

            console.info("link:" + entry.getName() + " mode:" + entry.getMode() + " linkname:"
                    + entry.getLinkName() + " username:" + entry.getUserName() + " userid:" + entry.getUserId()
                    + " groupname:" + entry.getGroupName() + " groupid:" + entry.getGroupId());
        }

        private void createDirectory(String directory, String user, int uid, String group, int gid, int mode,
                long size) throws IOException {
            // All dirs should end with "/" when created, or the test DebAndTaskTestCase.testTarFileSet() thinks its a file
            // and so thinks it has the wrong permission.
            // This consistency also helps when checking if a directory already exists in addedDirectories.

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

            if (!addedDirectories.contains(directory)) {
                TarArchiveEntry entry = new TarArchiveEntry(directory, true);
                entry.setUserName(user);
                entry.setUserId(uid);
                entry.setGroupName(group);
                entry.setGroupId(gid);
                entry.setMode(mode);
                entry.setSize(size);

                tarOutputStream.putArchiveEntry(entry);
                tarOutputStream.closeArchiveEntry();
                addedDirectories.add(directory); // so addedDirectories consistently have "/" for finding duplicates.
            }
        }

        private void createParentDirectories(String filename, String user, int uid, String group, int gid)
                throws IOException {
            String dirname = fixPath(new File(filename).getParent());

            // Debian packages must have parent directories created
            // before sub-directories or files can be installed.
            // For example, if an entry of ./usr/lib/foo/bar existed
            // in a .deb package, but the ./usr/lib/foo directory didn't
            // exist, the package installation would fail.  The .deb must
            // then have an entry for ./usr/lib/foo and then ./usr/lib/foo/bar

            if (dirname == null) {
                return;
            }

            // The loop below will create entries for all parent directories
            // to ensure that .deb packages will install correctly.
            String[] pathParts = dirname.split("/");
            String parentDir = "./";
            for (int i = 1; i < pathParts.length; i++) {
                parentDir += pathParts[i] + "/";
                // Make it so the dirs can be traversed by users.
                // We could instead try something more granular, like setting the directory
                // permission to 'rx' for each of the 3 user/group/other read permissions
                // found on the file being added (ie, only if "other" has read
                // permission on the main node, then add o+rx permission on all the containing
                // directories, same w/ user & group), and then also we'd have to
                // check the parentDirs collection of those already added to
                // see if those permissions need to be similarly updated.  (Note, it hasn't
                // been demonstrated, but there might be a bug if a user specifically
                // requests a directory with certain permissions,
                // that has already been auto-created because it was a parent, and if so, go set
                // the user-requested mode on that directory instead of this automatic one.)
                // But for now, keeping it simple by making every dir a+rx.   Examples are:
                // drw-r----- fs/fs   # what you get with setMode(mode)
                // drwxr-xr-x fs/fs   # Usable. Too loose?
                int mode = TarArchiveEntry.DEFAULT_DIR_MODE;

                createDirectory(parentDir, user, uid, group, gid, mode, 0);
            }
        }
    };

    try {
        for (DataProducer data : producers) {
            data.produce(receiver);
        }
    } finally {
        tarOutputStream.close();
    }

    console.info("Total size: " + dataSize);

    return dataSize.count;
}

From source file:org.vafer.jdeb.mapping.LsMapper.java

private TarArchiveEntry readDir(final BufferedReader reader, final String base) throws IOException, ParseError {
    final String current = reader.readLine();
    final Matcher currentMatcher = dirPattern.matcher(current);
    if (!currentMatcher.matches()) {
        throw new ParseError("expected dirline but got \"" + current + "\"");
    }//from ww w.ja v a  2 s . c  o  m

    final String parent = reader.readLine();
    final Matcher parentMatcher = dirPattern.matcher(parent);
    if (!parentMatcher.matches()) {
        throw new ParseError("expected dirline but got \"" + parent + "\"");
    }

    final TarArchiveEntry entry = new TarArchiveEntry(base, true);

    entry.setMode(convertModeFromString(currentMatcher.group(1)));
    entry.setUserName(currentMatcher.group(3));
    entry.setGroupName(currentMatcher.group(4));

    return entry;
}

From source file:org.vafer.jdeb.mapping.LsMapper.java

private TarArchiveEntry readFile(final BufferedReader reader, final String base)
        throws IOException, ParseError {

    while (true) {
        final String line = reader.readLine();

        if (line == null) {
            return null;
        }/*from   ww w .  ja  v a 2s.c  om*/

        final Matcher currentMatcher = filePattern.matcher(line);
        if (!currentMatcher.matches()) {
            final Matcher newlineMatcher = newlinePattern.matcher(line);
            if (newlineMatcher.matches()) {
                return null;
            }
            throw new ParseError("expected file line but got \"" + line + "\"");
        }

        final String type = currentMatcher.group(1);
        if (type.startsWith("-")) {
            final TarArchiveEntry entry = new TarArchiveEntry(base + "/" + currentMatcher.group(8), true);

            entry.setMode(convertModeFromString(currentMatcher.group(2)));
            entry.setUserName(currentMatcher.group(4));
            entry.setGroupName(currentMatcher.group(5));

            return entry;
        }
    }

}

From source file:org.vafer.jdeb.mapping.LsMapper.java

public TarArchiveEntry map(final TarArchiveEntry pEntry) {

    final TarArchiveEntry entry = mapping.get(pEntry.getName());

    if (entry != null) {

        final TarArchiveEntry newEntry = new TarArchiveEntry(entry.getName(), true);
        newEntry.setUserId(entry.getUserId());
        newEntry.setGroupId(entry.getGroupId());
        newEntry.setUserName(entry.getUserName());
        newEntry.setGroupName(entry.getGroupName());
        newEntry.setMode(entry.getMode());
        newEntry.setSize(entry.getSize());

        return newEntry;
    }//from   w w w.java  2 s .c o m

    return pEntry;
}

From source file:org.vafer.jdeb.mapping.PermMapper.java

public TarArchiveEntry map(final TarArchiveEntry entry) {
    final String name = entry.getName();

    final TarArchiveEntry newEntry = new TarArchiveEntry(prefix + '/' + Utils.stripPath(strip, name), true);

    // Set ownership
    if (uid > -1) {
        newEntry.setUserId(uid);/*from   w ww .j  av a2  s.  c  o  m*/
    } else {
        newEntry.setUserId(entry.getUserId());
    }
    if (gid > -1) {
        newEntry.setGroupId(gid);
    } else {
        newEntry.setGroupId(entry.getGroupId());
    }
    if (user != null) {
        newEntry.setUserName(user);
    } else {
        newEntry.setUserName(entry.getUserName());
    }
    if (group != null) {
        newEntry.setGroupName(group);
    } else {
        newEntry.setGroupName(entry.getGroupName());
    }

    // Set permissions
    if (newEntry.isDirectory()) {
        if (dirMode > -1) {
            newEntry.setMode(dirMode);
        } else {
            newEntry.setMode(entry.getMode());
        }
    } else {
        if (fileMode > -1) {
            newEntry.setMode(fileMode);
        } else {
            newEntry.setMode(entry.getMode());

        }
    }

    newEntry.setSize(entry.getSize());

    return newEntry;
}

From source file:org.vafer.jdeb.maven.DebMojo.java

/**
 * Main entry point/*from  ww w.  j a  v a 2 s .c o  m*/
 *
 * @throws MojoExecutionException on error
 */
@Override
public void execute() throws MojoExecutionException {

    final MavenProject project = getProject();

    if (skip) {
        getLog().info("skipping as configured (skip)");
        return;
    }

    if (skipPOMs && isPOM()) {
        getLog().info("skipping because artifact is a pom (skipPOMs)");
        return;
    }

    if (skipSubmodules && isSubmodule()) {
        getLog().info("skipping submodule (skipSubmodules)");
        return;
    }

    setData(dataSet);

    console = new MojoConsole(getLog(), verbose);

    initializeSignProperties();

    final VariableResolver resolver = initializeVariableResolver(new HashMap<String, String>());

    final File debFile = new File(Utils.replaceVariables(resolver, deb, openReplaceToken, closeReplaceToken));
    final File controlDirFile = new File(
            Utils.replaceVariables(resolver, controlDir, openReplaceToken, closeReplaceToken));
    final File installDirFile = new File(
            Utils.replaceVariables(resolver, installDir, openReplaceToken, closeReplaceToken));
    final File changesInFile = new File(
            Utils.replaceVariables(resolver, changesIn, openReplaceToken, closeReplaceToken));
    final File changesOutFile = new File(
            Utils.replaceVariables(resolver, changesOut, openReplaceToken, closeReplaceToken));
    final File changesSaveFile = new File(
            Utils.replaceVariables(resolver, changesSave, openReplaceToken, closeReplaceToken));
    final File keyringFile = keyring == null ? null
            : new File(Utils.replaceVariables(resolver, keyring, openReplaceToken, closeReplaceToken));

    // if there are no producers defined we try to use the artifacts
    if (dataProducers.isEmpty()) {

        if (hasMainArtifact()) {
            Set<Artifact> artifacts = new HashSet<Artifact>();

            artifacts.add(project.getArtifact());

            @SuppressWarnings("unchecked")
            final Set<Artifact> projectArtifacts = project.getArtifacts();

            for (Artifact artifact : projectArtifacts) {
                artifacts.add(artifact);
            }

            @SuppressWarnings("unchecked")
            final List<Artifact> attachedArtifacts = project.getAttachedArtifacts();

            for (Artifact artifact : attachedArtifacts) {
                artifacts.add(artifact);
            }

            for (Artifact artifact : artifacts) {
                final File file = artifact.getFile();
                if (file != null) {
                    dataProducers.add(new DataProducer() {
                        @Override
                        public void produce(final DataConsumer receiver) {
                            try {
                                final File path = new File(installDirFile.getPath(), file.getName());
                                final String entryName = path.getPath();

                                final boolean symbolicLink = SymlinkUtils.isSymbolicLink(path);
                                final TarArchiveEntry e;
                                if (symbolicLink) {
                                    e = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
                                    e.setLinkName(SymlinkUtils.readSymbolicLink(path));
                                } else {
                                    e = new TarArchiveEntry(entryName, true);
                                }

                                e.setUserId(0);
                                e.setGroupId(0);
                                e.setUserName("root");
                                e.setGroupName("root");
                                e.setMode(TarEntry.DEFAULT_FILE_MODE);
                                e.setSize(file.length());

                                receiver.onEachFile(new FileInputStream(file), e);
                            } catch (Exception e) {
                                getLog().error(e);
                            }
                        }
                    });
                } else {
                    getLog().error("No file for artifact " + artifact);
                }
            }
        }
    }

    try {
        DebMaker debMaker = new DebMaker(console, dataProducers, conffileProducers);
        debMaker.setDeb(debFile);
        debMaker.setControl(controlDirFile);
        debMaker.setPackage(getProject().getArtifactId());
        debMaker.setDescription(getProject().getDescription());
        debMaker.setHomepage(getProject().getUrl());
        debMaker.setChangesIn(changesInFile);
        debMaker.setChangesOut(changesOutFile);
        debMaker.setChangesSave(changesSaveFile);
        debMaker.setCompression(compression);
        debMaker.setKeyring(keyringFile);
        debMaker.setKey(key);
        debMaker.setPassphrase(passphrase);
        debMaker.setSignPackage(signPackage);
        debMaker.setSignMethod(signMethod);
        debMaker.setSignRole(signRole);
        debMaker.setResolver(resolver);
        debMaker.setOpenReplaceToken(openReplaceToken);
        debMaker.setCloseReplaceToken(closeReplaceToken);
        debMaker.validate();
        debMaker.makeDeb();

        // Always attach unless explicitly set to false
        if ("true".equalsIgnoreCase(attach)) {
            console.info("Attaching created debian package " + debFile);
            if (!isType()) {
                projectHelper.attachArtifact(project, type, classifier, debFile);
            } else {
                project.getArtifact().setFile(debFile);
            }
        }

    } catch (PackagingException e) {
        getLog().error("Failed to create debian package " + debFile, e);
        throw new MojoExecutionException("Failed to create debian package " + debFile, e);
    }

    if (!StringUtils.isBlank(propertyPrefix)) {
        project.getProperties().put(propertyPrefix + "version", getProjectVersion());
        project.getProperties().put(propertyPrefix + "deb", debFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "deb.name", debFile.getName());
        project.getProperties().put(propertyPrefix + "changes", changesOutFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "changes.name", changesOutFile.getName());
        project.getProperties().put(propertyPrefix + "changes.txt", changesSaveFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "changes.txt.name", changesSaveFile.getName());
    }

}