List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private void indexJar(URL url, File jar) throws IOException { JarFile jarFile = new JarFile(jar); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); cachedFiles.put(entry.getName(), url); }/*from w w w . j a va 2 s . c o m*/ jarFile.close(); cachedJars.put(url, jar); }
From source file:org.apache.catalina.startup.TldConfig.java
/** * Scans all TLD entries in the given JAR for application listeners. * * @param file JAR file whose TLD entries are scanned for application * listeners/* w ww. ja v a2 s . c om*/ */ private void tldScanJar(File file) throws Exception { JarFile jarFile = null; String name = null; String jarPath = file.getAbsolutePath(); try { jarFile = new JarFile(file); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); name = entry.getName(); if (!name.startsWith("META-INF/")) { continue; } if (!name.endsWith(".tld")) { continue; } if (log.isTraceEnabled()) { log.trace(" Processing TLD at '" + name + "'"); } try { tldScanStream(new InputSource(jarFile.getInputStream(entry))); } catch (Exception e) { log.error(sm.getString("contextConfig.tldEntryException", name, jarPath, context.getPath()), e); } } } catch (Exception e) { log.error(sm.getString("contextConfig.tldJarException", jarPath, context.getPath()), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // Ignore } } } }
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException { JarFile jarFile = new JarFile(jar); JarEntry entry = jarFile.getJarEntry(pathName); InputStream input = jarFile.getInputStream(entry); byte[] classData = new byte[(int) entry.getSize()]; int totalBytes = 0; while (totalBytes < classData.length) { int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes); if (bytesRead == -1) { throw new IOException("Jar Entry too short!"); }//from ww w . j a v a 2s . com totalBytes += bytesRead; } Class<?> loadedClass = defineClass(name, classData, 0, classData.length, new CodeSource(url, entry.getCertificates())); input.close(); jarFile.close(); return loadedClass; }
From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java
private URL getURLFromJAR(URLClassLoader urlLoader, URL relativeURL) { URL[] urlList = null;//from ww w. j a v a 2s. c o m ResourceFinderFactory rff = (ResourceFinderFactory) MetadataFactoryRegistry .getFactory(ResourceFinderFactory.class); ResourceFinder cf = rff.getResourceFinder(); if (log.isDebugEnabled()) { log.debug("ResourceFinderFactory: " + rff.getClass().getName()); log.debug("ResourceFinder: " + cf.getClass().getName()); } urlList = cf.getURLs(urlLoader); if (urlList == null) { if (log.isDebugEnabled()) { log.debug("No URL's found in URL ClassLoader"); } throw ExceptionFactory.makeWebServiceException(Messages.getMessage("WSDL4JWrapperErr1")); } for (URL url : urlList) { if ("file".equals(url.getProtocol())) { // Insure that Windows spaces are properly handled in the URL final File f = new File(url.getPath().replaceAll("%20", " ")); // If file is not of type directory then its a jar file if (isAFile(f)) { try { JarFile jf = (JarFile) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return new JarFile(f); } }); Enumeration<JarEntry> entries = jf.entries(); // read all entries in jar file and return the first // wsdl file that matches // the relative path while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String name = je.getName(); if (name.endsWith(".wsdl")) { String relativePath = relativeURL.getPath(); if (relativePath.endsWith(name)) { String path = f.getAbsolutePath(); // This check is necessary because Unix/Linux file paths begin // with a '/'. When adding the prefix 'jar:file:/' we may end // up with '//' after the 'file:' part. This causes the URL // object to treat this like a remote resource if (path != null && path.indexOf("/") == 0) { path = path.substring(1, path.length()); } URL absoluteUrl = new URL("jar:file:/" + path + "!/" + je.getName()); return absoluteUrl; } } } } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } } } return null; }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlCompilerGeneratesModuleForValidUnits() throws IOException { CeyloncTaskImpl compilerTask = getCompilerTask("modules/single/module.ceylon", "modules/single/Correct.ceylon", "modules/single/Invalid.ceylon"); Boolean success = compilerTask.call(); assertFalse(success);/* w w w . j a v a 2 s .c o m*/ File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6"); assertTrue(carFile.exists()); JarFile car = new JarFile(carFile); ZipEntry moduleClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class"); assertNotNull(moduleClass); ZipEntry correctClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/Correct.class"); assertNotNull(correctClass); ZipEntry invalidClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/Invalid.class"); assertNull(invalidClass); car.close(); }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
/** * Get a list of resources from class path directory. Attention: path must * be a path !/*from w w w. j a va 2 s. c om*/ * * @param path * @return * @throws IOException * @throws de.unibi.techfak.bibiserv.util.codegen.CodeGenParserException */ public static List<String> getClasspathEntriesByPath(String path) throws IOException, CodeGenParserException { try { List<String> tmp = new ArrayList<>(); URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation(); String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8"); JarFile jarFile = new JarFile(jarPath); String prefix = path.startsWith("/") ? path.substring(1) : path; Enumeration<JarEntry> enu = jarFile.entries(); while (enu.hasMoreElements()) { JarEntry je = enu.nextElement(); if (!je.isDirectory()) { String name = je.getName(); if (name.startsWith(prefix)) { tmp.add("/" + name); } } } return tmp; } catch (Exception e) { // maybe we start Main.class not from Jar. } InputStream is = Main.class.getResourceAsStream(path); if (is == null) { throw new CodeGenParserException("Path '" + path + "' not found in Classpath!"); } StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024]; while (is.read(buffer) != -1) { sb.append(new String(buffer, Charset.defaultCharset())); } is.close(); return Arrays.asList(sb.toString().split("\n")) // Convert StringBuilder to individual lines .stream() // Stream the list .filter(line -> line.trim().length() > 0) // Filter out empty lines .map(line -> path + "/" + line) // add path for each entry .collect(Collectors.toList()); // Collect remaining lines into a List again }
From source file:com.cloudera.cdk.data.hbase.tool.SchemaTool.java
/** * Gets the list of HBase Common Avro schema strings from a directory in the * Jar. It recursively searches the directory in the jar to find files that * end in .avsc to locate thos strings./*w ww . ja va 2s . com*/ * * @param jarPath * The path to the jar to search * @param directoryPath * The directory in the jar to find avro schema strings * @return The list of schema strings. */ private List<String> getSchemaStringsFromJar(String jarPath, String directoryPath) { LOG.info("Getting schema strings in: " + directoryPath + ", from jar: " + jarPath); JarFile jar; try { jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new HBaseCommonException(e); } catch (IOException e) { throw new HBaseCommonException(e); } Enumeration<JarEntry> entries = jar.entries(); List<String> schemaStrings = new ArrayList<String>(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.getName().startsWith(directoryPath) && jarEntry.getName().endsWith(".avsc")) { LOG.info("Found schema: " + jarEntry.getName()); InputStream inputStream; try { inputStream = jar.getInputStream(jarEntry); } catch (IOException e) { throw new HBaseCommonException(e); } String schemaString = AvroUtils.inputStreamToString(inputStream); schemaStrings.add(schemaString); } } return schemaStrings; }
From source file:com.izforge.izpack.compiler.packager.impl.Packager.java
/** * Write Packs to primary jar or each to a separate jar. *///from ww w. ja v a 2 s. c o m protected void writePacks() throws Exception { final int num = packsList.size(); sendMsg("Writing " + num + " Pack" + (num > 1 ? "s" : "") + " into installer"); // Map to remember pack number and bytes offsets of back references Map<File, Object[]> storedFiles = new HashMap<File, Object[]>(); // Pack200 files map Map<Integer, File> pack200Map = new HashMap<Integer, File>(); int pack200Counter = 0; // Force UTF-8 encoding in order to have proper ZipEntry names. primaryJarStream.setEncoding("utf-8"); // First write the serialized files and file metadata data for each pack // while counting bytes. int packNumber = 0; IXMLElement root = new XMLElementImpl("packs"); for (PackInfo packInfo : packsList) { Pack pack = packInfo.getPack(); pack.nbytes = 0; if ((pack.id == null) || (pack.id.length() == 0)) { pack.id = pack.name; } // create a pack specific jar if required // REFACTOR : Repare web installer // REFACTOR : Use a mergeManager for each packages that will be added to the main merger // if (packJarsSeparate) { // See installer.Unpacker#getPackAsStream for the counterpart // String name = baseFile.getName() + ".pack-" + pack.id + ".jar"; // packStream = IoHelper.getJarOutputStream(name, baseFile.getParentFile()); // } sendMsg("Writing Pack " + packNumber + ": " + pack.name, PackagerListener.MSG_VERBOSE); // Retrieve the correct output stream org.apache.tools.zip.ZipEntry entry = new org.apache.tools.zip.ZipEntry( RESOURCES_PATH + "packs/pack-" + pack.id); primaryJarStream.putNextEntry(entry); primaryJarStream.flush(); // flush before we start counting ByteCountingOutputStream dos = new ByteCountingOutputStream(outputStream); ObjectOutputStream objOut = new ObjectOutputStream(dos); // We write the actual pack files objOut.writeInt(packInfo.getPackFiles().size()); for (PackFile packFile : packInfo.getPackFiles()) { boolean addFile = !pack.loose; boolean pack200 = false; File file = packInfo.getFile(packFile); if (file.getName().toLowerCase().endsWith(".jar") && info.isPack200Compression() && isNotSignedJar(file)) { packFile.setPack200Jar(true); pack200 = true; } // use a back reference if file was in previous pack, and in // same jar Object[] info = storedFiles.get(file); if (info != null && !packJarsSeparate) { packFile.setPreviousPackFileRef((String) info[0], (Long) info[1]); addFile = false; } objOut.writeObject(packFile); // base info if (addFile && !packFile.isDirectory()) { long pos = dos.getByteCount(); // get the position if (pack200) { /* * Warning! * * Pack200 archives must be stored in separated streams, as the Pack200 unpacker * reads the entire stream... * * See http://java.sun.com/javase/6/docs/api/java/util/jar/Pack200.Unpacker.html */ pack200Map.put(pack200Counter, file); objOut.writeInt(pack200Counter); pack200Counter = pack200Counter + 1; } else { FileInputStream inStream = new FileInputStream(file); long bytesWritten = IoHelper.copyStream(inStream, objOut); inStream.close(); if (bytesWritten != packFile.length()) { throw new IOException("File size mismatch when reading " + file); } } storedFiles.put(file, new Object[] { pack.id, pos }); } // even if not written, it counts towards pack size pack.nbytes += packFile.size(); } // Write out information about parsable files objOut.writeInt(packInfo.getParsables().size()); for (ParsableFile parsableFile : packInfo.getParsables()) { objOut.writeObject(parsableFile); } // Write out information about executable files objOut.writeInt(packInfo.getExecutables().size()); for (ExecutableFile executableFile : packInfo.getExecutables()) { objOut.writeObject(executableFile); } // Write out information about updatecheck files objOut.writeInt(packInfo.getUpdateChecks().size()); for (UpdateCheck updateCheck : packInfo.getUpdateChecks()) { objOut.writeObject(updateCheck); } // Cleanup objOut.flush(); if (!compressor.useStandardCompression()) { outputStream.close(); } primaryJarStream.closeEntry(); // close pack specific jar if required if (packJarsSeparate) { primaryJarStream.closeAlways(); } IXMLElement child = new XMLElementImpl("pack", root); child.setAttribute("nbytes", Long.toString(pack.nbytes)); child.setAttribute("name", pack.name); if (pack.id != null) { child.setAttribute("id", pack.id); } root.addChild(child); packNumber++; } // Now that we know sizes, write pack metadata to primary jar. primaryJarStream.putNextEntry(new org.apache.tools.zip.ZipEntry(RESOURCES_PATH + "packs.info")); ObjectOutputStream out = new ObjectOutputStream(primaryJarStream); out.writeInt(packsList.size()); for (PackInfo packInfo : packsList) { out.writeObject(packInfo.getPack()); } out.flush(); primaryJarStream.closeEntry(); // Pack200 files Pack200.Packer packer = createAgressivePack200Packer(); for (Integer key : pack200Map.keySet()) { File file = pack200Map.get(key); primaryJarStream .putNextEntry(new org.apache.tools.zip.ZipEntry(RESOURCES_PATH + "packs/pack200-" + key)); JarFile jar = new JarFile(file); packer.pack(jar, primaryJarStream); jar.close(); primaryJarStream.closeEntry(); } }
From source file:org.apache.catalina.startup.HostConfig.java
/** * Deploy WAR files.//from w w w. j a v a 2 s. c om */ protected void deployWARs(File appBase, String[] files) { for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; if (deployed.contains(files[i])) continue; File dir = new File(appBase, files[i]); if (files[i].toLowerCase().endsWith(".war")) { deployed.add(files[i]); // Calculate the context path and make sure it is unique String contextPath = "/" + files[i]; int period = contextPath.lastIndexOf("."); if (period >= 0) contextPath = contextPath.substring(0, period); if (contextPath.equals("/ROOT")) contextPath = ""; if (host.findChild(contextPath) != null) continue; // Checking for a nested /META-INF/context.xml JarFile jar = null; JarEntry entry = null; InputStream istream = null; BufferedOutputStream ostream = null; File xml = new File(configBase, files[i].substring(0, files[i].lastIndexOf(".")) + ".xml"); if (!xml.exists()) { try { jar = new JarFile(dir); entry = jar.getJarEntry("META-INF/context.xml"); if (entry != null) { istream = jar.getInputStream(entry); ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; entry = null; jar.close(); jar = null; deployDescriptors(configBase(), configBase.list()); return; } } catch (Exception e) { // Ignore and continue if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ; } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ; } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (Throwable t) { ; } jar = null; } } } if (isUnpackWARs()) { // Expand and deploy this application as a directory log.debug(sm.getString("hostConfig.expand", files[i])); URL url = null; String path = null; try { url = new URL("jar:file:" + dir.getCanonicalPath() + "!/"); path = ExpandWar.expand(host, url); } catch (IOException e) { // JAR decompression failure log.warn(sm.getString("hostConfig.expand.error", files[i])); continue; } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); continue; } try { if (path != null) { url = new URL("file:" + path); ((Deployer) host).install(contextPath, url); } } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); } } else { // Deploy the application in this WAR file log.info(sm.getString("hostConfig.deployJar", files[i])); try { URL url = new URL("file", null, dir.getCanonicalPath()); url = new URL("jar:" + url.toString() + "!/"); ((Deployer) host).install(contextPath, url); } catch (Throwable t) { log.error(sm.getString("hostConfig.deployJar.error", files[i]), t); } } } } }
From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java
@Override public Collection<File> repackageJarList(Collection<File> files) throws IOException { List<String> mainDexList = getMainDexList(files); List<File> jarList = new ArrayList<>(); List<File> folderList = new ArrayList<>(); for (File file : files) { if (file.isDirectory()) { folderList.add(file);// w w w. jav a 2s .c om } else { jarList.add(file); } } File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(), "fastmultidex/" + appVariantContext.getVariantName()); FileUtils.deleteDirectory(dir); dir.mkdirs(); if (!folderList.isEmpty()) { File mergedJar = new File(dir, "jarmerging/combined.jar"); mergedJar.getParentFile().mkdirs(); mergedJar.delete(); mergedJar.createNewFile(); JarMerger jarMerger = new JarMerger(mergedJar); for (File folder : folderList) { jarMerger.addFolder(folder); } jarMerger.close(); if (mergedJar.length() > 0) { jarList.add(mergedJar); } } List<File> result = new ArrayList<>(); File maindexJar = new File(dir, "fastmaindex.jar"); JarOutputStream mainJarOuputStream = new JarOutputStream( new BufferedOutputStream(new FileOutputStream(maindexJar))); for (File jar : jarList) { File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar"); result.add(outJar); JarFile jarFile = new JarFile(jar); JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar))); Enumeration<JarEntry> jarFileEntries = jarFile.entries(); while (jarFileEntries.hasMoreElements()) { JarEntry ze = jarFileEntries.nextElement(); String pathName = ze.getName(); if (mainDexList.contains(pathName)) { copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName); } else { copyStream(jarFile.getInputStream(ze), jos, ze, pathName); } } jarFile.close(); IOUtils.closeQuietly(jos); } IOUtils.closeQuietly(mainJarOuputStream); Collections.sort(result, new NameComparator()); result.add(0, maindexJar); return result; }