List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveOutputStream putArchiveEntry
public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException
From source file:gov.nih.nci.nbia.servlet.DownloadServletV2.java
private void sendImagesData(List<ImageDTO2> imageResults, TarArchiveOutputStream tos) throws IOException { InputStream dicomIn = null;/*from w ww .java2 s. com*/ try { for (ImageDTO2 imageDto : imageResults) { String filePath = imageDto.getFileName(); String sop = imageDto.getSOPInstanceUID(); logger.info("filepath: " + filePath + " filename: " + sop); try { File dicomFile = new File(filePath); ArchiveEntry tarArchiveEntry = tos.createArchiveEntry(dicomFile, sop + ".dcm"); dicomIn = new FileInputStream(dicomFile); tos.putArchiveEntry(tarArchiveEntry); IOUtils.copy(dicomIn, tos); tos.closeArchiveEntry(); } catch (FileNotFoundException e) { e.printStackTrace(); // just print the exception and continue the loop so rest of // images will get download. } finally { IOUtils.closeQuietly(dicomIn); logger.info("DownloadServlet Image transferred at " + new Date().getTime()); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:de.uzk.hki.da.pkg.NativeJavaTarArchiveBuilder.java
/** * There is an option to override the name of the first level entry if you want to pack * a directory. Set includeFolder = true so that it not only packs the contents but also * the containing folder. Then use the setter setFirstLevelEntryName and set the name * of the folder which contains the files to pack. The name of the folder then gets replaced * in the resulting tar. Note that after calling archiveFolder once, the variable gets automatically * reset so that you have to call the setter again if you want to set the override setting again. *//*from w ww . ja v a 2 s .c o m*/ public void archiveFolder(File srcFolder, File destFile, boolean includeFolder) throws Exception { FileOutputStream fOut = null; BufferedOutputStream bOut = null; TarArchiveOutputStream tOut = null; fOut = new FileOutputStream(destFile); bOut = new BufferedOutputStream(fOut); tOut = new TarArchiveOutputStream(bOut); tOut.setLongFileMode(longFileMode); tOut.setBigNumberMode(bigNumberMode); try { String base = ""; if (firstLevelEntryName.isEmpty()) firstLevelEntryName = srcFolder.getName() + "/"; if (includeFolder) { logger.debug("addFileToTar: " + firstLevelEntryName); TarArchiveEntry entry = (TarArchiveEntry) tOut.createArchiveEntry(srcFolder, firstLevelEntryName); tOut.putArchiveEntry(entry); tOut.closeArchiveEntry(); base = firstLevelEntryName; } File children[] = srcFolder.listFiles(); for (int i = 0; i < children.length; i++) { addFileToTar(tOut, children[i], base); } } finally { tOut.finish(); tOut.close(); bOut.close(); fOut.close(); firstLevelEntryName = ""; } }
From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java
/** * Encrypts and encodes the string and writes it to the tar output stream with the specified file name *///from w w w . ja v a 2s .co m protected void encryptAndWrite(TarArchiveOutputStream tarArchiveOutputStream, String contents, String fileName) throws InvalidCipherTextException, IOException { final byte[] contentBytes = contents.getBytes(CHARSET); //Encrypt contents final AsymmetricBlockCipher encryptCipher = this.getEncryptCipher(); final byte[] encryptedContentBytes = encryptCipher.processBlock(contentBytes, 0, contentBytes.length); final byte[] encryptedContentBase64Bytes = Base64.encodeBase64(encryptedContentBytes); //Write encrypted contents to tar output stream final TarArchiveEntry contentEntry = new TarArchiveEntry(fileName); contentEntry.setSize(encryptedContentBase64Bytes.length); tarArchiveOutputStream.putArchiveEntry(contentEntry); tarArchiveOutputStream.write(encryptedContentBase64Bytes); tarArchiveOutputStream.closeArchiveEntry(); }
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//ww w.ja va 2 s. 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:freenet.client.async.ContainerInserter.java
/** ** OutputStream os will be close()d if this method returns successfully. *//*from w ww . j av a2s .c o m*/ private String createTarBucket(OutputStream os) throws IOException { if (logMINOR) Logger.minor(this, "Create a TAR Bucket"); TarArchiveOutputStream tarOS = new TarArchiveOutputStream(os); try { tarOS.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry ze; for (ContainerElement ph : containerItems) { if (logMINOR) Logger.minor(this, "Putting into tar: " + ph + " data length " + ph.data.size() + " name " + ph.targetInArchive); ze = new TarArchiveEntry(ph.targetInArchive); ze.setModTime(0); long size = ph.data.size(); ze.setSize(size); tarOS.putArchiveEntry(ze); BucketTools.copyTo(ph.data, tarOS, size); tarOS.closeArchiveEntry(); } } finally { tarOS.close(); } return ARCHIVE_TYPE.TAR.mimeTypes[0]; }
From source file:adams.core.io.TarUtils.java
/** * Creates a tar file from the specified files. * <br><br>/*from ww w. j a v a 2s . c o m*/ * See <a href="http://www.thoughtspark.org/node/53" target="_blank">Creating a tar.gz with commons-compress</a>. * * @param output the output file to generate * @param files the files to store in the tar file * @param stripRegExp the regular expression used to strip the file names * @param bufferSize the buffer size to use * @return null if successful, otherwise error message */ @MixedCopyright(author = "Jeremy Whitlock (jcscoobyrs)", copyright = "2010 Jeremy Whitlock", license = License.APACHE2, url = "http://www.thoughtspark.org/node/53") public static String compress(File output, File[] files, String stripRegExp, int bufferSize) { String result; int i; byte[] buf; int len; TarArchiveOutputStream out; BufferedInputStream in; FileInputStream fis; FileOutputStream fos; String filename; String msg; TarArchiveEntry entry; in = null; fis = null; out = null; fos = null; result = null; try { // does file already exist? if (output.exists()) System.err.println("WARNING: overwriting '" + output + "'!"); // create tar file buf = new byte[bufferSize]; fos = new FileOutputStream(output.getAbsolutePath()); out = openArchiveForWriting(output, fos); for (i = 0; i < files.length; i++) { fis = new FileInputStream(files[i].getAbsolutePath()); in = new BufferedInputStream(fis); // Add tar entry to output stream. filename = files[i].getParentFile().getAbsolutePath(); if (stripRegExp.length() > 0) filename = filename.replaceFirst(stripRegExp, ""); if (filename.length() > 0) filename += File.separator; filename += files[i].getName(); entry = new TarArchiveEntry(filename); if (files[i].isFile()) entry.setSize(files[i].length()); out.putArchiveEntry(entry); // Transfer bytes from the file to the tar file while ((len = in.read(buf)) > 0) out.write(buf, 0, len); // Complete the entry out.closeArchiveEntry(); FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); in = null; fis = null; } // Complete the tar file FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); out = null; fos = null; } catch (Exception e) { msg = "Failed to generate archive '" + output + "': "; System.err.println(msg); e.printStackTrace(); result = msg + e; } finally { FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } return result; }
From source file:com.st.maven.debian.DebianPackageMojo.java
private void fillDataTar(Config config, ArFileOutputStream output) throws MojoExecutionException { TarArchiveOutputStream tar = null; try {/*from ww w .java 2 s . co m*/ 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:io.anserini.index.IndexUtils.java
public void dumpRawDocuments(String reqDocidsPath, boolean prependDocid) throws IOException, NotStoredException { LOG.info("Start dump raw documents" + (prependDocid ? " with Docid prepended" : ".")); InputStream in = getReadFileStream(reqDocidsPath); BufferedReader bRdr = new BufferedReader(new InputStreamReader(in)); FileOutputStream fOut = new FileOutputStream(new File(reqDocidsPath + ".output.tar.gz")); BufferedOutputStream bOut = new BufferedOutputStream(fOut); GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(bOut); TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut); String docid;//from ww w.j a v a 2s . co m int counter = 0; while ((docid = bRdr.readLine()) != null) { counter += 1; Document d = reader.document(convertDocidToLuceneDocid(docid)); IndexableField doc = d.getField(LuceneDocumentGenerator.FIELD_RAW); if (doc == null) { throw new NotStoredException("Raw documents not stored!"); } TarArchiveEntry tarEntry = new TarArchiveEntry(new File(docid)); byte[] bytesOut = doc.stringValue().getBytes(StandardCharsets.UTF_8); tarEntry.setSize( bytesOut.length + (prependDocid ? String.format("<DOCNO>%s</DOCNO>\n", docid).length() : 0)); tOut.putArchiveEntry(tarEntry); if (prependDocid) { tOut.write(String.format("<DOCNO>%s</DOCNO>\n", docid).getBytes()); } tOut.write(bytesOut); tOut.closeArchiveEntry(); if (counter % 100000 == 0) { LOG.info(counter + " files have been dumped."); } } tOut.close(); LOG.info(String.format("Raw documents are output to: %s", reqDocidsPath + ".output.tar.gz")); }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.FilePackager.java
private void copyFileToArchive(final TarArchiveOutputStream out, final String tempFilename, final String filename) throws IOException { if (StringUtils.isEmpty(tempFilename)) { return;// ww w .jav a2 s.co m } final byte[] buffer = new byte[1024]; final File file = new File(tempFilename); if (!file.exists()) { throw new IOException("File does not exist: " + tempFilename); } final TarArchiveEntry tarAdd = new TarArchiveEntry(file); tarAdd.setModTime(file.lastModified()); tarAdd.setName(filename); out.putArchiveEntry(tarAdd); FileInputStream in = null; try { in = new FileInputStream(file); int nRead = in.read(buffer, 0, buffer.length); while (nRead >= 0) { out.write(buffer, 0, nRead); nRead = in.read(buffer, 0, buffer.length); } } finally { if (in != null) { in.close(); } } out.closeArchiveEntry(); }
From source file:com.st.maven.debian.DebianPackageMojo.java
private void addRecursively(Config config, TarArchiveOutputStream tar, Fileset fileset) throws MojoExecutionException { File sourceFile = new File(fileset.getSource()); String targetFilename = fileset.getTarget(); // skip well-known ignore directories if (ignore.contains(sourceFile.getName()) || sourceFile.getName().endsWith(".rrd") || sourceFile.getName().endsWith(".log")) { return;//from ww w .j a va 2 s . c o m } FileInputStream fis = null; try { if (!sourceFile.isDirectory()) { TarArchiveEntry curEntry = new TarArchiveEntry(targetFilename); if (fileset.isFilter()) { byte[] bytes = processTemplate(freemarkerConfig, config, fileset.getSource()); curEntry.setSize(bytes.length); tar.putArchiveEntry(curEntry); tar.write(bytes); } else { curEntry.setSize(sourceFile.length()); tar.putArchiveEntry(curEntry); fis = new FileInputStream(sourceFile); IOUtils.copy(fis, tar); } tar.closeArchiveEntry(); } else if (sourceFile.isDirectory()) { targetFilename += "/"; if (!dirsAdded.contains(targetFilename)) { dirsAdded.add(targetFilename); writeDirectory(tar, targetFilename); } } } catch (Exception e) { throw new MojoExecutionException("unable to write", e); } finally { IOUtils.closeQuietly(fis); } if (sourceFile.isDirectory()) { File[] subFiles = sourceFile.listFiles(); for (File curSubFile : subFiles) { Fileset curSubFileset = new Fileset(fileset.getSource() + "/" + curSubFile.getName(), fileset.getTarget() + "/" + curSubFile.getName(), fileset.isFilter()); addRecursively(config, tar, curSubFileset); } } }