Java Code Examples for java.util.jar.JarFile#close()

The following examples show how to use java.util.jar.JarFile#close() . 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: TestNormal.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void compareJars(JarFile jf1, JarFile jf2) throws Exception {
    try {
        if (jf1.size() != jf2.size()) {
            throw new Exception("Jars " + jf1.getName() + " and " + jf2.getName()
                    + " have different number of entries");
        }
        for (JarEntry elem1 : Collections.list(jf1.entries())) {
            JarEntry elem2 = jf2.getJarEntry(elem1.getName());
            if (elem2 == null) {
                throw new Exception("Element " + elem1.getName() + " is missing from " + jf2.getName());
            }
            if (!elem1.isDirectory() && elem1.getCrc() != elem2.getCrc()) {
                throw new Exception("The crc of " + elem1.getName() + " is different.");
            }
        }
    } finally {
        jf1.close();
        jf2.close();
    }
}
 
Example 2
Source File: ArkPluginMojo.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
public void shadeJarIntoArkPlugin(File pluginFile, File tmpPluginFile, Set<Artifact> artifacts)
                                                                                               throws IOException {
    Set<Artifact> shadeJars = new HashSet<>();
    shadeJars.add(project.getArtifact());
    for (Artifact artifact : artifacts) {
        if (isShadeJar(artifact)) {
            shadeJars.add(artifact);
        }
    }

    JarWriter writer = new JarWriter(pluginFile);
    JarFile tmpJarFile = new JarFile(tmpPluginFile);
    try {
        writer.writeEntries(tmpJarFile);
        for (Artifact jar : shadeJars) {
            writer.writeEntries(new JarFile(jar.getFile()));
        }
    } finally {
        writer.close();
        tmpJarFile.close();
    }
}
 
Example 3
Source File: FileUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static File extractJarEntry(
        final String entry,
        final File source,
        final File target) throws IOException {
    JarFile jar = new JarFile(source);
    FileOutputStream out = new FileOutputStream(target);
    
    try {
        StreamUtils.transferData(jar.getInputStream(jar.getEntry(entry)), out);
        
        return target;
    } finally {
        jar.close();
        out.close();
    }
}
 
Example 4
Source File: PackerImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Takes a JarFile and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 *
 * @param in  a JarFile
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarFile in, OutputStream out) throws IOException {
    assert (Utils.currentInstance.get() == null);

    boolean needUTC = !props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE);
    try {
        Utils.currentInstance.set(this);
        if (needUTC) {
            Utils.changeDefaultTimeZoneToUtc();
        }

        if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
            Utils.copyJarFile(in, out);
        } else {
            (new DoPack()).run(in, out);
        }
    } finally {
        Utils.currentInstance.set(null);
        if (needUTC) {
            Utils.restoreDefaultTimeZone();
        }
        in.close();
    }
}
 
Example 5
Source File: JarUtils.java    From zelixkiller with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a map of <String(Class name), ClassNode> for a given jar file
 * 
 * @param jarFile
 * @author Konloch (Bytecode Viewer)
 * @return
 * @throws IOException
 */
public static Map<String, ClassNode> loadClasses(File jarFile) throws IOException {
	Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
	JarFile jar = new JarFile(jarFile);
	Stream<JarEntry> str = jar.stream();
	// For some reason streaming = entries in messy jars
	// enumeration = no entries
	// Or if the jar is really big, enumeration = infinite hang
	// ...
	// Whatever. It works now!
	str.forEach(z -> readJar(jar, z, classes, null));
	jar.close();
	return classes;
}
 
Example 6
Source File: FSInfo.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public List<File> getJarClassPath(File file) throws IOException {
    String parent = file.getParent();
    JarFile jarFile = new JarFile(file);
    try {
        Manifest man = jarFile.getManifest();
        if (man == null)
            return Collections.emptyList();

        Attributes attr = man.getMainAttributes();
        if (attr == null)
            return Collections.emptyList();

        String path = attr.getValue(Attributes.Name.CLASS_PATH);
        if (path == null)
            return Collections.emptyList();

        List<File> list = new ArrayList<File>();

        for (StringTokenizer st = new StringTokenizer(path); st.hasMoreTokens(); ) {
            String elt = st.nextToken();
            File f = (parent == null ? new File(elt) : new File(parent, elt));
            list.add(f);
        }

        return list;
    } finally {
        jarFile.close();
    }
}
 
Example 7
Source File: TestFile.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Manifest getManifest() {
    assertIsFile();
    try {
        JarFile jarFile = new JarFile(this);
        try {
            return jarFile.getManifest();
        } finally {
            jarFile.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: FileUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isSigned(
        final File file) throws IOException {
    JarFile jar = new JarFile(file);

    try {
        Enumeration<JarEntry> entries = jar.entries();
        boolean signatureInfoPresent = false;
        boolean signatureFilePresent = false;
        while (entries.hasMoreElements()) {
            String entryName = entries.nextElement().getName();
            if (entryName.startsWith("META-INF/")) {
                if (entryName.endsWith(".RSA") || entryName.endsWith(".DSA")) {
                    signatureFilePresent = true;
                    if(signatureInfoPresent) {
                        break;
                    }
                } else if (entryName.endsWith(".SF")) {
                    signatureInfoPresent = true;
                    if(signatureFilePresent) {
                        break;
                    }
                }
            }
        }
        return signatureFilePresent && signatureInfoPresent;
    } finally {
        jar.close();
    }
}
 
Example 9
Source File: XenqttUtil.java    From xenqtt with Apache License 2.0 5 votes vote down vote up
private static void findFilesInJar(String jarPath, ClassPathFileListBuilder builder) throws Exception {

		JarFile jarFile = new JarFile(jarPath);
		try {
			Enumeration<JarEntry> entries = jarFile.entries();
			while (entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				builder.accept(entry.getName());
			}
		} finally {
			jarFile.close();
		}
	}
 
Example 10
Source File: Jar.java    From scar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static public void addToJAR (String inJar, String outJar, String addName, byte[] bytes, boolean overwrite) throws IOException {
	if (DEBUG) debug("scar", "Adding to JAR: " + inJar + " -> " + outJar + ", " + addName);

	JarFile inJarFile = new JarFile(inJar);
	mkdir(parent(outJar));
	JarOutputStream outJarStream = new JarOutputStream(new FileOutputStream(outJar));
	outJarStream.setLevel(Deflater.BEST_COMPRESSION);
	ArrayList<String> names = new ArrayList();
	for (Enumeration<JarEntry> entries = inJarFile.entries(); entries.hasMoreElements();)
		names.add(entries.nextElement().getName());

	addName = addName.replace('\\', '/');
	boolean exists = names.contains(addName) || names.contains(addName.replace('/', '\\'));
	if (!overwrite && exists) throw new RuntimeException("JAR already has entry: " + addName);
	if (!exists) {
		names.add(addName);
		Collections.sort(names);
	}

	if (names.remove("META-INF/MANIFEST.MF") || names.remove("META-INF\\MANIFEST.MF")) names.add(0, "META-INF/MANIFEST.MF");

	for (String name : names) {
		outJarStream.putNextEntry(new JarEntry(name.replace('\\', '/')));
		if (name.replace('\\', '/').equals(addName))
			outJarStream.write(bytes);
		else
			copyStream(inJarFile.getInputStream(inJarFile.getEntry(name)), outJarStream);
		outJarStream.closeEntry();
	}
	outJarStream.close();
	inJarFile.close();
}
 
Example 11
Source File: URLClassPath.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static JarFile checkJar(JarFile jar) throws IOException {
    if (System.getSecurityManager() != null && !DISABLE_JAR_CHECKING
        && !zipAccess.startsWithLocHeader(jar)) {
        IOException x = new IOException("Invalid Jar file");
        try {
            jar.close();
        } catch (IOException ex) {
            x.addSuppressed(ex);
        }
        throw x;
    }

    return jar;
}
 
Example 12
Source File: Utils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je : Collections.list(in.entries())) {
        out.putNextEntry(je);
        InputStream ein = in.getInputStream(je);
        for (int nr; 0 < (nr = ein.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 13
Source File: JarUtils.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
public static Map<String, ClassNode> loadRT() throws IOException {
  Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
  JarFile jar = new JarFile(getRT());
  Stream<JarEntry> str = jar.stream();
  // TODO: Make ignoring these packages optional
  str.forEach(z -> readJar(jar, z, classes, Arrays.asList("com/sun/", "com/oracle/", "jdk/", "sun/")));
  jar.close();
  return classes;
}
 
Example 14
Source File: ModulePackager.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
public static String getAdapterAlias(File jarFile) throws IOException {
    String version = null;
    JarFile jar = new JarFile(jarFile);
    Attributes attributes = jar.getManifest().getMainAttributes();
    if (attributes.containsKey(ATTR_MODULE_ALIAS)) {
        version = attributes.getValue(ATTR_MODULE_ALIAS);
    }
    jar.close();
    return version;
}
 
Example 15
Source File: IndexV1Updater.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private void processDownloadedIndex(File outputFile, String cacheTag)
        throws IOException, IndexUpdater.UpdateException {
    JarFile jarFile = new JarFile(outputFile, true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(DATA_FILE_NAME);
    InputStream indexInputStream = new ProgressBufferedInputStream(jarFile.getInputStream(indexEntry),
            processIndexListener, (int) indexEntry.getSize());
    processIndexV1(indexInputStream, indexEntry, cacheTag);
    jarFile.close();
}
 
Example 16
Source File: WLPluginProperties.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Version getServerVersion(File serverRoot) {
    File weblogicJar = WebLogicLayout.getWeblogicJar(serverRoot);
    if (!weblogicJar.exists()) {
        return null;
    }
    try {
        // JarInputStream cannot be used due to problem in weblogic.jar in Oracle Weblogic Server 10.3
        JarFile jar = new JarFile(weblogicJar);
        try {
            Manifest manifest = jar.getManifest();
            String implementationVersion = null;
            if (manifest != null) {
                implementationVersion = manifest.getMainAttributes()
                        .getValue("Implementation-Version"); // NOI18N
            }
            if (implementationVersion != null) { // NOI18N
                implementationVersion = implementationVersion.trim();
                return Version.fromJsr277OrDottedNotationWithFallback(implementationVersion);
            }
        } finally {
            try {
                jar.close();
            } catch (IOException ex) {
                LOGGER.log(Level.FINEST, null, ex);
            }
        }
    } catch (IOException e) {
        LOGGER.log(Level.FINE, null, e);
    }
    return null;
}
 
Example 17
Source File: Utils.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je : Collections.list(in.entries())) {
        out.putNextEntry(je);
        InputStream ein = in.getInputStream(je);
        for (int nr; 0 < (nr = ein.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example 18
Source File: RunJar.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Unpack matching files from a jar. Entries inside the jar that do
 * not match the given pattern will be skipped.
 *
 * @param jarFile the .jar file to unpack
 * @param toDir the destination directory into which to unpack the jar
 * @param unpackRegex the pattern to match jar entries against
 */
public static void unJar(File jarFile, File toDir, Pattern unpackRegex)
  throws IOException {
  JarFile jar = new JarFile(jarFile);
  try {
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
      final JarEntry entry = entries.nextElement();
      if (!entry.isDirectory() &&
          unpackRegex.matcher(entry.getName()).matches()) {
        InputStream in = jar.getInputStream(entry);
        try {
          File file = new File(toDir, entry.getName());
          ensureDirectory(file.getParentFile());
          OutputStream out = new FileOutputStream(file);
          try {
            IOUtils.copyBytes(in, out, 8192);
          } finally {
            out.close();
          }
        } finally {
          in.close();
        }
      }
    }
  } finally {
    jar.close();
  }
}
 
Example 19
Source File: JarUtils.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a map of <String(Class name), ClassNode> for a given jar file
 * 
 * @param jarFile
 * @author Konloch (Bytecode Viewer)
 * @return
 * @throws IOException
 */
public static Map<String, ClassNode> loadClasses(File jarFile) throws IOException {
  Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
  JarFile jar = new JarFile(jarFile);
  Stream<JarEntry> str = jar.stream();
  // For some reason streaming = entries in messy jars
  // enumeration = no entries
  // Or if the jar is really big, enumeration = infinite hang
  // ...
  // Whatever. It works now!
  str.forEach(z -> readJar(jar, z, classes, null));
  jar.close();
  return classes;
}
 
Example 20
Source File: DefaultJarContentHasherTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetContentHashesDoesNotIncorrectlyCache() throws Exception {
  if (Platform.isWindows()) {
    // Windows doesn't allow clobbering a file while it's already open, so this test isn't
    // meaningful for windows platforms
    return;
  }
  ProjectFilesystem filesystem =
      TestProjectFilesystems.createProjectFilesystem(temporaryFolder.getRoot().toPath());
  File toTest = temporaryFolder.newFile();
  File modification = temporaryFolder.newFile();
  new JarBuilder()
      .setShouldHashEntries(true)
      .addEntry(
          new JarEntrySupplier(
              new CustomZipEntry("Before"),
              "container_test",
              () -> new ByteArrayInputStream("Before".getBytes(StandardCharsets.UTF_8))))
      .createJarFile(toTest.toPath());
  new JarBuilder()
      .setShouldHashEntries(true)
      .addEntry(
          new JarEntrySupplier(
              new CustomZipEntry("After"),
              "container_test",
              () -> new ByteArrayInputStream("After".getBytes(StandardCharsets.UTF_8))))
      .createJarFile(modification.toPath());

  FileTime hardcodedTime = FileTime.fromMillis(ZipConstants.getFakeTime());
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);
  Files.setLastModifiedTime(modification.toPath(), hardcodedTime);

  Path relativeToTestPath = temporaryFolder.getRoot().toPath().relativize(toTest.toPath());

  // Use JarBuilder with toTest -- we cache the open file to make sure it stays mmapped
  //noinspection unused
  JarFile cache = new JarFile(toTest);
  assertThat(
      new DefaultJarContentHasher(filesystem, relativeToTestPath).getContentHashes().keySet(),
      Matchers.contains(Paths.get("Before")));

  // Now modify toTest make sure we don't get a cached result when we open it for a second time
  Files.move(modification.toPath(), toTest.toPath(), StandardCopyOption.REPLACE_EXISTING);
  Files.setLastModifiedTime(toTest.toPath(), hardcodedTime);
  assertThat(
      new DefaultJarContentHasher(filesystem, relativeToTestPath).getContentHashes().keySet(),
      Matchers.contains(Paths.get("After")));
  cache.close();
}