类java.util.jar.JarInputStream源码实例Demo

下面列出了怎么用java.util.jar.JarInputStream的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Tomcat8-Source-Read   文件: JarWarResourceSet.java
@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);
    }
}
 
源代码2 项目: openjdk-8-source   文件: PackerImpl.java
/**
 * 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();
    }
}
 
源代码3 项目: dragonwell8_jdk   文件: PackerImpl.java
/**
 * 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();
    }
}
 
源代码4 项目: openjdk-8   文件: PackerImpl.java
/**
 * 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();
    }
}
 
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");
    }
}
 
源代码6 项目: cloudstack   文件: OnwireClassRegistry.java
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;
    }
}
 
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");
    }
}
 
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");
    }
}
 
源代码9 项目: ModTheSpire   文件: MTSClassLoader.java
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();
    }
}
 
源代码10 项目: cxf   文件: CodeGenTest.java
@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"));
}
 
源代码11 项目: glowroot   文件: ClasspathCache.java
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);
        }
    }
}
 
源代码12 项目: tapir   文件: ClassScanner.java
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);
    }
}
 
源代码13 项目: concierge   文件: SyntheticBundleBuilderTest.java
@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();
}
 
源代码14 项目: sofa-ark   文件: JarFile.java
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);
    }
}
 
源代码15 项目: nexus-repository-p2   文件: JarExtractor.java
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();
}
 
源代码16 项目: openjdk-jdk8u-backup   文件: Utils.java
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
}
 
源代码17 项目: component-runtime   文件: NestedJarArchiveTest.java
@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();
    }
}
 
@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);
      }
    }
  };
}
 
源代码19 项目: hbase   文件: TestJarFinder.java
@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();
}
 
源代码20 项目: twill   文件: ApplicationBundlerTest.java
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();
    }
  }
}
 
源代码21 项目: AVM   文件: RenamerTest.java
@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)));
}
 
源代码22 项目: big-c   文件: TestJarFinder.java
@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();
}
 
源代码23 项目: AVM   文件: RenamerTest.java
@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")));
}
 
源代码24 项目: tascalate-javaflow   文件: RewritingUtils.java
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");
    
}
 
源代码25 项目: AVM   文件: UnreachableMethodRemoverTest.java
@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());
}
 
源代码26 项目: knopflerfish.org   文件: Dexifier.java
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();
}
 
源代码27 项目: choerodon-starters   文件: UnpackJar.java
/**
 * 从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);
        }
    }
}
 
源代码28 项目: BIMserver   文件: MemoryJarClassLoader.java
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();
			}
		}
	}
}
 
源代码29 项目: Tomcat8-Source-Read   文件: ExtensionValidator.java
/**
 * Return the Manifest from a jar file or war file
 *
 * @param inStream Input stream to a WAR or JAR file
 * @return The WAR's or JAR's manifest
 */
private static Manifest getManifest(InputStream inStream) throws IOException {
    Manifest manifest = null;
    try (JarInputStream jin = new JarInputStream(inStream)) {
        manifest = jin.getManifest();
    }
    return manifest;
}
 
源代码30 项目: jkube   文件: MavenUtil.java
public static boolean hasKubernetesJson(File f) throws IOException {
    try (FileInputStream fis = new FileInputStream(f); JarInputStream jis = new JarInputStream(fis)) {
        for (JarEntry entry = jis.getNextJarEntry(); entry != null; entry = jis.getNextJarEntry()) {
            if (entry.getName().equals(DEFAULT_CONFIG_FILE_NAME)) {
                return true;
            }
        }
    }
    return false;
}
 
 类所在包
 同包方法