public static Application readJar(Path path) throws IOException { Application application = new Application(); try (JarInputStream in = new JarInputStream(new BufferedInputStream(Files.newInputStream(path)))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String name = entry.getName(); if (!name.endsWith(".class")) continue; name = name.replaceAll(".class$", ""); ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(in); reader.accept(node, ClassReader.SKIP_DEBUG); application.classes.put(name, node); } } return application; }
/** * Store all class names found in this jar file */ private static LinkedList<String> processJar(File jarfile, String basepath) { // System.out.println("Processing JAR " + jarfile.getPath()); LinkedList<String> addlist = new LinkedList<String>(); try { JarInputStream jarIS = new JarInputStream(new FileInputStream( jarfile)); JarEntry entry = null; while ((entry = jarIS.getNextJarEntry()) != null) { String name = entry.getName(); if (name.endsWith(".class")) { // System.out.println( entry.getAttributes().toString() ); if (!add(name, jarfile.getPath(), basepath).isEmpty()) addlist.addAll(add(name, jarfile.getPath(), basepath)); } } } catch (Exception e) { } return addlist; }
@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(); }
@SuppressWarnings("PMD.EmptyCatchBlock") private InputStream readManifest(InputStream binaryExtension) throws IOException { JarInputStream jar = new JarInputStream(binaryExtension); try { JarEntry entry; do { entry = jar.getNextJarEntry(); if (entry != null && MANIFEST_LOCATION.equals(entry.getName())) { return jar; } } while (entry != null); jar.close(); return null; } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) { try { jar.close(); } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception ex2) { // ignore } throw SyndesisServerException.launderThrowable(e); } }
protected void scanJar(URL jarUrl, Map<String, ResourceInfo> resInfos) throws IOException { JarInputStream jarInput = new JarInputStream(jarUrl.openStream(), false); JarEntry entry = null; while((entry = jarInput.getNextJarEntry()) != null) { String entryName = entry.getName(); if(entryName != null && entryName.endsWith(".class")) { final String className = entryName.substring(0, entryName.length() - 6).replace('/', '.'); if(!resInfos.containsKey(className)) { ClassReader classReader = new ClassReader(jarInput); ResourceInfo resInfo = new ResourceInfo(null, className, null); ResourceInfoVisitor visitor = new ResourceInfoVisitor(resInfo); classReader.accept(visitor, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); if(visitor.isCreoleResource()) { resInfos.put(className, resInfo); } } } } jarInput.close(); }
public void tstConnectionToJarOnClassPath() throws Exception { URL url = bundle.getEntry("bundleclasspath/simple.jar"); System.out.println("jar url is " + url); URLConnection con = url.openConnection(); System.out.println(con); System.out.println(con.getContentType()); InputStream stream = con.getInputStream(); JarInputStream jis = new JarInputStream(stream); System.out.println(jis); System.out.println(jis.available()); System.out.println(jis.getNextJarEntry()); System.out.println(jis.getNextJarEntry()); System.out.println(jis.getNextJarEntry()); System.out.println(jis.available()); System.out.println(jis.getNextJarEntry()); System.out.println(jis.available()); jis.close(); }
/** * Dumps the entries of a jar and return them as a String. This method can * be memory expensive depending on the jar size. * * @param jis * @return * @throws Exception */ public static String dumpJarContent(JarInputStream jis) { StringBuilder buffer = new StringBuilder(); try { JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { buffer.append(entry.getName()); buffer.append("\n"); } } catch (IOException ioException) { buffer.append("reading from stream failed"); } finally { closeStream(jis); } return buffer.toString(); }
private void assertExistingJarFile(Path mtaArchiveFile, String fileName, String expectedContent) throws Exception { try (JarInputStream in = new JarInputStream(Files.newInputStream(mtaArchiveFile))) { for (ZipEntry e; (e = in.getNextEntry()) != null;) { if (fileName.equals(e.getName()) && !e.isDirectory()) { StringBuilder textBuilder = new StringBuilder(); try (Reader reader = new BufferedReader(new InputStreamReader(in))) { int c = 0; while ((c = reader.read()) != -1) { textBuilder.append((char) c); } } assertEquals(expectedContent, textBuilder.toString()); return; } } throw new AssertionError(MessageFormat.format("Zip archive file \"{0}\" could not be found", fileName)); } }
/** * 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(); } }
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 }
private Set<String> pakArchiefBestandUit(final Path tmpFolder) { getLog().debug("Unpacking artifact"); Set<String> keys = new TreeSet<>(); try (final JarInputStream archiefStream = new JarInputStream(new FileInputStream(artifact + ".bak"))) { final List<String> bestanden = new ArrayList<>(); JarEntry archiefItem = archiefStream.getNextJarEntry(); while (archiefItem != null) { final File archiefBestand = new File(tmpFolder.toFile(), archiefItem.getName()); if (archiefItem.isDirectory()) { archiefBestand.mkdirs(); } else { pakBestandUit(archiefStream, archiefBestand); } bestanden.add(archiefItem.getName()); archiefStream.closeEntry(); archiefItem = archiefStream.getNextJarEntry(); } pakManifestUit(tmpFolder, archiefStream, bestanden); keys.addAll(bestanden); } catch (IOException | WrappedException e) { getLog().debug("Artifact cannot be fixed", e); } return keys; }
private void pakBestandUit(final JarInputStream archiefStream, final File archiefBestand) throws IOException { final File parentBestand = new File(archiefBestand.getAbsolutePath().substring(0, archiefBestand.getAbsolutePath().lastIndexOf(File.separator))); parentBestand.mkdirs(); if (archiefBestand.createNewFile()) { try (final FileOutputStream fos = new FileOutputStream(archiefBestand); final BufferedOutputStream bos = new BufferedOutputStream(fos)) { int len; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiefStream.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.flush(); } } }
private static void publicize(Path inPath, Path outPath) throws IOException { try (JarInputStream in = new JarInputStream(Files.newInputStream(inPath))) { try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(outPath))) { JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { if (entry.isDirectory()) { continue; } String name = entry.getName(); out.putNextEntry(new JarEntry(name)); if (name.endsWith(".class")) { ClassWriter writer = new ClassWriter(0); ClassReader reader = new ClassReader(in); reader.accept(new CheckClassAdapter(new ClassDefinalizer(new ClassPublicizer(writer)), true), 0); out.write(writer.toByteArray()); } else { ByteStreams.copy(in, out); } } } } }
/** * 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(); } }
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 Path addFiles(Path module, InMemoryFile... resources) throws IOException { Path tempFile = Files.createTempFile("jlink-test", ""); try (JarInputStream in = new JarInputStream(Files.newInputStream(module)); JarOutputStream out = new JarOutputStream(new FileOutputStream(tempFile.toFile()))) { ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String name = entry.getName(); out.putNextEntry(new ZipEntry(name)); copy(in, out); out.closeEntry(); } for (InMemoryFile r : resources) { addFile(r, out); } } Files.move(tempFile, module, StandardCopyOption.REPLACE_EXISTING); return module; }
@SuppressWarnings("resource") private List<String> readFromJarFile(String jarPath, String splashedPackageName) throws IOException { if (logger.isDebugEnabled()) { logger.debug("从JAR包中读取类: {}", jarPath); } JarInputStream jarIn = new JarInputStream(new FileInputStream(jarPath)); JarEntry entry = jarIn.getNextJarEntry(); List<String> nameList = new ArrayList<>(); while (null != entry) { String name = entry.getName(); if (name.startsWith(splashedPackageName) && isClassFile(name)) { nameList.add(name); } entry = jarIn.getNextJarEntry(); } return nameList; }
public static String[] loadManifestClasspath(File file) { try { JarInputStream inputStream = new JarInputStream(new FileInputStream(file)); try { final Manifest manifest = inputStream.getManifest(); if (manifest != null) { final String classPath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); if (classPath != null) { return classPath.split(" "); } } } finally { inputStream.close(); } } catch (Exception ignore) { } return null; }
@Test public void createFoo() throws IOException { Path mp = Paths.get("createFoo"); createTestDir(mp); Path modClasses = MODULE_CLASSES.resolve(FOO.moduleName); Path modularJar = mp.resolve(FOO.moduleName + ".jar"); jar("--create", "--file=" + modularJar.toString(), "--main-class=" + FOO.mainClass, "--module-version=" + FOO.version, "--no-manifest", "-C", modClasses.toString(), ".") .assertSuccess(); java(mp, FOO.moduleName + "/" + FOO.mainClass) .assertSuccess() .resultChecker(r -> assertModuleData(r, FOO)); try (InputStream fis = Files.newInputStream(modularJar); JarInputStream jis = new JarInputStream(fis)) { assertTrue(!jarContains(jis, "./"), "Unexpected ./ found in ", modularJar.toString()); } }
public static Manifest getManifest(final URI uri) { if (uri == null) { return null; } Manifest manifest; if ((manifest = manifests.get(uri)) != null) { return manifest; } try (JarInputStream jarInputStream = new JarInputStream(uri.toURL().openStream())) { if ((manifest = jarInputStream.getManifest()) != null) { manifests.put(uri, manifest); } return manifest; } catch (final IOException exception) { return null; } }
/** * 从jar包中加载class * @param loader * @param jar * @param packageName * @return * @throws IOException * @throws ClassNotFoundException */ private static Set<Class<?>> getFromJARFile(final ClassLoader loader, final String jar, final String packageName) throws IOException, ClassNotFoundException { final Set<Class<?>> classes = new HashSet<Class<?>>(); final JarInputStream jarFile = new JarInputStream(new FileInputStream(jar)); try { JarEntry jarEntry; do { jarEntry = jarFile.getNextJarEntry(); if (jarEntry != null) { String className = jarEntry.getName(); if (className.endsWith(".class") && getPackageName(className).equals(packageName)) { className = stripFilenameExtension(className); classes.add(Class.forName(className.replace('/', '.'), true, loader)); } } } while (jarEntry != null); } finally { jarFile.close(); } return classes; }
private void scanJar(Path path, SourceSet src, Decompiler decomp) { try (JarInputStream jar = new JarInputStream(new BufferedInputStream(Files.newInputStream(path)))) { ZipEntry entry = jar.getNextEntry(); if (entry == null) { return; } do { if (entry.isDirectory()) { continue; } final String name = entry.getName(); if (!name.endsWith(".class")) { continue; } scanClassFile(jar, src, decomp); } while ((entry = jar.getNextEntry()) != null); } catch (IOException e) { e.printStackTrace(); return; } }
/** * List the names of the entries in the given {@link JarInputStream} that begin with the * specified {@code path}. Entries will match with or without a leading slash. * * @param jar The JAR input stream * @param path The leading path to match * @return The names of all the matching entries * @throws IOException If I/O errors occur */ protected List<String> listResources(JarInputStream jar, String path) throws IOException { // Include the leading and trailing slash when matching names if (!path.startsWith("/")) path = "/" + path; if (!path.endsWith("/")) path = path + "/"; // Iterate over the entries and collect those that begin with the requested path List<String> resources = new ArrayList<String>(); for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) { if (!entry.isDirectory()) { // Add leading slash if it's missing String name = entry.getName(); if (!name.startsWith("/")) name = "/" + name; // Check file name if (name.startsWith(path)) { log.trace("Found resource: ", name); resources.add(name.substring(1)); // Trim leading slash } } } return resources; }
private static MainPair loadMainClassFromClasspathJar(File jarFile, String[] args) throws Exception { final JarInputStream inputStream = new JarInputStream(new FileInputStream(jarFile)); try { final Manifest manifest = inputStream.getManifest(); final String vmParams = manifest.getMainAttributes().getValue("VM-Options"); if (vmParams != null) { final HashMap vmOptions = new HashMap(); parseVmOptions(vmParams, vmOptions); for (Iterator iterator = vmOptions.keySet().iterator(); iterator.hasNext(); ) { String optionName = (String)iterator.next(); System.setProperty(optionName, (String)vmOptions.get(optionName)); } } } finally { if (inputStream != null) { inputStream.close(); } jarFile.deleteOnExit(); } return new MainPair(Class.forName(args[1]), new String[args.length - 2]); }
/** * Reads a properties file from a jar. * * @param jarFileName * @param fileName * @return Properties * @throws IOException */ public static Properties readProperties( String jarFileName, String fileName ) throws IOException, FileNotFoundException { // open the jar file JarInputStream jarInputStream = openJar( jarFileName ); // look for the properties file JarEntry jarEntry = getJarEntry( jarInputStream, fileName ); // read the properties file into a Properties object Properties properties = null; if ( jarEntry != null ) { properties = new Properties(); properties.load( jarInputStream ); } else { throw new FileNotFoundException( "file not found: " + fileName ); } // close the jar file jarInputStream.close(); return properties; }
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(); } } }
static Set<Class<?>> getFromJARFile(final String jar, final String packageName) throws IOException, ClassNotFoundException { final Set<Class<?>> classes = new HashSet<>(); 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 { final 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 List<String> listResources(JarInputStream jis, String path) throws Exception { List<String> res = Lists.newArrayList(); if (!path.startsWith("/")) { path = "/" + path; } if (!path.endsWith("/")) { path = path + "/"; } System.out.println(path); for (JarEntry entry; (entry = jis.getNextJarEntry()) != null;) { if (!entry.isDirectory()) { String name = entry.getName(); System.out.println("jar中资源>" + name); if (!name.startsWith("/")) { name = "/" + name; } if (name.startsWith(path)) { System.out.println("jar中指定包资源>" + name); res.add(name.substring(1)); } } } return res; }
private List<String> jar(JarInputStream jarStream) throws IOException { List<String> classNames = new ArrayList<>(); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } String className = entry.getName(); className = className.replaceFirst(".class$", ""); //war files are treated as .jar files, so takeout WEB-INF/classes className = StringUtils.removeStart(className, "WEB-INF/classes/"); className = className.replace('/', '.'); classNames.add(className); } return classNames; }
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); } }