org.apache.commons.compress.archivers.tar.TarArchiveEntry Java Examples

The following examples show how to use org.apache.commons.compress.archivers.tar.TarArchiveEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TarUnpackerSequenceFileWriter.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
@Override
protected void processInputStream(final InputStream stream, final FlowFile tarArchivedFlowFile, final Writer writer) throws IOException {
    try (final TarArchiveInputStream tarIn = new TarArchiveInputStream(new BufferedInputStream(stream))) {
        TarArchiveEntry tarEntry;
        while ((tarEntry = tarIn.getNextTarEntry()) != null) {
            if (tarEntry.isDirectory()) {
                continue;
            }
            final String key = tarEntry.getName();
            final long fileSize = tarEntry.getSize();
            final InputStreamWritable inStreamWritable = new InputStreamWritable(tarIn, (int) fileSize);
            writer.append(new Text(key), inStreamWritable);
            logger.debug("Appending FlowFile {} to Sequence File", new Object[]{key});
        }
    }
}
 
Example #2
Source File: Utils.java    From tutorials with MIT License 7 votes vote down vote up
/**
 * Extract a "tar.gz" file into a given folder.
 * @param file
 * @param folder 
 */
public static void extractTarArchive(File file, String folder) throws IOException {
    logger.info("Extracting archive {} into folder {}", file.getName(), folder);
    // @formatter:off
    try (FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis); 
        TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) {
   // @formatter:on
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) {
            extractEntry(entry, tar, folder);
        }
    }
  logger.info("Archive extracted"); 
}
 
Example #3
Source File: FileHelper.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private static void addFileToArchive(TarArchiveOutputStream archiveOutputStream, File file,
                                     String base) throws IOException {
  final File absoluteFile = file.getAbsoluteFile();
  final String entryName = base + file.getName();
  final TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, entryName);
  archiveOutputStream.putArchiveEntry(tarArchiveEntry);

  if (absoluteFile.isFile()) {
    Files.copy(file.toPath(), archiveOutputStream);
    archiveOutputStream.closeArchiveEntry();
  } else {
    archiveOutputStream.closeArchiveEntry();
    if (absoluteFile.listFiles() != null) {
      for (File f : absoluteFile.listFiles()) {
        addFileToArchive(archiveOutputStream, f, entryName + "/");
      }
    }
  }
}
 
Example #4
Source File: DatabaseMigrationAcceptanceTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private static void extract(final Path path, final String destDirectory) throws IOException {
  try (TarArchiveInputStream fin =
      new TarArchiveInputStream(
          new GzipCompressorInputStream(new FileInputStream(path.toAbsolutePath().toString())))) {
    TarArchiveEntry entry;
    while ((entry = fin.getNextTarEntry()) != null) {
      if (entry.isDirectory()) {
        continue;
      }
      final File curfile = new File(destDirectory, entry.getName());
      final File parent = curfile.getParentFile();
      if (!parent.exists()) {
        parent.mkdirs();
      }
      IOUtils.copy(fin, new FileOutputStream(curfile));
    }
  }
}
 
Example #5
Source File: ExpProc.java    From Export with Apache License 2.0 6 votes vote down vote up
private void addArchive(File file, TarArchiveOutputStream aos,
		String basepath) throws Exception {
	if (file.exists()) {
		TarArchiveEntry entry = new TarArchiveEntry(basepath + "/"
				+ file.getName());
		entry.setSize(file.length());
		aos.putArchiveEntry(entry);
		BufferedInputStream bis = new BufferedInputStream(
				new FileInputStream(file));
		int count;
		byte data[] = new byte[1024];
		while ((count = bis.read(data, 0, data.length)) != -1) {
			aos.write(data, 0, count);
		}
		bis.close();
		aos.closeArchiveEntry();
	}
}
 
Example #6
Source File: NPMPackageGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public void loadFiles(String root, File dir, String... noload) throws IOException {
  for (File f : dir.listFiles()) {
    if (!Utilities.existsInList(f.getName(), noload)) {
      if (f.isDirectory()) {
        loadFiles(root, f);
      } else {
        String path = f.getAbsolutePath().substring(root.length()+1);
        byte[] content = TextFile.fileToBytes(f);
        if (created.contains(path)) 
          System.out.println("Duplicate package file "+path);
        else {
          created.add(path);
          TarArchiveEntry entry = new TarArchiveEntry(path);
          entry.setSize(content.length);
          tar.putArchiveEntry(entry);
          tar.write(content);
          tar.closeArchiveEntry();
        }
      }
    }
  }
}
 
Example #7
Source File: PackageBuilderTest.java    From dropwizard-debpkg-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileOwnershipAndPermissions() throws IOException, PackagingException {
    final File debFile = createPackage(ImmutableList.<Resource>of(
            new StringResource("hello world", true, "/test.txt", USER, USER, 0764)
    ));

    final File packageDir = temporaryFolder.newFolder();
    ArchiveUtils.extractAr(debFile, packageDir);

    try (final TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(new File(packageDir, "data.tar.gz"))))) {
        final TarArchiveEntry entry = in.getNextTarEntry();
        assertEquals("./test.txt", entry.getName());
        assertEquals(USER, entry.getUserName());
        assertEquals(USER, entry.getGroupName());
        assertEquals(0764, entry.getMode());
    }
}
 
Example #8
Source File: FlowFilePackagerV1.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout) throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties\n  SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n");
    sb.append("<properties>");
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String escapedKey = StringEscapeUtils.escapeXml11(entry.getKey());
        final String escapedValue = StringEscapeUtils.escapeXml11(entry.getValue());
        sb.append("\n  <entry key=\"").append(escapedKey).append("\">").append(escapedValue).append("</entry>");
    }
    sb.append("</properties>");

    final byte[] metaBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
    final TarArchiveEntry attribEntry = new TarArchiveEntry(FILENAME_ATTRIBUTES);
    attribEntry.setMode(tarPermissions);
    attribEntry.setSize(metaBytes.length);
    tout.putArchiveEntry(attribEntry);
    tout.write(metaBytes);
    tout.closeArchiveEntry();
}
 
Example #9
Source File: FlowFilePackagerV1.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout) throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties\n  SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n");
    sb.append("<properties>");
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String escapedKey = StringEscapeUtils.escapeXml11(entry.getKey());
        final String escapedValue = StringEscapeUtils.escapeXml11(entry.getValue());
        sb.append("\n  <entry key=\"").append(escapedKey).append("\">").append(escapedValue).append("</entry>");
    }
    sb.append("</properties>");

    final byte[] metaBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
    final TarArchiveEntry attribEntry = new TarArchiveEntry(FILENAME_ATTRIBUTES);
    attribEntry.setMode(tarPermissions);
    attribEntry.setSize(metaBytes.length);
    tout.putArchiveEntry(attribEntry);
    tout.write(metaBytes);
    tout.closeArchiveEntry();
}
 
Example #10
Source File: MaxMindGeoLocationService.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
public Future<?> setDataPath(String dataFilePath) {
    try (TarArchiveInputStream tarInput = new TarArchiveInputStream(new GZIPInputStream(
            new FileInputStream(dataFilePath)))) {

        TarArchiveEntry currentEntry;
        boolean hasDatabaseFile = false;
        while ((currentEntry = tarInput.getNextTarEntry()) != null) {
            if (currentEntry.getName().contains(DATABASE_FILE_NAME)) {
                hasDatabaseFile = true;
                break;
            }
        }
        if (!hasDatabaseFile) {
            return Future.failedFuture(String.format("Database file %s not found in %s archive", DATABASE_FILE_NAME,
                    dataFilePath));
        }

        databaseReader = new DatabaseReader.Builder(tarInput).fileMode(Reader.FileMode.MEMORY).build();
        return Future.succeededFuture();
    } catch (IOException e) {
        return Future.failedFuture(
                String.format("IO Exception occurred while trying to read an archive/db file: %s", e.getMessage()));
    }
}
 
Example #11
Source File: Packaging.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public static void tar(Path inputPath, Path outputPath) throws IOException {
  if (!Files.exists(inputPath)) {
    throw new FileNotFoundException("File not found " + inputPath);
  }

  try (TarArchiveOutputStream tarArchiveOutputStream = buildTarStream(outputPath.toFile())) {
    if (!Files.isDirectory(inputPath)) {
      TarArchiveEntry tarEntry = new TarArchiveEntry(inputPath.toFile().getName());
      if (inputPath.toFile().canExecute()) {
        tarEntry.setMode(tarEntry.getMode() | 0755);
      }
      putTarEntry(tarArchiveOutputStream, tarEntry, inputPath);
    } else {
      Files.walkFileTree(inputPath,
                         new TarDirWalker(inputPath, tarArchiveOutputStream));
    }
    tarArchiveOutputStream.flush();
  }
}
 
Example #12
Source File: AbstractInitializrIntegrationTests.java    From initializr with Apache License 2.0 6 votes vote down vote up
private void untar(Path archiveFile, Path project) throws IOException {
	try (TarArchiveInputStream input = new TarArchiveInputStream(
			new GzipCompressorInputStream(Files.newInputStream(archiveFile)))) {
		TarArchiveEntry entry = null;
		while ((entry = input.getNextTarEntry()) != null) {
			Path path = project.resolve(entry.getName());
			if (entry.isDirectory()) {
				Files.createDirectories(path);
			}
			else {
				Files.createDirectories(path.getParent());
				Files.write(path, StreamUtils.copyToByteArray(input));
			}
			applyPermissions(path, getPosixFilePermissions(entry.getMode()));
		}
	}
}
 
Example #13
Source File: FileSystemObjectImportStructureProvider.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get the IFileSystemObject corresponding to the specified raw object
 *
 * @param o
 *            the raw object
 * @return the corresponding IFileSystemObject
 */
public IFileSystemObject getIFileSystemObject(Object o) {
    if (o == null) {
        return null;
    }

    if (o instanceof File) {
        return new FileFileSystemObject((File) o);
    } else if (o instanceof TarArchiveEntry) {
        return new TarFileSystemObject((TarArchiveEntry) o, fArchivePath);
    } else if (o instanceof ZipArchiveEntry) {
        return new ZipFileSystemObject((ZipArchiveEntry) o, fArchivePath);
    } else if (o instanceof GzipEntry) {
        return new GzipFileSystemObject((GzipEntry) o, fArchivePath);
    }

    throw new IllegalArgumentException("Object type not handled"); //$NON-NLS-1$
}
 
Example #14
Source File: CompressedDirectory.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir,
                                         BasicFileAttributes attrs) throws IOException {
  if (Files.isSameFile(dir, root)) {
    return FileVisitResult.CONTINUE;
  }

  final Path relativePath = root.relativize(dir);

  if (exclude(ignoreMatchers, relativePath)) {
    return FileVisitResult.CONTINUE;
  }

  final TarArchiveEntry entry = new TarArchiveEntry(dir.toFile());
  entry.setName(relativePath.toString());
  entry.setMode(getFileMode(dir));
  tarStream.putArchiveEntry(entry);
  tarStream.closeArchiveEntry();
  return FileVisitResult.CONTINUE;
}
 
Example #15
Source File: TarGzipPacker.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * given tar.gz file will be copied to this tar.gz file.
 * all files will be transferred to new tar.gz file one by one.
 * original directory structure will be kept intact
 *
 * @param zipFile the archive file to be copied to the new archive
 * @param dirPrefixForTar sub path inside the archive
 */
public boolean addZipToArchive(String zipFile, String dirPrefixForTar) {
  try {
    // construct input stream
    ZipFile zipFileObj = new ZipFile(zipFile);
    Enumeration<? extends ZipEntry> entries = zipFileObj.entries();

    // copy the existing entries from source gzip file
    while (entries.hasMoreElements()) {
      ZipEntry nextEntry = entries.nextElement();
      TarArchiveEntry entry = new TarArchiveEntry(dirPrefixForTar + nextEntry.getName());
      entry.setSize(nextEntry.getSize());
      entry.setModTime(nextEntry.getTime());

      tarOutputStream.putArchiveEntry(entry);
      IOUtils.copy(zipFileObj.getInputStream(nextEntry), tarOutputStream);
      tarOutputStream.closeArchiveEntry();
    }

    zipFileObj.close();
    return true;
  } catch (IOException ioe) {
    LOG.log(Level.SEVERE, "Archive File can not be added: " + zipFile, ioe);
    return false;
  }
}
 
Example #16
Source File: DebianPackageWriter.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private static void applyInfo ( final TarArchiveEntry entry, final EntryInformation entryInformation )
{
    if ( entryInformation == null )
    {
        return;
    }

    if ( entryInformation.getUser () != null )
    {
        entry.setUserName ( entryInformation.getUser () );
    }
    if ( entryInformation.getGroup () != null )
    {
        entry.setGroupName ( entryInformation.getGroup () );
    }
    entry.setMode ( entryInformation.getMode () );
}
 
Example #17
Source File: ExtractUtils.java    From MSPaintIDE with MIT License 6 votes vote down vote up
public static void untar(TarArchiveInputStream tarIn, File targetDir) throws IOException {
    byte[] b = new byte[4096];
    TarArchiveEntry tarEntry;
    while ((tarEntry = tarIn.getNextTarEntry()) != null) {
        final File file = new File(targetDir, tarEntry.getName());
        if (tarEntry.isDirectory()) {
            if (!file.mkdirs()) {
                throw new IOException("Unable to create folder " + file.getAbsolutePath());
            }
        } else {
            final File parent = file.getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs()) {
                    throw new IOException("Unable to create folder " + parent.getAbsolutePath());
                }
            }
            try (FileOutputStream fos = new FileOutputStream(file)) {
                int r;
                while ((r = tarIn.read(b)) != -1) {
                    fos.write(b, 0, r);
                }
            }
        }
    }
}
 
Example #18
Source File: FileUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Wraps the parent stream into TarInputStream 
 * and positions it to read the given entry (no wildcards are applicable).
 * 
 * If no entry is given, the stream is positioned to read the first file entry.
 * 
 * @param parentStream
 * @param entryName
 * @return
 * @throws IOException
 */
public static TarArchiveInputStream getTarInputStream(InputStream parentStream, String entryName) throws IOException {
    TarArchiveInputStream tis = new TarArchiveInputStream(parentStream) ;     
    TarArchiveEntry entry;

    // find a matching entry
    while ((entry = tis.getNextTarEntry()) != null) {
    	if (entry.isDirectory()) {
    		continue; // CLS-537: skip directories, we want to read the first file
    	}
    	// when url is given without anchor; first entry in tar file is used
        if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
           	return tis;
        }
    }
    
    //no entry found report
    throw new IOException("Wrong anchor (" + entryName + ") to tar file.");
}
 
Example #19
Source File: GeneratorService.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
private void addFile(Path rootPath, Path filePath, ArchiveOutputStream stream) throws IOException {
  String relativePath = rootPath.relativize(filePath).toString();
  if (relativePath.length() == 0) return;
  String entryName = jarFileWorkAround(leadingDot(relativePath));
  ArchiveEntry entry = stream.createArchiveEntry(filePath.toFile(), entryName);
  if (EXECUTABLES.contains(entryName)) {
    if (entry instanceof ZipArchiveEntry) {
      ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entry;
      zipArchiveEntry.setUnixMode(0744);
    } else if (entry instanceof TarArchiveEntry) {
      TarArchiveEntry tarArchiveEntry = (TarArchiveEntry) entry;
      tarArchiveEntry.setMode(0100744);
    }
  }
  stream.putArchiveEntry(entry);
  if (filePath.toFile().isFile()) {
    try (InputStream i = Files.newInputStream(filePath)) {
      IOUtils.copy(i, stream);
    }
  }
  stream.closeArchiveEntry();
}
 
Example #20
Source File: CompressedDirectoryTest.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithEmptyDirectory() throws Exception {
  Path tempDir = Files.createTempDirectory("dockerDirectoryEmptySubdirectory");
  tempDir.toFile().deleteOnExit();
  assertThat(new File(tempDir.toFile(), "emptySubDir").mkdir(), is(true));

  try (CompressedDirectory dir = CompressedDirectory.create(tempDir);
       BufferedInputStream fileIn = new BufferedInputStream(Files.newInputStream(dir.file()));
       GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(fileIn);
       TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {

    final List<String> names = new ArrayList<>();
    TarArchiveEntry entry;
    while ((entry = tarIn.getNextTarEntry()) != null) {
      final String name = entry.getName();
      names.add(name);
    }
    assertThat(names, contains("emptySubDir/"));
  }
}
 
Example #21
Source File: TarUtils.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static void addToArchiveCompression(TarArchiveOutputStream out, File file, String dir)
    throws IOException {
  if (file.isFile()){
    String archivePath = "." + dir;
    LOGGER.info("archivePath = " + archivePath);
    out.putArchiveEntry(new TarArchiveEntry(file, archivePath));
    try (FileInputStream in = new FileInputStream(file)) {
      IOUtils.copy(in, out);
    }
    out.closeArchiveEntry();
  } else if (file.isDirectory()) {
    File[] children = file.listFiles();
    if (children != null){
      for (File child : children){
        String appendDir = child.getAbsolutePath().replace(file.getAbsolutePath(), "");
        addToArchiveCompression(out, child, dir + appendDir);
      }
    }
  } else {
    LOGGER.error(file.getName() + " is not supported");
  }
}
 
Example #22
Source File: DeployOvfTemplateService.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@NotNull
private String getOvfTemplateAsString(final String templatePath) throws IOException {
    if (isOva(Paths.get(templatePath))) {
        try (final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templatePath))) {
            TarArchiveEntry entry;
            while ((entry = tar.getNextTarEntry()) != null) {
                if (isOvf(Paths.get(new File(entry.getName()).getName()))) {
                    return OvfUtils.writeToString(tar, entry.getSize());
                }
            }
        }
    } else if (isOvf(Paths.get(templatePath))) {
        final InputStream inputStream = new FileInputStream(templatePath);
        return IOUtils.toString(inputStream, UTF_8);
    }
    throw new RuntimeException(FILE_COULD_NOT_BE_READ);
}
 
Example #23
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static void addFileToTar(String rootTarPath, File file, TarArchiveOutputStream tar)
  throws IOException {

  final String fileName =
    Optional.ofNullable(rootTarPath).orElse("") + TAR_PATH_DELIMITER + file.getName();
  tar.putArchiveEntry(new TarArchiveEntry(file, fileName));
  if (file.isFile()) {
    Files.copy(file.toPath(), tar);
    tar.closeArchiveEntry();
  } else if (file.isDirectory()) {
    tar.closeArchiveEntry();
    for (File fileInDirectory : file.listFiles()) {
      addFileToTar(fileName, fileInDirectory, tar);
    }
  }
}
 
Example #24
Source File: AttributeAccessor.java    From jarchivelib with Apache License 2.0 6 votes vote down vote up
/**
 * Detects the type of the given ArchiveEntry and returns an appropriate AttributeAccessor for it.
 * 
 * @param entry the adaptee
 * @return a new attribute accessor instance
 */
public static AttributeAccessor<?> create(ArchiveEntry entry) {
    if (entry instanceof TarArchiveEntry) {
        return new TarAttributeAccessor((TarArchiveEntry) entry);
    } else if (entry instanceof ZipArchiveEntry) {
        return new ZipAttributeAccessor((ZipArchiveEntry) entry);
    } else if (entry instanceof CpioArchiveEntry) {
        return new CpioAttributeAccessor((CpioArchiveEntry) entry);
    } else if (entry instanceof ArjArchiveEntry) {
        return new ArjAttributeAccessor((ArjArchiveEntry) entry);
    } else if (entry instanceof ArArchiveEntry) {
        return new ArAttributeAccessor((ArArchiveEntry) entry);
    }

    return new FallbackAttributeAccessor(entry);
}
 
Example #25
Source File: DeployOvfTemplateService.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
private ITransferVmdkFrom getTransferVmdK(final String templateFilePathStr, final String vmdkName) throws IOException {
    final Path templateFilePath = Paths.get(templateFilePathStr);
    if (isOva(templateFilePath)) {
        final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templateFilePathStr));
        TarArchiveEntry entry;
        while ((entry = tar.getNextTarEntry()) != null) {
            if (new File(entry.getName()).getName().startsWith(vmdkName)) {
                return new TransferVmdkFromInputStream(tar, entry.getSize());
            }
        }
    } else if (isOvf(templateFilePath)) {
        final Path vmdkPath = templateFilePath.getParent().resolve(vmdkName);
        return new TransferVmdkFromFile(vmdkPath.toFile());
    }
    throw new RuntimeException(NOT_OVA_OR_OVF);
}
 
Example #26
Source File: LifecycleChaincodePackage.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
public JsonObject getMetaInfJson() throws IOException {

        try (TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new ByteArrayInputStream(pBytes)))) {

            TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
            while (currentEntry != null) {
                if (currentEntry.getName().equals("metadata.json")) {
                    byte[] buf = new byte[(int) currentEntry.getSize()];
                    tarInput.read(buf, 0, (int) currentEntry.getSize());

                    try (InputStream stream = new ByteArrayInputStream(buf)) {
                        try (JsonReader reader = Json.createReader(stream)) {

                            return (JsonObject) reader.read();
                        }
                    }

                }
                currentEntry = tarInput.getNextTarEntry();

            }
        }

        return null;
    }
 
Example #27
Source File: CustomProcessorUploadHandler.java    From streamline with Apache License 2.0 6 votes vote down vote up
private byte[] getFileAsByteArray (File tarFile, Function<String, Boolean> filterFunc) {
    byte[] data = null;
    LOG.info("Looking in to file {} ", tarFile);
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tarFile));
         TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(bis)) {
        TarArchiveEntry tarArchiveEntry = tarArchiveInputStream.getNextTarEntry();
        while (tarArchiveEntry != null) {
            if (filterFunc.apply(tarArchiveEntry.getName())) {
                data = IOUtils.toByteArray(tarArchiveInputStream);
                break;
            }
            tarArchiveEntry = tarArchiveInputStream.getNextTarEntry();
        }
    } catch (IOException e) {
        LOG.warn("Exception occured while looking in to tar file [] ", filterFunc, tarFile, e);
    }
    return data;
}
 
Example #28
Source File: TarUtils.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 数据归档
 *
 * @param data
 *            待归档数据
 * @param path
 *            归档数据的当前路径
 * @param name
 *            归档文件名
 * @param taos
 *            TarArchiveOutputStream
 * @throws Exception
 */
private static void archiveFile(File file, TarArchiveOutputStream taos,
                                String dir) throws Exception {

    /**
     * 归档内文件名定义
     *
     * <pre>
     * 如果有多级目录,那么这里就需要给出包含目录的文件名
     * 如果用WinRAR打开归档包,中文名将显示为乱码
     * </pre>
     */
    TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());

    entry.setSize(file.length());

    taos.putArchiveEntry(entry);

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
            file));
    int count;
    byte data[] = new byte[BUFFER];
    while ((count = bis.read(data, 0, BUFFER)) != -1) {
        taos.write(data, 0, count);
    }

    bis.close();

    taos.closeArchiveEntry();
}
 
Example #29
Source File: Packages.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public static Map<String, String> parseControlFile ( final File packageFile ) throws IOException, ParserException
{
    try ( final ArArchiveInputStream in = new ArArchiveInputStream ( new FileInputStream ( packageFile ) ) )
    {
        ArchiveEntry ar;
        while ( ( ar = in.getNextEntry () ) != null )
        {
            if ( !ar.getName ().equals ( "control.tar.gz" ) )
            {
                continue;
            }
            try ( final TarArchiveInputStream inputStream = new TarArchiveInputStream ( new GZIPInputStream ( in ) ) )
            {
                TarArchiveEntry te;
                while ( ( te = inputStream.getNextTarEntry () ) != null )
                {
                    String name = te.getName ();
                    if ( name.startsWith ( "./" ) )
                    {
                        name = name.substring ( 2 );
                    }
                    if ( !name.equals ( "control" ) )
                    {
                        continue;
                    }
                    return parseControlFile ( inputStream );
                }
            }
        }
    }
    return null;
}
 
Example #30
Source File: AbstractBaseArchiver.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static void writeArchiveEntry(final ArchiveOutputStream archive, final String name, final byte[] bytes) throws IOException {
    final TarArchiveEntry entry = new TarArchiveEntry(name);
    entry.setSize(bytes.length);
    archive.putArchiveEntry(entry);
    archive.write(bytes);
    archive.closeArchiveEntry();
}