Java Code Examples for org.apache.commons.compress.archivers.zip.ZipArchiveEntry#isDirectory()

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipArchiveEntry#isDirectory() . 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: ArchiveUtils.java    From gradle-golang-plugin with Mozilla Public License 2.0 6 votes vote down vote up
public static void unZip(Path file, Path target) throws IOException {
    try (final ZipFile zipFile = new ZipFile(file.toFile())) {
        final Enumeration<ZipArchiveEntry> files = zipFile.getEntriesInPhysicalOrder();
        while (files.hasMoreElements()) {
            final ZipArchiveEntry entry = files.nextElement();
            final Path entryFile = target.resolve(REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).toAbsolutePath();
            if (entry.isDirectory()) {
                createDirectoriesIfRequired(entryFile);
            } else {
                ensureParentOf(entryFile);
                try (final InputStream is = zipFile.getInputStream(entry)) {
                    try (final OutputStream os = newOutputStream(entryFile)) {
                        copy(is, os);
                    }
                }
            }
        }
    }
}
 
Example 2
Source File: ScrubService.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
public Vector<TaskEntry> collectZipEntries(String filename, String scrubDir) {
    Vector<TaskEntry> archiveEntries = new Vector<>();
    try {
        ZipFile zf = new ZipFile(new File(filename));
        Enumeration<ZipArchiveEntry> entries = zf.getEntries();
        ZipArchiveEntry ent = entries.nextElement();
        String archiveName = ent.getName();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zae = entries.nextElement();
            TaskEntry te = new ZipFileTaskEntry(zf, zae, archiveName);
            if(zae.isDirectory()){
                new File(scrubDir + SystemProperties.fileSeparator + te.entryName()).mkdir();
            }
            else{
                archiveEntries.add(te);
            }
        }
    } catch (IOException e) {
        logger.error(Constants.CONSOLE, "Error obtaining zip file entries");
        logger.error(e);
    }

    return archiveEntries;

}
 
Example 3
Source File: Assembler.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given file in the ZIP file. If the given file is a directory, then this method
 * recursively adds all files contained in this directory. This method is invoked for zipping
 * the "application/sis-console/src/main/artifact" directory and sub-directories before to zip.
 */
private void appendRecursively(final File file, String relativeFile, final ZipArchiveOutputStream out) throws IOException {
    if (file.isDirectory()) {
        relativeFile += '/';
    }
    final ZipArchiveEntry entry = new ZipArchiveEntry(file, relativeFile);
    if (file.canExecute()) {
        entry.setUnixMode(0744);
    }
    out.putArchiveEntry(entry);
    if (!entry.isDirectory()) {
        try (FileInputStream in = new FileInputStream(file)) {
            in.transferTo(out);
        }
    }
    out.closeArchiveEntry();
    if (entry.isDirectory()) {
        for (final String filename : file.list(this)) {
            appendRecursively(new File(file, filename), relativeFile.concat(filename), out);
        }
    }
}
 
Example 4
Source File: AbstractInitializrIntegrationTests.java    From initializr with Apache License 2.0 6 votes vote down vote up
private void unzip(Path archiveFile, Path project) throws IOException {
	try (ZipFile zip = new ZipFile(archiveFile.toFile())) {
		Enumeration<? extends ZipArchiveEntry> entries = zip.getEntries();
		while (entries.hasMoreElements()) {
			ZipArchiveEntry entry = entries.nextElement();
			Path path = project.resolve(entry.getName());
			if (entry.isDirectory()) {
				Files.createDirectories(path);
			}
			else {
				Files.createDirectories(path.getParent());
				Files.write(path, StreamUtils.copyToByteArray(zip.getInputStream(entry)));
			}
			applyPermissions(path, getPosixFilePermissions(entry.getUnixMode()));
		}
	}
}
 
Example 5
Source File: ZipUtils.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
private void unzipEntry(final ZipFile zipfile, final ZipArchiveEntry entry, final File outputDir) throws IOException {

        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }

        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }

        try (BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
             BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
            IOUtils.copy(inputStream, outputStream);
        }
    }
 
Example 6
Source File: BasicExtractor.java    From embedded-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void extractZip(ZipFile zipFile) {
  Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();
    String fileName = entry.getName();
    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {
      makeDirectory(outputFile);
    } else {
      createNewFile(outputFile);
      try {
        InputStream inputStream = zipFile.getInputStream(entry);
        extractFile(inputStream, outputFile, fileName);
      } catch (IOException e) {
        throw new ExtractionException("Error extracting file '" + fileName + "' "
            + "from downloaded file: " + config.getDownloadTarget(), e);
      }
    }
  }
}
 
Example 7
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 把一个ZIP文件解压到一个指定的目录中
 * @param zipfilename ZIP文件抽象地址
 * @param outputdir 目录绝对地址
 */
public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {
    File zipfile = new File(zipfilename);
    if (zipfile.exists()) {
        outputdir = outputdir + File.separator;
        FileUtils.forceMkdir(new File(outputdir));

        ZipFile zf = new ZipFile(zipfile, "UTF-8");
        Enumeration zipArchiveEntrys = zf.getEntries();
        while (zipArchiveEntrys.hasMoreElements()) {
            ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
            if (zipArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));
            } else {
                IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));
            }
        }
    } else {
        throw new IOException("指定的解压文件不存在:\t" + zipfilename);
    }
}
 
Example 8
Source File: ZipUtils.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
public static Path unzipToTemporaryDirectory(File file) throws IOException {
    File tempDirectory = new File("/tmp/" + UUID.nameUUIDFromBytes(file.getName().getBytes()).toString());
    if (!tempDirectory.exists()) {
        tempDirectory.mkdir();
        ZipFile zipFile = new ZipFile(file);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            if (!entry.isDirectory()) {
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(entry), new File(Paths.get(tempDirectory.toString(), "/" + entry.getName()).toString()));
            }
        }
        zipFile.close();
    }
    return tempDirectory.toPath();
}
 
Example 9
Source File: DocxFile.java    From wechattool with MIT License 5 votes vote down vote up
private void copyZipFile() throws IOException {
    Enumeration<ZipArchiveEntry> entries = in.getEntries();
    ZipArchiveEntry e;
    ZipArchiveEntry e1;
    while(entries.hasMoreElements()){
        e1 = entries.nextElement();
        outfile.putArchiveEntry(e1);

        if (!e1.isDirectory()) {
            copy(in.getInputStream(e1), outfile);
        }
        outfile.closeArchiveEntry();
    }
}
 
Example 10
Source File: ZipUtils.java    From youtubedl-android with GNU General Public License v3.0 5 votes vote down vote up
public static void unzip(File sourceFile, File targetDirectory) throws IOException, ErrnoException, IllegalAccessException {
    try (ZipFile zipFile = new ZipFile(sourceFile)) {
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File entryDestination = new File(targetDirectory, entry.getName());
            // prevent zipSlip
            if (!entryDestination.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator)) {
                throw new IllegalAccessException("Entry is outside of the target dir: " + entry.getName());
            }
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else if (entry.isUnixSymlink()) {
                try (InputStream in = zipFile.getInputStream(entry)) {
                    String symlink = IOUtils.toString(in, StandardCharsets.UTF_8);
                    Os.symlink(symlink, entryDestination.getAbsolutePath());
                }
            } else {
                entryDestination.getParentFile().mkdirs();
                try (InputStream in = zipFile.getInputStream(entry);
                     OutputStream out = new FileOutputStream(entryDestination)) {
                    IOUtils.copy(in, out);
                }
            }
        }
    }
}
 
Example 11
Source File: MavenDownloader.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public static void unzip(File zipFile, File destination)
        throws IOException {
    ZipFile zip = new ZipFile(zipFile);
    try {
        Enumeration<ZipArchiveEntry> e = zip.getEntries();
        while (e.hasMoreElements()) {
            ZipArchiveEntry entry = e.nextElement();
            File file = new File(destination, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = zip.getInputStream(entry);
                File parent = file.getParentFile();
                if (parent != null && parent.exists() == false) {
                    parent.mkdirs();
                }
                FileOutputStream os = new FileOutputStream(file);
                try {
                    IOUtils.copy(is, os);
                } finally {
                    os.close();
                    is.close();
                }
                file.setLastModified(entry.getTime());
                int mode = entry.getUnixMode();
                if ((mode & EXEC_MASK) != 0) {
                    if (!file.setExecutable(true)) {
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zip);
    }
}
 
Example 12
Source File: Zip.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private File unzipEntry(ZipFile zipFile, ZipArchiveEntry entry, Path targetDirectory,
        Consumer<ZipExtractionResult> unzipCallback) {
    final String fileName = entry.getName();
    final long compressedSize = entry.getCompressedSize();

    final Path targetPath = targetDirectory.resolve(fileName);
    try {
        if (entry.isDirectory()) {
            LOGGER.info(String.format("Attempting to create output directory %s.", targetPath.toString()));

            Files.createDirectories(targetPath);
        } else {
            Files.createDirectories(targetPath.getParent());

            try (InputStream in = zipFile.getInputStream(entry)) {
                LOGGER.info(String.format("Creating output file %s.", targetPath.toString()));

                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);

                // update progress bar
                unzipCallback.accept(new ZipExtractionResult(compressedSize, fileName));
            }
        }

        return targetPath.toFile();
    } catch (IOException e) {
        throw new ArchiveException(String.format("Unable to extract file \"%s\"", fileName), e);
    }
}
 
Example 13
Source File: ZipReader.java    From kkFileView with Apache License 2.0 4 votes vote down vote up
public String readZipFile(String filePath,String fileKey) {
    String archiveSeparator = "/";
    Map<String, FileNode> appender = Maps.newHashMap();
    List<String> imgUrls = Lists.newArrayList();
    String baseUrl = BaseUrlFilter.getBaseUrl();
    String archiveFileName = fileUtils.getFileNameFromPath(filePath);
    try {
        ZipFile zipFile = new ZipFile(filePath, fileUtils.getFileEncodeUTFGBK(filePath));
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        // 排序
        entries = sortZipEntries(entries);
        List<Map<String, ZipArchiveEntry>> entriesToBeExtracted = Lists.newArrayList();
        while (entries.hasMoreElements()){
            ZipArchiveEntry entry = entries.nextElement();
            String fullName = entry.getName();
            int level = fullName.split(archiveSeparator).length;
            // 展示名
            String originName = getLastFileName(fullName, archiveSeparator);
            String childName = level + "_" + originName;
            boolean directory = entry.isDirectory();
            if (!directory) {
                childName = archiveFileName + "_" + originName;
                entriesToBeExtracted.add(Collections.singletonMap(childName, entry));
            }
            String parentName = getLast2FileName(fullName, archiveSeparator, archiveFileName);
            parentName = (level-1) + "_" + parentName;
            FileType type=fileUtils.typeFromUrl(childName);
            if (type.equals(FileType.picture)){//添加图片文件到图片列表
                imgUrls.add(baseUrl+childName);
            }
            FileNode node = new FileNode(originName, childName, parentName, new ArrayList<>(), directory, fileKey);
            addNodes(appender, parentName, node);
            appender.put(childName, node);
        }
        // 开启新的线程处理文件解压
        executors.submit(new ZipExtractorWorker(entriesToBeExtracted, zipFile, filePath));
        fileUtils.putImgCache(fileKey,imgUrls);
        return new ObjectMapper().writeValueAsString(appender.get(""));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 14
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
private void extractZip( String zipFilePath, String outputDirPath ) {

        ZipArchiveEntry zipEntry = null;
        File outputDir = new File(outputDirPath);
        outputDir.mkdirs();//check if the dir is created

        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
            int unixPermissions = 0;

            while (entries.hasMoreElements()) {
                zipEntry = entries.nextElement();
                if (log.isDebugEnabled()) {
                    log.debug("Extracting " + zipEntry.getName());
                }
                File entryDestination = new File(outputDirPath, zipEntry.getName());

                unixPermissions = zipEntry.getUnixMode();
                if (zipEntry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = null;
                    OutputStream out = null;

                    in = zipFile.getInputStream(zipEntry);
                    out = new BufferedOutputStream(new FileOutputStream(entryDestination));

                    IoUtils.copyStream(in, out);
                }
                if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                    // set file/dir permissions, after it is created
                    Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                                  getPosixFilePermission(unixPermissions));
                }
            }
        } catch (Exception e) {
            String errorMsg = "Unable to unzip " + ((zipEntry != null)
                                                    ? zipEntry.getName() + " from "
                                                    : "")
                              + zipFilePath + ".Target directory '" + outputDirPath
                              + "' is in inconsistent state.";
            throw new FileSystemOperationException(errorMsg, e);
        }

    }
 
Example 15
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Unzip file to local or remote machine. If the machine is UNIX-like it will preserve the permissions
 *
 * @param zipFilePath the zip file path
 * @param outputDirPath output directory. The directory will be created if it does not exist
 * @throws FileSystemOperationException
 */
@Deprecated
@Override
public void unzip(
        String zipFilePath,
        String outputDirPath ) throws FileSystemOperationException {

    ZipArchiveEntry zipEntry = null;
    File outputDir = new File(outputDirPath);
    outputDir.mkdirs();//check if the dir is created

    try (ZipFile zipFile = new ZipFile(zipFilePath)) {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        int unixPermissions = 0;

        while (entries.hasMoreElements()) {
            zipEntry = entries.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("Extracting " + zipEntry.getName());
            }
            File entryDestination = new File(outputDirPath, zipEntry.getName());

            unixPermissions = zipEntry.getUnixMode();
            if (zipEntry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = null;
                OutputStream out = null;

                in = zipFile.getInputStream(zipEntry);
                out = new BufferedOutputStream(new FileOutputStream(entryDestination));

                IoUtils.copyStream(in, out);
            }
            if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                // set file/dir permissions, after it is created
                Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                              getPosixFilePermission(unixPermissions));
            }
        }
    } catch (Exception e) {
        String errorMsg = "Unable to unzip " + ((zipEntry != null)
                                                ? zipEntry.getName() + " from "
                                                : "")
                          + zipFilePath + ".Target directory '" + outputDirPath
                          + "' is in inconsistent state.";
        throw new FileSystemOperationException(errorMsg, e);
    }
}
 
Example 16
Source File: ZipExtractorProvider.java    From appengine-plugins-core with Apache License 2.0 4 votes vote down vote up
@Override
public void extract(Path archive, Path destination, ProgressListener progressListener)
    throws IOException {

  progressListener.start(
      "Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

  String canonicalDestination = destination.toFile().getCanonicalPath();

  // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
  // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
  // all the zip file data and will return "0" for any call to getUnixMode().
  try (ZipFile zipFile = new ZipFile(archive.toFile())) {
    // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
    Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
    while (zipEntries.hasMoreElements()) {
      ZipArchiveEntry entry = zipEntries.nextElement();
      Path entryTarget = destination.resolve(entry.getName());

      String canonicalTarget = entryTarget.toFile().getCanonicalPath();
      if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
        throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
      }

      progressListener.update(1);
      logger.fine(entryTarget.toString());

      if (entry.isDirectory()) {
        if (!Files.exists(entryTarget)) {
          Files.createDirectories(entryTarget);
        }
      } else {
        if (!Files.exists(entryTarget.getParent())) {
          Files.createDirectories(entryTarget.getParent());
        }
        try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
          try (InputStream in = zipFile.getInputStream(entry)) {
            IOUtils.copy(in, out);
            PosixFileAttributeView attributeView =
                Files.getFileAttributeView(entryTarget, PosixFileAttributeView.class);
            if (attributeView != null) {
              attributeView.setPermissions(
                  PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
            }
          }
        }
      }
    }
  }
  progressListener.done();
}
 
Example 17
Source File: FilesDecompressUnarchiveBatchController.java    From MyBox with Apache License 2.0 4 votes vote down vote up
protected void unarchiveZip(File srcFile) {
    try {
        try ( ZipFile zipFile = new ZipFile(srcFile)) {
            Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                if (entry.isDirectory()) {
                    continue;
                }
                if (verboseCheck == null || verboseCheck.isSelected()) {
                    updateLogs(message("Handling...") + ":   " + entry.getName());
                }
                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));
                    }
                    continue;
                }
                try ( FileOutputStream out = new FileOutputStream(file);
                      InputStream in = zipFile.getInputStream(entry)) {
                    IOUtils.copy(in, out);
                }
                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 18
Source File: ExtensionUtils.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Unpacks a given zip file to {@link ApplicationLayout#getExtensionInstallationDir}. The 
 * file permissions in the original zip will be retained.
 * <p>
 * Note: This method uses the Apache zip files since they keep track of permissions info; 
 * the built-in java objects (ZipEntry et al.) do not.
 * 
 * @param zipFile the zip file to unpack
 * @param monitor the task monitor
 * @throws ExtensionException if any part of the unzipping fails, or if the target location is invalid
 * @throws CancelledException if the user cancels the unzip
 * @throws IOException if error unzipping zip file
 */
private static void unzipToInstallationFolder(File zipFile, TaskMonitor monitor)
		throws ExtensionException, CancelledException, IOException {

	ApplicationLayout layout = Application.getApplicationLayout();

	if (!isZip(zipFile)) {
		throw new ExtensionException(zipFile.getAbsolutePath() + " is not a valid zip file",
			ExtensionExceptionType.ZIP_ERROR);
	}

	if (layout.getExtensionInstallationDir() == null ||
		!layout.getExtensionInstallationDir().exists()) {
		throw new ExtensionException(
			"Extension installation directory is not valid: " +
				layout.getExtensionInstallationDir(),
			ExtensionExceptionType.INVALID_INSTALL_LOCATION);
	}

	try (ZipFile zFile = new ZipFile(zipFile)) {

		Enumeration<ZipArchiveEntry> entries = zFile.getEntries();
		while (entries.hasMoreElements()) {

			ZipArchiveEntry entry = entries.nextElement();

			String filePath =
				(layout.getExtensionInstallationDir() + File.separator + entry.getName());

			File file = new File(filePath);

			if (entry.isDirectory()) {
				file.mkdirs();
			}
			else {
				try (OutputStream outputStream =
					new BufferedOutputStream(new FileOutputStream(file))) {

					// Create the file at the new location...
					IOUtils.copy(zFile.getInputStream(entry), outputStream);

					// ...and update its permissions. But only continue if the zip
					// was created on a unix platform. If not we cannot use the posix
					// libraries to set permissions. 
					if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX) {

						int mode = entry.getUnixMode();
						if (mode != 0) { // 0 indicates non-unix platform
							Set<PosixFilePermission> perms = getPermissions(mode);

							try {
								Files.setPosixFilePermissions(file.toPath(), perms);
							}
							catch (UnsupportedOperationException e) {
								// Need to catch this, as Windows does not support the
								// posix call. This is not an error, however, and should
								// just silently fail.
							}
						}
					}
				}
			}
		}
	}
}
 
Example 19
Source File: JarUtils.java    From bytecode-viewer with GNU General Public License v3.0 4 votes vote down vote up
public static void put2(final File jarFile) throws IOException
{
    //if this ever fails, worst case import Sun's jarsigner code from JDK 7 re-sign the jar to rebuild the CRC, should also rebuild the archive byte offsets

    FileContainer container = new FileContainer(jarFile);
    HashMap<String, byte[]> files = new HashMap<>();

    Path path = jarFile.toPath();

    String fileBaseName = FilenameUtils.getBaseName(path.getFileName().toString());
    Path destFolderPath = Paths.get(path.getParent().toString(), fileBaseName);

    try (ZipFile zipFile = new ZipFile(jarFile))
    {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements())
        {
            ZipArchiveEntry entry = entries.nextElement();
            Path entryPath = destFolderPath.resolve(entry.getName());
            String name = entry.getName();
            if (entry.isDirectory())
            {
                //directory
            }
            else
            {
                try (InputStream in = zipFile.getInputStream(entry))
                {
                    final byte[] bytes = getBytes(in);

                    if(!name.endsWith(".class"))
                    {
                        files.put(name, bytes);
                    }
                    else
                    {
                        String cafebabe = String.format("%02X", bytes[0]) + String.format("%02X", bytes[1]) + String.format("%02X", bytes[2]) + String.format("%02X", bytes[3]);
                        if (cafebabe.toLowerCase().equals("cafebabe"))
                        {
                            try
                            {
                                final ClassNode cn = getNode(bytes);
                                container.classes.add(cn);
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            files.put(name, bytes);
                        }
                    }

                }
            }
        }
    }

    container.files = files;
    BytecodeViewer.files.add(container);
}
 
Example 20
Source File: WRS2GeometryStore.java    From geowave with Apache License 2.0 4 votes vote down vote up
private void init() throws MalformedURLException, IOException {
  if (!wrs2Shape.exists()) {
    if (!wrs2Directory.delete()) {
      LOGGER.warn("Unable to delete '" + wrs2Directory.getAbsolutePath() + "'");
    }
    final File wsDir = wrs2Directory.getParentFile();
    if (!wsDir.exists() && !wsDir.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wsDir.getAbsolutePath() + "'");
    }

    if (!wrs2Directory.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wrs2Directory.getAbsolutePath() + "'");
    }
    // download and unzip the shapefile
    final File targetFile = new File(wrs2Directory, WRS2_SHAPE_ZIP);
    if (targetFile.exists()) {
      if (!targetFile.delete()) {
        LOGGER.warn("Unable to delete file '" + targetFile.getAbsolutePath() + "'");
      }
    }
    FileUtils.copyURLToFile(new URL(WRS2_SHAPE_URL), targetFile);
    final ZipFile zipFile = new ZipFile(targetFile);
    try {
      final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
      while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
          FileUtils.copyInputStreamToFile(
              zipFile.getInputStream(entry),
              new File(wrs2Directory, entry.getName()));
          // HP Fortify "Path Traversal" false positive
          // What Fortify considers "user input" comes only
          // from users with OS-level access anyway
        }
      }
    } finally {
      zipFile.close();
    }
  }
  // read the shapefile and cache the features for quick lookup by path
  // and row
  try {
    final Map<String, Object> map = new HashMap<>();
    map.put("url", wrs2Shape.toURI().toURL());
    final DataStore dataStore = DataStoreFinder.getDataStore(map);
    if (dataStore == null) {
      LOGGER.error("Unable to get a datastore instance, getDataStore returned null");
      return;
    }
    final SimpleFeatureSource source = dataStore.getFeatureSource(WRS2_TYPE_NAME);

    final SimpleFeatureCollection featureCollection = source.getFeatures();
    wrs2Type = featureCollection.getSchema();
    final SimpleFeatureIterator iterator = featureCollection.features();
    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();
      final Number path = (Number) feature.getAttribute("PATH");
      final Number row = (Number) feature.getAttribute("ROW");
      featureCache.put(
          new WRS2Key(path.intValue(), row.intValue()),
          (MultiPolygon) feature.getDefaultGeometry());
    }
  } catch (final IOException e) {
    LOGGER.error(
        "Unable to read wrs2_asc_desc shapefile '" + wrs2Shape.getAbsolutePath() + "'",
        e);
    throw (e);
  }
}