Java Code Examples for org.apache.commons.compress.archivers.ArchiveInputStream#getNextEntry()

The following examples show how to use org.apache.commons.compress.archivers.ArchiveInputStream#getNextEntry() . 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: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static void makeOnlyUnZip() throws ArchiveException, IOException{
		final InputStream is = new FileInputStream("D:/中文名字.zip");
		ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);
		ZipArchiveEntry entry = entry = (ZipArchiveEntry) in.getNextEntry();
		
		String dir = "D:/cnname";
		File filedir = new File(dir);
		if(!filedir.exists()){
			filedir.mkdir();
		}
//		OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
		OutputStream out = new FileOutputStream(new File(filedir, entry.getName()));
		IOUtils.copy(in, out);
		out.close();
		in.close();
	}
 
Example 2
Source File: ZipTest.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
public void testApache() throws IOException, ArchiveException {
	log.debug("testApache()");
	File zip = File.createTempFile("apache_", ".zip");
	
	// Create zip
	FileOutputStream fos = new FileOutputStream(zip);
	ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("zip", fos);
	aos.putArchiveEntry(new ZipArchiveEntry("coñeta"));
	aos.closeArchiveEntry();
	aos.close();
	
	// Read zip
	FileInputStream fis = new FileInputStream(zip);
	ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream("zip", fis);
	ZipArchiveEntry zae = (ZipArchiveEntry) ais.getNextEntry();
	assertEquals(zae.getName(), "coñeta");
	ais.close();
}
 
Example 3
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 4
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 5
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 6
Source File: PdpProcessor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public AssemblyTemplate registerPdpFromArchive(InputStream archiveInput) {
    try {
        ArchiveInputStream input = new ArchiveStreamFactory()
            .createArchiveInputStream(archiveInput);
        
        while (true) {
            ArchiveEntry entry = input.getNextEntry();
            if (entry==null) break;
            // TODO unpack entry, create a space on disk holding the archive ?
        }

        // use yaml...
        throw new UnsupportedOperationException("in progress");
        
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 7
Source File: ModelExtractor.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
/**
 * Traverses the Archive to find either an entry that matches the modelFileNameInArchive name (if not empty) or
 * and entry that ends in .pb if the modelFileNameInArchive is empty.
 *
 * @param modelFileNameInArchive Optional name of the archive entry that represents the frozen model file. If empty
 *                               the archive will be searched for the first entry that ends in .pb
 * @param archive Archive stream to be traversed
 * @return
 * @throws IOException
 */
private byte[] findInArchiveStream(String modelFileNameInArchive, ArchiveInputStream archive) throws IOException {
	ArchiveEntry entry;
	while ((entry = archive.getNextEntry()) != null) {
		//System.out.println(entry.getName() + " : " + entry.isDirectory());

		if (archive.canReadEntryData(entry) && !entry.isDirectory()) {
			if ((StringUtils.hasText(modelFileNameInArchive) && entry.getName().endsWith(modelFileNameInArchive)) ||
					(!StringUtils.hasText(modelFileNameInArchive) && entry.getName().endsWith(this.frozenGraphFileExtension))) {
				return StreamUtils.copyToByteArray(archive);
			}
		}
	}
	throw new IllegalArgumentException("No model is found in the archive");
}
 
Example 8
Source File: CompressedFileReference.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void decompress(ArchiveInputStream archiveInputStream, File outputFile) throws IOException {
    int entries = 0;
    ArchiveEntry entry;
    while ((entry = archiveInputStream.getNextEntry()) != null) {
        File outFile = new File(outputFile, entry.getName());
        if (entry.isDirectory()) {
            if (!(outFile.exists() && outFile.isDirectory())) {
                log.log(Level.FINE, () -> "Creating dir: " + outFile.getAbsolutePath());
                if (!outFile.mkdirs()) {
                    log.log(Level.WARNING, "Could not create dir " + entry.getName());
                }
            }
        } else {
            // Create parent dir if necessary
            File parent = new File(outFile.getParent());
            if (!parent.exists() && !parent.mkdirs()) {
                log.log(Level.WARNING, "Could not create dir " + parent.getAbsolutePath());
            }
            FileOutputStream fos = new FileOutputStream(outFile);
            ByteStreams.copy(archiveInputStream, fos);
            fos.close();
        }
        entries++;
    }
    if (entries == 0) {
        throw new IllegalArgumentException("Not able to read any entries from stream (" +
                                                   archiveInputStream.getBytesRead() + " bytes read from stream)");
    }
}
 
Example 9
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();
}
 
Example 10
Source File: ArchiveUtils.java    From dropwizard-debpkg-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static void extractArchive(ArchiveInputStream in, File destination) throws IOException {
    for (ArchiveEntry entry; (entry = in.getNextEntry()) != null; ) {
        final File target = new File(destination, entry.getName());
        if (entry.isDirectory()) {
            target.mkdir();
        }
        else {
            Files.asByteSink(target).writeFrom(in);
        }
    }
}
 
Example 11
Source File: ArchiveExtractor.java    From carbon-kernel with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the file and create directories accordingly.
 *
 * @param is        pass the stream, because the stream is different for various file types
 * @param targetDir target directory
 * @throws IOException
 */
private static void extract(ArchiveInputStream is, File targetDir) throws IOException {
    try {
        if (targetDir.exists()) {
            FileUtils.forceDelete(targetDir);
        }
        createDirectory(targetDir);
        ArchiveEntry entry = is.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            name = name.substring(name.indexOf("/") + 1);
            File file = new File(targetDir, name);
            if (entry.isDirectory()) {
                createDirectory(file);
            } else {
                createDirectory(file.getParentFile());
                OutputStream os = new FileOutputStream(file);
                try {
                    IOUtils.copy(is, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
            entry = is.getNextEntry();
        }
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            logger.warn("Error occurred while closing the stream", e);
        }
    }
}
 
Example 12
Source File: CommonsArchiver.java    From jarchivelib with Apache License 2.0 5 votes vote down vote up
private void extract(ArchiveInputStream input, File destination) throws IOException {
    ArchiveEntry entry;
    while ((entry = input.getNextEntry()) != null) {
        File file = new File(destination, entry.getName());

        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            file.getParentFile().mkdirs();
            IOUtils.copy(input, file);
        }

        FileModeMapper.map(entry, file);
    }
}
 
Example 13
Source File: FilesDecompressUnarchiveBatchController.java    From MyBox with Apache License 2.0 4 votes vote down vote up
protected void unarchive(ArchiveInputStream archiveInputStream) {
    try {
        if (archiveInputStream == null) {
            return;
        }
        ArchiveEntry entry;
        while ((entry = archiveInputStream.getNextEntry()) != null) {
            if (verboseCheck == null || verboseCheck.isSelected()) {
                updateLogs(message("Handling...") + ":   " + entry.getName());
            }
            if (!archiveInputStream.canReadEntryData(entry)) {
                archiveFail++;
                if (verboseCheck == null || verboseCheck.isSelected()) {
                    updateLogs(message("CanNotReadEntryData" + ":" + entry.getName()));
                }
                continue;
            }
            if (!entry.isDirectory()) {
                File file = makeTargetFile(entry.getName(), targetPath);
                if (file == null) {
                    continue;
                }
                File parent = file.getParentFile();
                if (!parent.isDirectory() && !parent.mkdirs()) {
                    archiveFail++;
                    if (verboseCheck == null || verboseCheck.isSelected()) {
                        updateLogs(message("FailOpenFile" + ":" + file));
                    }
                }
                try ( OutputStream o = Files.newOutputStream(file.toPath())) {
                    IOUtils.copy(archiveInputStream, o);
                }
                archiveSuccess++;
                targetFileGenerated(file);
            }
        }
    } catch (Exception e) {
        archiveFail++;
        String s = e.toString();
        updateLogs(s);
        if (s.contains("java.nio.charset.MalformedInputException")
                || s.contains("Illegal char")) {
            updateLogs(message("CharsetIncorrect"));
            charsetIncorrect = true;
        }
    }
}
 
Example 14
Source File: ArchiveUtil.java    From lrkFM with MIT License 4 votes vote down vote up
private Handler<FMFile> getArchiveExtractionCallback(String path, AtomicBoolean result, FileType fileType) {
    return fi -> {
        try (InputStream is = new FileInputStream(fi.getFile())) {

            ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(fileType.getExtension(), is);
            ZipEntry entry;

            while ((entry = (ZipArchiveEntry) ais.getNextEntry()) != null) {

                if (entry.getName().endsWith("/")) {
                    File dir = new File(path + File.separator + entry.getName());
                    if (!dir.exists()) {
                        //noinspection ResultOfMethodCallIgnored
                        dir.mkdirs();
                    }
                    continue;
                }

                File outFile = new File(path + File.separator + entry.getName());

                if (outFile.isDirectory()) {
                    continue;
                }

                if (outFile.exists()) {
                    continue;
                }

                try (FileOutputStream out = new FileOutputStream(outFile)) {
                    byte[] buffer = new byte[1024];
                    //noinspection UnusedAssignment
                    int length = 0;
                    while ((length = ais.read(buffer)) > 0) {
                        out.write(buffer, 0, length);
                        out.flush();
                    }
                }

                result.set(true);
            }
        } catch (IOException | ArchiveException e) {
            Log.e(TAG, "Error extracting " + fileType.getExtension(), e);
            result.set(false);
        }

    };
}
 
Example 15
Source File: UnZip.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void unCompress (String zip_file, String output_folder)
      throws IOException, CompressorException, ArchiveException
{
   ArchiveInputStream ais = null;
   ArchiveStreamFactory asf = new ArchiveStreamFactory ();

   FileInputStream fis = new FileInputStream (new File (zip_file));

   if (zip_file.toLowerCase ().endsWith (".tar"))
   {
      ais = asf.createArchiveInputStream (
            ArchiveStreamFactory.TAR, fis);
   }
   else if (zip_file.toLowerCase ().endsWith (".zip"))
   {
      ais = asf.createArchiveInputStream (
            ArchiveStreamFactory.ZIP, fis);
   }
   else if (zip_file.toLowerCase ().endsWith (".tgz") ||
         zip_file.toLowerCase ().endsWith (".tar.gz"))
   {
      CompressorInputStream cis = new CompressorStreamFactory ().
            createCompressorInputStream (CompressorStreamFactory.GZIP, fis);
      ais = asf.createArchiveInputStream (new BufferedInputStream (cis));
   }
   else
   {
      try
      {
         fis.close ();
      }
      catch (IOException e)
      {
         LOGGER.warn ("Cannot close FileInputStream:", e);
      }
      throw new IllegalArgumentException (
            "Format not supported: " + zip_file);
   }

   File output_file = new File (output_folder);
   if (!output_file.exists ()) output_file.mkdirs ();

   // copy the existing entries
   ArchiveEntry nextEntry;
   while ((nextEntry = ais.getNextEntry ()) != null)
   {
      File ftemp = new File (output_folder, nextEntry.getName ());
      if (nextEntry.isDirectory ())
      {
         ftemp.mkdir ();
      }
      else
      {
         FileOutputStream fos = FileUtils.openOutputStream (ftemp);
         IOUtils.copy (ais, fos);
         fos.close ();
      }
   }
   ais.close ();
   fis.close ();
}