java.util.jar.JarInputStream Java Examples

The following examples show how to use java.util.jar.JarInputStream. 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: SyntheticBundleBuilderTest.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAddFiles() throws IOException {
	SyntheticBundleBuilder builder = SyntheticBundleBuilder.newBuilder();
	File f = TestUtils.createFileFromString("<xml>", "xml");
	builder.bundleSymbolicName("testAddFiles").bundleVersion("1.0.0")
			.addManifestHeader("Import-Package", "org.osgi.framework")
			.addFile("plugin.xml", f)
			.addFile("plugin.properties", "name=value");
	InputStream is = builder.asInputStream();
	JarInputStream jis = new JarInputStream(is);
	Manifest mf = jis.getManifest();
	Assert.assertEquals("1.0.0",
			mf.getMainAttributes().getValue("Bundle-Version"));
	Assert.assertEquals("org.osgi.framework", mf.getMainAttributes()
			.getValue("Import-Package"));
	JarEntry je1 = jis.getNextJarEntry();
	Assert.assertEquals("plugin.xml", je1.getName());
	JarEntry je2 = jis.getNextJarEntry();
	Assert.assertEquals("plugin.properties", je2.getName());
	jis.close();
	is.close();
}
 
Example #2
Source File: RewritingUtils.java    From tascalate-javaflow with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException, IOException {
    ResourceTransformationFactory factory = createTransformerFactoryInstance();
    for (int i=0; i<args.length; i+=2) {
        System.out.println("rewriting " + args[i]);
        
        ResourceTransformer transformer = createTransformer(new URL[]{new File(args[i]).toURI().toURL()}, factory);
        try {
            RewritingUtils.rewriteJar(
                new JarInputStream(new FileInputStream(args[i])),
                transformer,
                new JarOutputStream(new FileOutputStream(args[i+1]))
            );
        } finally {
            transformer.release();
        }
    }

    System.out.println("done");
    
}
 
Example #3
Source File: UnreachableMethodRemoverTest.java    From AVM with MIT License 6 votes vote down vote up
@Test
public void testInvokeStaticMethodRemoval() throws Exception {
    String ClassInvokeStaticEntryName = getInternalNameForClass(InvokeStaticEntry.class);

    byte[] jar = TestUtil.serializeClassesAsJar(InvokeStaticEntry.class, ClassH.class, ClassI.class);
    byte[] optimizedJar = UnreachableMethodRemover.optimize(jar);
    assertNotNull(optimizedJar);

    JarInputStream jarReader = new JarInputStream(new ByteArrayInputStream(optimizedJar), true);
    Map<String, byte[]> classMap = Utilities.extractClasses(jarReader, Utilities.NameStyle.SLASH_NAME);

    assertNotNull(optimizedJar);
    assertEquals(3, classMap.size());

    Map<String, ClassInfo> classInfoMap = MethodReachabilityDetector.getClassInfoMap(ClassInvokeStaticEntryName, classMap);
    assertEquals(21, classInfoMap.size());
    ClassInfo classInfoH = classInfoMap.get(getInternalNameForClass(ClassH.class));
    ClassInfo classInfoI = classInfoMap.get(getInternalNameForClass(ClassI.class));

    assertNotNull(classInfoI);
    assertNotNull(classInfoH);

    assertEquals(1, classInfoI.getMethodMap().size());
    assertEquals(0, classInfoH.getMethodMap().size());
}
 
Example #4
Source File: MemoryJarClassLoader.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
public MemoryJarClassLoader(ClassLoader parentClassLoader, File jarFile) throws FileNotFoundException, IOException {
	super(parentClassLoader);
	this.jarFile = jarFile;
	try (FileInputStream fileInputStream = new FileInputStream(jarFile)) {
		try (JarInputStream jarInputStream = new JarInputStream(fileInputStream)) {
			JarEntry entry = jarInputStream.getNextJarEntry();
			while (entry != null) {
				if (entry.getName().endsWith(".jar")) {
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					IOUtils.copy(jarInputStream, byteArrayOutputStream);
					
					// Not storing the original JAR, so future code will be unable to read the original
					loadSubJars(byteArrayOutputStream.toByteArray());
				} else {
					// Files are being stored deflated in memory because most of the time a lot of files are not being used (or the complete plugin is not being used)
					addDataToMap(jarInputStream, entry);
				}
				entry = jarInputStream.getNextJarEntry();
			}
		}
	}
}
 
Example #5
Source File: PackerImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Takes a JarInputStream and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 * <p>
 * The modification time and deflation hint attributes are not available,
 * for the jar-manifest file and the directory containing the file.
 *
 * @see #MODIFICATION_TIME
 * @see #DEFLATION_HINT
 * @param in a JarInputStream
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarInputStream in, OutputStream out) throws IOException {
    assert(Utils.currentInstance.get() == null);
    TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null :
        TimeZone.getDefault();
    try {
        Utils.currentInstance.set(this);
        if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
            Utils.copyJarFile(in, out);
        } else {
            (new DoPack()).run(in, out);
        }
    } finally {
        Utils.currentInstance.set(null);
        if (tz != null) TimeZone.setDefault(tz);
        in.close();
    }
}
 
Example #6
Source File: UnpackJar.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
/**
 * 从jar包输入流解压需要的文件到目标目录
 *
 * @param inputStream jar包输入流
 * @param dir         目标目录
 * @param dep         是否是Spring Boot依赖包的解压, 只有为false时
 * @throws IOException 出现IO错误
 */
private void extraJarStream(InputStream inputStream, String dir, boolean dep, boolean jarInit) throws IOException {
    JarEntry entry = null;
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    while ((entry = jarInputStream.getNextJarEntry()) != null) {
        String name = entry.getName();
        if (((name.endsWith(SUFFIX_GROOVY)
                || name.endsWith(SUFFIX_XML)
                || name.endsWith(SUFFIX_XLSX)
                || name.endsWith(SUFFIX_SQL)) && name.contains(PREFIX_SCRIPT_DB))) {
            if (name.startsWith(PREFIX_SPRING_BOOT_CLASSES)) {
                name = name.substring(PREFIX_SPRING_BOOT_CLASSES.length());
            }
            File file = new File(dir + name);
            if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
                throw new IOException("create dir fail: " + file.getParentFile().getAbsolutePath());
            }
            try (FileOutputStream outputStream = new FileOutputStream(file)) {
                StreamUtils.copy(jarInputStream, outputStream);
            }
        } else if (name.endsWith(SUFFIX_JAR) && jarInit) {
            extraJarStream(jarInputStream, dir, true, true);
        }
    }
}
 
Example #7
Source File: PackerImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Takes a JarInputStream and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 * <p>
 * The modification time and deflation hint attributes are not available,
 * for the jar-manifest file and the directory containing the file.
 *
 * @see #MODIFICATION_TIME
 * @see #DEFLATION_HINT
 * @param in a JarInputStream
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarInputStream in, OutputStream out) throws IOException {
    assert(Utils.currentInstance.get() == null);
    TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null :
        TimeZone.getDefault();
    try {
        Utils.currentInstance.set(this);
        if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        if ("0".equals(props.getProperty(Pack200.Packer.EFFORT))) {
            Utils.copyJarFile(in, out);
        } else {
            (new DoPack()).run(in, out);
        }
    } finally {
        Utils.currentInstance.set(null);
        if (tz != null) TimeZone.setDefault(tz);
        in.close();
    }
}
 
Example #8
Source File: PackerImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Takes a JarInputStream and converts into a pack-stream.
 * <p>
 * Closes its input but not its output.  (Pack200 archives are appendable.)
 * <p>
 * The modification time and deflation hint attributes are not available,
 * for the jar-manifest file and the directory containing the file.
 *
 * @see #MODIFICATION_TIME
 * @see #DEFLATION_HINT
 * @param in a JarInputStream
 * @param out an OutputStream
 * @exception IOException if an error is encountered.
 */
public synchronized void pack(JarInputStream 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 #9
Source File: TestIndexedJarWithBadSignature.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String...args) throws Throwable {
    try (JarInputStream jis = new JarInputStream(
             new FileInputStream(System.getProperty("test.src", ".") +
                                 System.getProperty("file.separator") +
                                 "BadSignedJar.jar")))
    {
        JarEntry je1 = jis.getNextJarEntry();
        while(je1!=null){
            System.out.println("Jar Entry1==>"+je1.getName());
            je1 = jis.getNextJarEntry(); // This should throw Security Exception
        }
        throw new RuntimeException(
            "Test Failed:Security Exception not being thrown");
    } catch (IOException ie){
        ie.printStackTrace();
    } catch (SecurityException e) {
        System.out.println("Test passed: Security Exception thrown as expected");
    }
}
 
Example #10
Source File: Dexifier.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private byte[] dexifyJar(JarInputStream ji) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream outJar = new JarOutputStream(baos);
  DexFile dexFile = getDexFile();
  for (JarEntry je = ji.getNextJarEntry(); je != null; je = ji.getNextJarEntry()) {
    byte [] bytes = null;
    String name = je.getName();
    if (keepEntry(name)) {
      bytes  = getBytes(ji, (int) je.getSize());
      saveEntry(name, bytes, outJar);
    }
    if (name.endsWith(CLASS_SUFFIX)) {
      if (bytes == null) {
        bytes  = getBytes(ji, (int) je.getSize());
      }
      addToDexFile(dexFile, name, bytes);
    } else if (!force && name.equals(CLASSES_DEX)) {
      // Jar already dexified
      return null;
    }
  }
  saveDexFile(dexFile, 1, outJar);
  outJar.close();
  return baos.toByteArray();
}
 
Example #11
Source File: JarWarResourceSet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {

    try (JarFile warFile = new JarFile(getBase())) {
        JarEntry jarFileInWar = warFile.getJarEntry(archivePath);
        InputStream jarFileIs = warFile.getInputStream(jarFileInWar);

        try (JarInputStream jarIs = new JarInputStream(jarFileIs)) {
            setManifest(jarIs.getManifest());
        }
    } catch (IOException ioe) {
        throw new IllegalArgumentException(ioe);
    }

    try {
        setBaseUrl(UriUtil.buildJarSafeUrl(new File(getBase())));
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #12
Source File: RenamerTest.java    From AVM with MIT License 6 votes vote down vote up
@Test
public void testRenameFields() throws Exception {
    byte[] jarBytes = TestUtil.serializeClassesAsJar(RenameTarget.class);
    JarInputStream jarReader = new JarInputStream(new ByteArrayInputStream(jarBytes), true);

    String mainClassName = Utilities.fulllyQualifiedNameToInternalName(RenameTarget.class.getName());
    Map<String, ClassNode> classMap = Renamer.sortBasedOnInnerClassLevel(extractClasses(jarReader));

    Map<String, ClassInfo> classInfoMap = MethodReachabilityDetector.getClassInfoMap(mainClassName, getClassBytes(classMap));
    Map<String, String> renamedFields = FieldRenamer.renameFields(classMap, classInfoMap);

    String ParentInterfaceOneName = RenameTarget.ParentInterfaceOne.class.getName();
    String ConcreteChildOneName = RenameTarget.ConcreteChildOne.class.getName();
    String ClassBName = RenameTarget.ClassB.class.getName();
    String ClassCName = RenameTarget.ClassB.ClassC.class.getName();

    String mappedName = renamedFields.get(makeFullFieldName(ConcreteChildOneName, "b"));
    Assert.assertNotNull(mappedName);
    Assert.assertEquals(mappedName, renamedFields.get(makeMethodFullName(ParentInterfaceOneName, "b")));

    mappedName = renamedFields.get(makeFullFieldName(ClassBName, "f"));
    Assert.assertNotNull(mappedName);
    Assert.assertNotEquals(mappedName, renamedFields.get(makeMethodFullName(ClassCName, "f")));
}
 
Example #13
Source File: TestJarFinder.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testNoManifest");
  delete(dir);
  dir.mkdirs();
  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
 
Example #14
Source File: TestIndexedJarWithBadSignature.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String...args) throws Throwable {
    try (JarInputStream jis = new JarInputStream(
             new FileInputStream(System.getProperty("test.src", ".") +
                                 System.getProperty("file.separator") +
                                 "BadSignedJar.jar")))
    {
        JarEntry je1 = jis.getNextJarEntry();
        while(je1!=null){
            System.out.println("Jar Entry1==>"+je1.getName());
            je1 = jis.getNextJarEntry(); // This should throw Security Exception
        }
        throw new RuntimeException(
            "Test Failed:Security Exception not being thrown");
    } catch (IOException ie){
        ie.printStackTrace();
    } catch (SecurityException e) {
        System.out.println("Test passed: Security Exception thrown as expected");
    }
}
 
Example #15
Source File: RenamerTest.java    From AVM with MIT License 6 votes vote down vote up
@Test
public void testJclMethodNotRenamed() throws Exception {
    byte[] jarBytes = TestUtil.serializeClassesAsJar(RenameTarget.class, ClassA.class, ClassB.class, ClassC.class, InterfaceD.class);
    JarInputStream jarReader = new JarInputStream(new ByteArrayInputStream(jarBytes), true);

    String mainClassName = Utilities.fulllyQualifiedNameToInternalName(RenameTarget.class.getName());
    Map<String, ClassNode> classMap = Renamer.sortBasedOnInnerClassLevel(extractClasses(jarReader));

    Map<String, ClassInfo> classInfoMap = MethodReachabilityDetector.getClassInfoMap(mainClassName, getClassBytes(classMap));
    Map<String, String> newMethodMap = MethodRenamer.renameMethods(classMap, classInfoMap);

    String comparatorMethodKeyString = "compareTo(Ljava/lang/String;)I";
    String classAName = ClassA.class.getName();
    String classBName = ClassB.class.getName();
    String classCName = ClassC.class.getName();

    Assert.assertTrue(!newMethodMap.containsKey(makeMethodFullName(classAName, comparatorMethodKeyString)));
    Assert.assertTrue(!newMethodMap.containsKey(makeMethodFullName(classBName, comparatorMethodKeyString)));
    Assert.assertTrue(!newMethodMap.containsKey(makeMethodFullName(classCName, comparatorMethodKeyString)));
}
 
Example #16
Source File: ApplicationBundlerTest.java    From twill with Apache License 2.0 6 votes vote down vote up
private void unjar(File jarFile, File targetDir) throws IOException {
  try (JarInputStream jarInput = new JarInputStream(new FileInputStream(jarFile))) {
    JarEntry jarEntry = jarInput.getNextJarEntry();
    while (jarEntry != null) {
      File target = new File(targetDir, jarEntry.getName());
      if (jarEntry.isDirectory()) {
        target.mkdirs();
      } else {
        target.getParentFile().mkdirs();
        ByteStreams.copy(jarInput, Files.newOutputStreamSupplier(target));
      }

      jarEntry = jarInput.getNextJarEntry();
    }
  }
}
 
Example #17
Source File: TestIndexedJarWithBadSignature.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String...args) throws Throwable {
    try (JarInputStream jis = new JarInputStream(
             new FileInputStream(System.getProperty("test.src", ".") +
                                 System.getProperty("file.separator") +
                                 "BadSignedJar.jar")))
    {
        JarEntry je1 = jis.getNextJarEntry();
        while(je1!=null){
            System.out.println("Jar Entry1==>"+je1.getName());
            je1 = jis.getNextJarEntry(); // This should throw Security Exception
        }
        throw new RuntimeException(
            "Test Failed:Security Exception not being thrown");
    } catch (IOException ie){
        ie.printStackTrace();
    } catch (SecurityException e) {
        System.out.println("Test passed: Security Exception thrown as expected");
    }
}
 
Example #18
Source File: MTSClassLoader.java    From ModTheSpire with MIT License 6 votes vote down vote up
public MTSClassLoader(InputStream stream, URL[] urls, ClassLoader parent) throws IOException
{
    super(urls, null);

    this.parent = parent;
    JarInputStream is = new JarInputStream(stream);
    JarEntry entry = is.getNextJarEntry();
    while (entry != null) {
        if (entry.getName().contains(".class")) {
            String className = entry.getName().replace(".class", "").replace('/', '.');
            byte[] classBytes = bufferStream(is);
            classes.put(className, classBytes);
        }
        entry = is.getNextJarEntry();
    }
}
 
Example #19
Source File: TestJarFinder.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testNoManifest");
  delete(dir);
  dir.mkdirs();
  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
 
Example #20
Source File: CodeGenTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientJar() throws Exception {
    env.put(ToolConstants.CFG_WSDLURL, getLocation("/wsdl2java_wsdl/hello_world_wsdl_import.wsdl"));
    env.put(ToolConstants.CFG_CLIENT_JAR, "test-client.jar");
    processor.setContext(env);
    processor.execute();
    File clientjarFile = new File(output, "test-client.jar");
    assertTrue(clientjarFile.exists());

    List<String> jarEntries = new ArrayList<>();
    JarInputStream jarIns = new JarInputStream(new FileInputStream(clientjarFile));
    JarEntry entry = null;
    while ((entry = jarIns.getNextJarEntry()) != null) {
        if (entry.getName().endsWith(".wsdl") || entry.getName().endsWith(".class")) {
            jarEntries.add(entry.getName());
        }
    }
    jarIns.close();
    assertEquals("15 files including wsdl and class files are expected", 15, jarEntries.size());
    assertTrue("hello_world_messages.wsdl is expected",
                 jarEntries.contains("hello_world_messages.wsdl"));
    assertTrue("org/apache/cxf/w2j/hello_world/SOAPService.class is expected",
                 jarEntries.contains("org/apache/cxf/w2j/hello_world/SOAPService.class"));
}
 
Example #21
Source File: AttributesParserFeatureXml.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public AttributesParserFeatureXml(final TempBlobConverter tempBlobConverter, final PropertyParser propertyParser) {
  this.propertyParser = propertyParser;
  documentJarExtractor = new JarExtractor<Document>(tempBlobConverter)
  {
    @Override
    protected Document createSpecificEntity(JarInputStream jis, JarEntry jarEntry)
        throws IOException, AttributeParsingException
    {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(false);
      try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        return factory.newDocumentBuilder().parse(jis);
      }
      catch (ParserConfigurationException | SAXException e) {
        throw new AttributeParsingException(e);
      }
    }
  };
}
 
Example #22
Source File: NestedJarArchiveTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void xbeanNestedScanning(final TestInfo info, @TempDir final File temporaryFolder) throws IOException {
    final File jar = createPlugin(temporaryFolder, info.getTestMethod().get().getName());
    final ConfigurableClassLoader configurableClassLoader = new ConfigurableClassLoader("", new URL[0],
            new URLClassLoader(new URL[] { jar.toURI().toURL() }, Thread.currentThread().getContextClassLoader()),
            n -> true, n -> true, new String[] { "com/foo/bar/1.0/bar-1.0.jar" }, new String[0]);
    try (final JarInputStream jis = new JarInputStream(
            configurableClassLoader.getResourceAsStream("MAVEN-INF/repository/com/foo/bar/1.0/bar-1.0.jar"))) {
        assertNotNull(jis, "test is wrongly setup, no nested jar, fix the createPlugin() method please");
        final AnnotationFinder finder =
                new AnnotationFinder(new NestedJarArchive(null, jis, configurableClassLoader));
        final List<Class<?>> annotatedClasses = finder.findAnnotatedClasses(Processor.class);
        assertEquals(1, annotatedClasses.size());
        assertEquals("org.talend.test.generated." + info.getTestMethod().get().getName() + ".Components",
                annotatedClasses.iterator().next().getName());
    } finally {
        URLClassLoader.class.cast(configurableClassLoader.getParent()).close();
    }
}
 
Example #23
Source File: Utils.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void copyJarFile(JarInputStream in, JarOutputStream out) throws IOException {
    if (in.getManifest() != null) {
        ZipEntry me = new ZipEntry(JarFile.MANIFEST_NAME);
        out.putNextEntry(me);
        in.getManifest().write(out);
        out.closeEntry();
    }
    byte[] buffer = new byte[1 << 14];
    for (JarEntry je; (je = in.getNextJarEntry()) != null; ) {
        out.putNextEntry(je);
        for (int nr; 0 < (nr = in.read(buffer)); ) {
            out.write(buffer, 0, nr);
        }
    }
    in.close();
    markJarFile(out);  // add PACK200 comment
}
 
Example #24
Source File: JarExtractor.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
protected Optional<T> getSpecificEntity(
    final TempBlob tempBlob,
    final String extension,
    @Nullable final String startNameForSearch) throws IOException, AttributeParsingException
{
  try (JarInputStream jis = getJarStreamFromBlob(tempBlob, extension)) {
    JarEntry jarEntry;
    while ((jarEntry = jis.getNextJarEntry()) != null) {
      if (startNameForSearch != null && jarEntry.getName().startsWith(startNameForSearch)) {
        return Optional.ofNullable(createSpecificEntity(jis, jarEntry));
      }
    }
  }

  return Optional.empty();
}
 
Example #25
Source File: ClasspathCache.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void loadClassNamesFromJarInputStream(JarInputStream jarIn, String directory,
        Location location, Multimap<String, Location> newClassNameLocations)
        throws IOException {
    JarEntry jarEntry;
    while ((jarEntry = jarIn.getNextJarEntry()) != null) {
        if (jarEntry.isDirectory()) {
            continue;
        }
        String name = jarEntry.getName();
        if (name.startsWith(directory) && name.endsWith(".class")) {
            name = name.substring(directory.length());
            String className = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
            newClassNameLocations.put(className, location);
        }
    }
}
 
Example #26
Source File: ClassScanner.java    From tapir with MIT License 6 votes vote down vote up
public void addPackage(String packageName, boolean recursive) throws IOException {
    String[] paths = loader.getPaths();
    final String packagePath = packageName == null ? null : (packageName.replace('.', '/') + "/");
    int prevSize = classes.size();
    for (String p : paths) {
        File file = new File(p);
        if (file.isDirectory()) {
            addMatchingDir(null, file, packagePath, recursive);
        } else {
            JarInputStream jis = new JarInputStream(new FileInputStream(file));
            ZipEntry e = jis.getNextEntry();
            while (e != null) {
                addMatchingFile(e.getName(), packagePath, recursive);
                jis.closeEntry();
                e = jis.getNextEntry();
            }
            jis.close();
        }
    }
    if (classes.size() == 0 && packageName == null) {
        logger.warn("No classes found in the unnamed package");
        Builder.printHelp();
    } else if (prevSize == classes.size() && packageName != null) {
        logger.warn("No classes found in package " + packageName);
    }
}
 
Example #27
Source File: JarFile.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
void setupEntryCertificates(JarEntry entry) {
    // Fallback to JarInputStream to obtain certificates, not fast but hopefully not
    // happening that often.
    try {
        JarInputStream inputStream = new JarInputStream(getData().getInputStream(
            ResourceAccess.ONCE));
        try {
            java.util.jar.JarEntry certEntry = inputStream.getNextJarEntry();
            while (certEntry != null) {
                inputStream.closeEntry();
                if (entry.getName().equals(certEntry.getName())) {
                    setCertificates(entry, certEntry);
                }
                setCertificates(getJarEntry(certEntry.getName()), certEntry);
                certEntry = inputStream.getNextJarEntry();
            }
        } finally {
            inputStream.close();
        }
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #28
Source File: OnwireClassRegistry.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
static Set<Class<?>> getFromJARFile(String jar, String packageName) throws IOException, ClassNotFoundException {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    try (JarInputStream jarFile = new JarInputStream(new FileInputStream(jar));) {
        JarEntry jarEntry;
        do {
            jarEntry = jarFile.getNextJarEntry();
            if (jarEntry != null) {
                String className = jarEntry.getName();
                if (className.endsWith(".class")) {
                    className = stripFilenameExtension(className);
                    if (className.startsWith(packageName)) {
                        try {
                            Class<?> clz = Class.forName(className.replace('/', '.'));
                            classes.add(clz);
                        } catch (ClassNotFoundException | NoClassDefFoundError e) {
                            s_logger.warn("Unable to load class from jar file", e);
                        }
                    }
                }
            }
        } while (jarEntry != null);
        return classes;
    }
}
 
Example #29
Source File: Utils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void copyJarFile(JarInputStream in, OutputStream out) throws IOException {
    // 4947205 : Peformance is slow when using pack-effort=0
    out = new BufferedOutputStream(out);
    out = new NonCloser(out); // protect from JarOutputStream.close()
    try (JarOutputStream jout = new JarOutputStream(out)) {
        copyJarFile(in, jout);
    }
}
 
Example #30
Source File: UpgradeServiceImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public UpgradeRequest readSlingJar(InputStream jar) throws IOException {
    log.trace("readSlingJar");

    UpgradeRequest request = null;
    try (JarInputStream jarIs = new JarInputStream(jar)) {
        Manifest manifest = jarIs.getManifest();

        request = new UpgradeRequest(manifest);

        JarEntry entry = jarIs.getNextJarEntry();
        while (entry != null) {
            log.debug("Reading entry {}", entry.getName());

            for (EntryHandlerFactory<?> factory : entryFactories) {
                if (factory.matches(entry)) {
                    log.debug("Loading with {}", factory.getClass().getName());
                    request.getEntries().add(factory.loadEntry(entry, jarIs));
                    break;
                }
            }
            entry = jarIs.getNextJarEntry();
        }

        Collections.sort(request.getEntries());
    }
    return request;
}