org.apache.commons.compress.archivers.ArchiveEntry Java Examples

The following examples show how to use org.apache.commons.compress.archivers.ArchiveEntry. 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: TarGzipPacker.java    From twister2 with Apache License 2.0 8 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 tarGzipFile the archive file to be copied to the new archive
 */
public boolean addTarGzipToArchive(String tarGzipFile) {
  try {
    // construct input stream
    InputStream fin = Files.newInputStream(Paths.get(tarGzipFile));
    BufferedInputStream in = new BufferedInputStream(fin);
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
    TarArchiveInputStream tarInputStream = new TarArchiveInputStream(gzIn);

    // copy the existing entries from source gzip file
    ArchiveEntry nextEntry;
    while ((nextEntry = tarInputStream.getNextEntry()) != null) {
      tarOutputStream.putArchiveEntry(nextEntry);
      IOUtils.copy(tarInputStream, tarOutputStream);
      tarOutputStream.closeArchiveEntry();
    }

    tarInputStream.close();
    return true;
  } catch (IOException ioe) {
    LOG.log(Level.SEVERE, "Archive File can not be added: " + tarGzipFile, ioe);
    return false;
  }
}
 
Example #2
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportFolder(Folder folder) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    String xml = createXStream().toXML(folder);
    byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes);
    zipOutputStream.putArchiveEntry(zipEntryDesign);
    zipOutputStream.write(xmlBytes);
    try {
        zipOutputStream.closeArchiveEntry();
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Exception occurred while exporting folder %s.",  folder.getName()));
    }

    zipOutputStream.close();
    return byteArrayOutputStream.toByteArray();
}
 
Example #3
Source File: EventsArchiver.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void restore(final Events events, final String namespace, final Path archiveFile) throws IOException {
    checkRestoreArguments(events, namespace, archiveFile);
    // create the namespace, in case the user hasn't already
    events.create(namespace);

    long startNanos = System.nanoTime();
    long totalEventsRestored = 0;
    try (final ArchiveInputStream archive = getArchiveInputStream(archiveFile)) {
        ArchiveEntry entry;
        while ((entry = archive.getNextEntry()) != null) {
            final EventsChunk chunk = EventsChunk.parseFrom(archive);
            for (final EventsChunk.Event event : chunk.getEventsList()) {
                if (ByteString.EMPTY.equals(event.getPayload())) {
                    events.store(namespace, event.getTimestampMillis(), event.getMetadataMap(), event.getDimensionsMap());
                } else {
                    events.store(namespace, event.getTimestampMillis(), event.getMetadataMap(), event.getDimensionsMap(), event.getPayload().toByteArray());
                }
            }
            logger.info("read {} entries from chunk {} ({} bytes) into {}", chunk.getEventsCount(), entry.getName(), entry.getSize(), namespace);
            totalEventsRestored += chunk.getEventsCount();
        }
    } finally {
        logger.info("restoring {} events into namespace '{}' from archive file {} took {}s",
                totalEventsRestored, namespace, archiveFile, TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNanos));
    }
}
 
Example #4
Source File: Tar.java    From writelatex-git-bridge with MIT License 6 votes vote down vote up
public static void untar(
        InputStream tar,
        File parentDir
) throws IOException {
    TarArchiveInputStream tin = new TarArchiveInputStream(tar);
    ArchiveEntry e;
    while ((e = tin.getNextEntry()) != null) {
        File f = new File(parentDir, e.getName());
        f.setLastModified(e.getLastModifiedDate().getTime());
        f.getParentFile().mkdirs();
        if (e.isDirectory()) {
            f.mkdir();
            continue;
        }
        long size = e.getSize();
        checkFileSize(size);
        try (OutputStream out = new FileOutputStream(f)) {
            /* TarInputStream pretends each
               entry's EOF is the stream's EOF */
            IOUtils.copy(tin, out);
        }
    }
}
 
Example #5
Source File: Tar.java    From writelatex-git-bridge with MIT License 6 votes vote down vote up
private static void addTarDir(
        TarArchiveOutputStream tout,
        Path base,
        File dir
) throws IOException {
    Preconditions.checkArgument(dir.isDirectory());
    String name = base.relativize(
            Paths.get(dir.getAbsolutePath())
    ).toString();
    ArchiveEntry entry = tout.createArchiveEntry(dir, name);
    tout.putArchiveEntry(entry);
    tout.closeArchiveEntry();
    for (File f : dir.listFiles()) {
        addTarEntry(tout, base, f);
    }
}
 
Example #6
Source File: SetsArchiver.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void restore(final Sets sets, final String namespace, final Path archiveFile) throws IOException {
    checkRestoreArguments(sets, namespace, archiveFile);
    // create the namespace, in case the user hasn't already
    sets.create(namespace);
    try (final ArchiveInputStream archive = getArchiveInputStream(archiveFile)) {
        ArchiveEntry entry;
        int total = 0;
        while ((entry = archive.getNextEntry()) != null) {
            final SetsChunk chunk = SetsChunk.parseFrom(archive);
            sets.add(namespace, chunk.getSet(), chunk.getEntriesMap());
            logger.info("read {} entries from chunk {} ({} bytes) into {}.{}", chunk.getEntriesCount(), entry.getName(), entry.getSize(), namespace, chunk.getSet());
            total += chunk.getEntriesCount();
        }
        logger.info("restored {} entries int namespace '{}' from archive file {}", total, namespace, archiveFile);
    }
}
 
Example #7
Source File: RemoteApiBasedDockerProvider.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static void addToTar(ArchiveOutputStream tar, File file, String fileNameAndPath) throws IOException {
    if (!file.exists() || !file.canRead()) {
        throw new FileNotFoundException(String.format("Cannot read file %s. Are you sure it exists?",
                file.getAbsolutePath()));
    }
    if (file.isDirectory()) {
        for (File fileInDirectory : file.listFiles()) {
            if (!fileNameAndPath.endsWith("/")) {
                fileNameAndPath = fileNameAndPath + "/";
            }
            addToTar(tar, fileInDirectory, fileNameAndPath + fileInDirectory.getName());
        }
    } else {
        ArchiveEntry entry = tar.createArchiveEntry(file, fileNameAndPath);
        tar.putArchiveEntry(entry);
        try (FileInputStream fis = new FileInputStream(file)) {
            IOUtils.copy(fis, tar);
        }
        tar.closeArchiveEntry();
    }
}
 
Example #8
Source File: ComposerJsonExtractor.java    From nexus-repository-composer with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Extracts the contents for the first matching {@code composer.json} file (of which there should only be one) as a
 * map representing the parsed JSON content. If no such file is found then an empty map is returned.
 */
public Map<String, Object> extractFromZip(final Blob blob) throws IOException {
  try (InputStream is = blob.getInputStream()) {
    try (ArchiveInputStream ais = archiveStreamFactory.createArchiveInputStream(ArchiveStreamFactory.ZIP, is)) {
      ArchiveEntry entry = ais.getNextEntry();
      while (entry != null) {
        Map<String, Object> contents = processEntry(ais, entry);
        if (!contents.isEmpty()) {
          return contents;
        }
        entry = ais.getNextEntry();
      }
    }
    return Collections.emptyMap();
  }
  catch (ArchiveException e) {
    throw new IOException("Error reading from archive", e);
  }
}
 
Example #9
Source File: ArchiveUtils.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
/**
 * Extract a single file from a tar.gz file. Does not support directories.
 * NOTE: This should not be used for batch extraction of files, due to the need to iterate over the entries until the
 * specified entry is found. Use {@link #unzipFileTo(String, String)} for batch extraction instead
 *
 * @param tarGz       A tar.gz file
 * @param destination The destination file to extract to
 * @param pathInTarGz The path in the tar.gz file to extract
 */
public static void tarGzExtractSingleFile(File tarGz, File destination, String pathInTarGz) throws IOException {
    try(TarArchiveInputStream tin = new TarArchiveInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(tarGz))))) {
        ArchiveEntry entry;
        boolean extracted = false;
        while((entry = tin.getNextTarEntry()) != null){
            String name = entry.getName();
            if(pathInTarGz.equals(name)){
                try(OutputStream os = new BufferedOutputStream(new FileOutputStream(destination))){
                    IOUtils.copy(tin, os);
                }
                extracted = true;
            }
        }
        Preconditions.checkState(extracted, "No file was extracted. File not found? %s", pathInTarGz);
    }
}
 
Example #10
Source File: ObjectsArchiver.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void restore(final Objects objects, final String namespace, final Path archiveFile) throws IOException {
    checkRestoreArguments(objects, namespace, archiveFile);
    // create the namespace, in case the user hasn't already
    objects.create(namespace);
    try (final ArchiveInputStream archive = getArchiveInputStream(archiveFile)) {
        ArchiveEntry entry;
        int total = 0;
        while ((entry = archive.getNextEntry()) != null) {
            final ObjectsChunk chunk = ObjectsChunk.parseFrom(archive);
            for (final Map.Entry<String, ByteString> chunkEntry : chunk.getObjectsMap().entrySet()) {
                objects.store(namespace, chunkEntry.getKey(), chunkEntry.getValue().toByteArray());
            }
            logger.info("read {} objects from chunk {} ({} bytes) into {}", chunk.getObjectsCount(), entry.getName(), entry.getSize(), objects);
            total += chunk.getObjectsCount();
        }
        logger.info("restored {} objects into namespace '{}' from archive file {}", total, namespace, archiveFile);
    }
}
 
Example #11
Source File: P4ExtFileUtils.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
private static void extractArchive(ArchiveInputStream archiveInputStream, File outputDir)
        throws IOException {
    createDirectory(outputDir);
    try {
        ArchiveEntry entry = archiveInputStream.getNextEntry();
        while (entry != null) {
            File node = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                if (!node.mkdirs() && !node.isDirectory()) {
                    throw new IOException("Could not create directory " + node);
                }
            } else {
                extractFile(archiveInputStream, node);
            }
            entry = archiveInputStream.getNextEntry();
        }
    } finally {
        archiveInputStream.close();
    }
}
 
Example #12
Source File: Tar.java    From writelatex-git-bridge with MIT License 6 votes vote down vote up
private static void addTarFile(
        TarArchiveOutputStream tout,
        Path base,
        File file
) throws IOException {
    Preconditions.checkArgument(
            file.isFile(),
            "given file" +
            " is not file: %s", file);
    checkFileSize(file.length());
    String name = base.relativize(
            Paths.get(file.getAbsolutePath())
    ).toString();
    ArchiveEntry entry = tout.createArchiveEntry(file, name);
    tout.putArchiveEntry(entry);
    try (InputStream in = new FileInputStream(file)) {
        IOUtils.copy(in, tout);
    }
    tout.closeArchiveEntry();
}
 
Example #13
Source File: PressUtility.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public static void decompress7z(File fromFile, File toDirectory) {
	try (SevenZFile archiveInputStream = new SevenZFile(fromFile)) {
		byte[] buffer = new byte[BUFFER_SIZE];
		ArchiveEntry archiveEntry;
		while (null != (archiveEntry = archiveInputStream.getNextEntry())) {
			File file = new File(toDirectory, archiveEntry.getName());
			try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
				int length = -1;
				while ((length = archiveInputStream.read(buffer)) != -1) {
					fileOutputStream.write(buffer, 0, length);
				}
			}
		}
	} catch (IOException exception) {
		throw new IllegalStateException("解压7Z异常:", exception);
	}
}
 
Example #14
Source File: CompressionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void compressArchive(
        final Path pathToCompress,
        final ArchiveOutputStream archiveOutputStream,
        final ArchiveEntryFactory archiveEntryFactory,
        final CompressionType compressionType,
        final BuildListener listener)
        throws IOException {
    final List<File> files = addFilesToCompress(pathToCompress, listener);

    LoggingHelper.log(listener, "Compressing directory '%s' as a '%s' archive",
            pathToCompress.toString(),
            compressionType.name());

    for (final File file : files) {
        final String newTarFileName = pathToCompress.relativize(file.toPath()).toString();
        final ArchiveEntry archiveEntry = archiveEntryFactory.create(file, newTarFileName);
        archiveOutputStream.putArchiveEntry(archiveEntry);

        try (final FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream, archiveOutputStream);
        }

        archiveOutputStream.closeArchiveEntry();
    }
}
 
Example #15
Source File: ExtractionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void extractArchive(final File destination, final ArchiveInputStream archiveInputStream)
        throws IOException {
    final int BUFFER_SIZE = 8192;
    ArchiveEntry entry = archiveInputStream.getNextEntry();

    while (entry != null) {
        final File destinationFile = getDestinationFile(destination, entry.getName());

        if (entry.isDirectory()) {
            destinationFile.mkdir();
        } else {
            destinationFile.getParentFile().mkdirs();
            try (final OutputStream fileOutputStream = new FileOutputStream(destinationFile)) {
                final byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead;

                while ((bytesRead = archiveInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
            }
        }

        entry = archiveInputStream.getNextEntry();
    }
}
 
Example #16
Source File: RDescriptionUtils.java    From nexus-repository-r with Eclipse Public License 1.0 6 votes vote down vote up
private static Map<String, String> extractMetadataFromArchive(final String archiveType, final InputStream is) {
  final ArchiveStreamFactory archiveFactory = new ArchiveStreamFactory();
  try (ArchiveInputStream ais = archiveFactory.createArchiveInputStream(archiveType, is)) {
    ArchiveEntry entry = ais.getNextEntry();
    while (entry != null) {
      if (!entry.isDirectory() && DESCRIPTION_FILE_PATTERN.matcher(entry.getName()).matches()) {
        return parseDescriptionFile(ais);
      }
      entry = ais.getNextEntry();
    }
  }
  catch (ArchiveException | IOException e) {
    throw new RException(null, e);
  }
  throw new IllegalStateException("No metadata file found");
}
 
Example #17
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 #18
Source File: GPXFileSystem.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public InputStream getFileContentsAsStream(String resource) throws Throwable {
	byte[] resourceBytes = null;

	ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(new ByteArrayInputStream(this.fsBuffer));
	ArchiveEntry zipEntry = null;
	while ((zipEntry = zipInputStream.getNextEntry()) != null) {
		if (zipEntry.getName().equals(resource)) {
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			byte buffer[] = new byte[2048];
			int read = 0;
			while ((read = zipInputStream.read(buffer)) > 0) {
				out.write(buffer, 0, read);
			}

			resourceBytes = out.toByteArray();

			out.close();
		}
	}
	zipInputStream.close();

	return (resourceBytes != null ? new ByteArrayInputStream(resourceBytes) : null);
}
 
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: UnpackBuilder.java    From kite with Apache License 2.0 6 votes vote down vote up
private boolean parseEntry(ArchiveInputStream archive, ArchiveEntry entry, EmbeddedExtractor extractor, Record record) {
  String name = entry.getName();
  if (archive.canReadEntryData(entry)) {
    Record entrydata = new Record(); // TODO: or pass myself?
    //Record entrydata = record.copy();
    
    // For detectors to work, we need a mark/reset supporting
    // InputStream, which ArchiveInputStream isn't, so wrap
    TemporaryResources tmp = new TemporaryResources();
    try {
      TikaInputStream tis = TikaInputStream.get(archive, tmp);
      return extractor.parseEmbedded(tis, entrydata, name, getChild());
    } finally {
      try {
        tmp.dispose();
      } catch (TikaException e) {
        LOG.warn("Cannot dispose of tmp Tika resources", e);
      }
    }
  } else {
    return false;
  } 
}
 
Example #21
Source File: PyPiInfoUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Processes the entries in an archive, attempting to extract metadata. The first possible metadata file found wins.
 */
private static Map<String, String> processArchiveEntries(final ArchiveInputStream ais) throws Exception {
  checkNotNull(ais);
  ArchiveEntry entry = ais.getNextEntry();
  while (entry != null) {
    if (isMetadataFile(entry)) {
      Map<String, String> results = new LinkedHashMap<>();
      for (Entry<String, List<String>> attribute : parsePackageInfo(ais).entrySet()) {
        results.put(attribute.getKey(), String.join("\n", attribute.getValue()));
      }
      return results;
    }
    entry = ais.getNextEntry();
  }
  return new LinkedHashMap<>();
}
 
Example #22
Source File: WorkspaceTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void assertEntry(File file, String name) {
    boolean exist = false;

    try (TarArchiveInputStream tar = new TarArchiveInputStream(
            new GzipCompressorInputStream(
                            new FileInputStream(file)))) {


        ArchiveEntry entry;
        while ((entry = tar.getNextEntry()) != null) {
            if (entry.getName().equals(name)) {
                exist = true;
                break;
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    if (!exist) {
        fail("zip entry " + name + " not exist!");
    }

}
 
Example #23
Source File: EntityImportExport.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) {
    String json = entitySerialization.toJson(entities, null, EntitySerializationOption.COMPACT_REPEATED_ENTITIES);
    byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.STORED);
    zipOutputStream.setEncoding(StandardCharsets.UTF_8.name());
    ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes);
    try {
        zipOutputStream.putArchiveEntry(singleDesignEntry);
        zipOutputStream.write(jsonBytes);
        zipOutputStream.closeArchiveEntry();
    } catch (Exception e) {
        throw new RuntimeException("Error on creating zip archive during entities export", e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}
 
Example #24
Source File: GzipExtractor.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
byte[] readArtifactContext(Path input) {
    try (InputStream in = Files.newInputStream(getDeflatedFile(input));
         TarArchiveInputStream tarIn = new TarArchiveInputStream(in)) {
        ArchiveEntry entry = tarIn.getNextEntry();
        while (entry != null) {
            if (ARTIFACT_CONTEXT.equals(entry.getName())) {
                byte[] data = new byte[(int) entry.getSize()];
                tarIn.read(data, 0, data.length);
                return data;
            }
            entry = tarIn.getNextEntry();
        }
    } catch (IOException e) {
        LOG.warn("[{} - {}]: Error extracting tar  {}.", request.getLogName(), request.getId(), e.getMessage());
        throw new IllegalStateException(e);
    }
    LOG.error("Missing artifact_context.xml in {}", input);
    throw new IllegalStateException("Missing artifact_context.xml in " + input.toString());
}
 
Example #25
Source File: Utils.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Extract an entry of the input stream into a given folder
 * @param entry
 * @param tar
 * @param folder
 * @throws IOException
 */
public static void extractEntry(ArchiveEntry entry, InputStream tar, String folder) throws IOException {
    final int bufferSize = 4096;
    final String path = folder + entry.getName();
    if (entry.isDirectory()) {
        new File(path).mkdirs();
    } else {
        int count;
        byte[] data = new byte[bufferSize];
        // @formatter:off
        try (FileOutputStream os = new FileOutputStream(path); 
            BufferedOutputStream dest = new BufferedOutputStream(os, bufferSize)) {
       // @formatter:off
            while ((count = tar.read(data, 0, bufferSize)) != -1) {
                dest.write(data, 0, count);
            }
        }
    }
}
 
Example #26
Source File: PressUtility.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public static void decompressZip(File fromFile, File toDirectory) {
	try (FileInputStream fileInputStream = new FileInputStream(fromFile); ZipArchiveInputStream archiveInputStream = new ZipArchiveInputStream(fileInputStream)) {
		byte[] buffer = new byte[BUFFER_SIZE];
		ArchiveEntry archiveEntry;
		while (null != (archiveEntry = archiveInputStream.getNextEntry())) {
			File file = new File(toDirectory, archiveEntry.getName());
			try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
				int length = -1;
				while ((length = archiveInputStream.read(buffer)) != -1) {
					fileOutputStream.write(buffer, 0, length);
				}
				fileOutputStream.flush();
			}
		}
	} catch (IOException exception) {
		throw new IllegalStateException("解压ZIP异常:", exception);
	}
}
 
Example #27
Source File: SimpleTest.java    From allure-teamcity with Apache License 2.0 5 votes vote down vote up
private static void zipViaApacheCompress(Path archive, Path base, List<Path> files) throws IOException {
    try (ArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(archive.toFile()))) {
        for (Path file : files) {
            String entryName = base.toAbsolutePath().relativize(file).toString();
            ArchiveEntry entry = output.createArchiveEntry(file.toFile(), entryName);
            output.putArchiveEntry(entry);
            try (InputStream i = Files.newInputStream(file)) {
                IOUtils.copy(i, output);
            }
            output.closeArchiveEntry();
        }
        output.finish();
    }
}
 
Example #28
Source File: ArchiveFileTree.java    From gradle-plugins with MIT License 5 votes vote down vote up
@Override
public void visit(FileVisitor visitor) {
    if (!archiveFile.exists()) {
        throw new InvalidUserDataException(String.format("Cannot expand %s as it does not exist.", getDisplayName()));
    }
    if (!archiveFile.isFile()) {
        throw new InvalidUserDataException(String.format("Cannot expand %s as it is not a file.", getDisplayName()));
    }

    AtomicBoolean stopFlag = new AtomicBoolean();

    try {
        IS archiveInputStream = inputStreamProvider.openFile(archiveFile);
        try {
            ArchiveEntry archiveEntry;

            while (!stopFlag.get() && (archiveEntry = archiveInputStream.getNextEntry()) != null) {
                ArchiveEntryFileTreeElement details = createDetails(chmod);
                details.archiveInputStream = archiveInputStream;
                details.archiveEntry = (E) archiveEntry;
                details.stopFlag = stopFlag;

                try {
                    if (archiveEntry.isDirectory()) {
                        visitor.visitDir(details);
                    }
                    else {
                        visitor.visitFile(details);
                    }
                } finally {
                    details.close();
                }
            }
        } finally {
            archiveInputStream.close();
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e);
    }
}
 
Example #29
Source File: ArchiveFileTree.java    From gradle-plugins with MIT License 5 votes vote down vote up
@Override
@SneakyThrows(IOException.class)
public InputStream open() {
    if (!closed && !inputStreamUsed) {
        // We are still visiting this FTE, so we can use the overall ArchiveInputStream
        return new ArchiveEntryInputStream(this);
    }
    // We already used the the overall ArchiveInputStream or it has moved to another entry
    // so we have to open a new InputStream

    // If getFile() was called before, we can use the file to open a new InputStream.
    if (file != null && file.exists()) {
        return new FileInputStream(file);
    }

    // As last resort: Reopen the Archive and skip forward to our ArchiveEntry
    try {
        IS archiveInputStream = inputStreamProvider.openFile(archiveFile);

        ArchiveEntry tmp;

        while ((tmp = archiveInputStream.getNextEntry()) != null) {
            if (tmp.equals(archiveEntry)) {
                return archiveInputStream;
            }
        }

        throw new IOException(archiveEntry.getName() + " not found in " + archiveFile);

    } catch (ArchiveException e) {
        throw new IOException(e);
    }
}
 
Example #30
Source File: NpmPackageParser.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the actual parsing of the package.json file if it exists.
 */
private Map<String, Object> parsePackageJsonInternal(final ArchiveInputStream archiveInputStream)
    throws IOException
{
  ArchiveEntry entry = archiveInputStream.getNextEntry();
  while (entry != null) {
    if (isPackageJson(entry)) {
      return NpmJsonUtils.parse(() -> archiveInputStream).backing();
    }
    entry = archiveInputStream.getNextEntry();
  }
  return emptyMap();
}