List of usage examples for java.util.jar JarInputStream close
public void close() throws IOException
From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java
/** * Find class inside managed jars or hand over the parent * @see java.lang.ClassLoader#findClass(java.lang.String) *//* w w w .java 2s . co m*/ protected Class<?> findClass(String name) throws ClassNotFoundException { // find in already loaded classes to make things shorter Class<?> clazz = findLoadedClass(name); if (clazz != null) return clazz; // check if the class searched for is contained inside managed jars, // otherwise hand over the request to the parent class loader String jarFileName = this.classesJarMapping.get(name); if (StringUtils.isBlank(jarFileName)) { super.findClass(name); } // try to find class inside jar the class name is associated with JarInputStream jarInput = null; try { // open a stream on jar which contains the class jarInput = new JarInputStream(new FileInputStream(jarFileName)); // ... and iterate through all entries JarEntry jarEntry = null; while ((jarEntry = jarInput.getNextJarEntry()) != null) { // extract the name of the jar entry and check if it has suffix '.class' and thus contains // the search for implementation String entryFileName = jarEntry.getName(); if (entryFileName.endsWith(".class")) { // replace slashes by dots, remove suffix and compare the result with the searched for class name entryFileName = entryFileName.substring(0, entryFileName.length() - 6).replace('/', '.'); if (name.equalsIgnoreCase(entryFileName)) { // load bytes from jar entry and define a class over it byte[] data = loadBytes(jarInput); if (data != null) { return defineClass(name, data, 0, data.length); } // if the jar entry does not contain any data, throw an exception throw new ClassNotFoundException("Class '" + name + "' not found"); } } } } catch (IOException e) { // if any io error occurs: throw an exception throw new ClassNotFoundException("Class '" + name + "' not found"); } finally { try { jarInput.close(); } catch (IOException e) { logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } } // if no such class exists, throw an exception throw new ClassNotFoundException("Class [" + name + "] not found"); }
From source file:org.apache.hadoop.hbase.ClassFinder.java
private Set<Class<?>> findClassesFromJar(String jarFileName, String packageName, boolean proceedOnExceptions) throws IOException, ClassNotFoundException, LinkageError { JarInputStream jarFile = null; try {//from ww w . j a v a2s. c o m jarFile = new JarInputStream(new FileInputStream(jarFileName)); } catch (IOException ioEx) { LOG.warn("Failed to look for classes in " + jarFileName + ": " + ioEx); throw ioEx; } Set<Class<?>> classes = new HashSet<Class<?>>(); JarEntry entry = null; try { while (true) { try { entry = jarFile.getNextJarEntry(); } catch (IOException ioEx) { if (!proceedOnExceptions) { throw ioEx; } LOG.warn("Failed to get next entry from " + jarFileName + ": " + ioEx); break; } if (entry == null) { break; // loop termination condition } String className = entry.getName(); if (!className.endsWith(CLASS_EXT)) { continue; } int ix = className.lastIndexOf('/'); String fileName = (ix >= 0) ? className.substring(ix + 1) : className; if (null != this.fileNameFilter && !this.fileNameFilter.isCandidateFile(fileName, className)) { continue; } className = className.substring(0, className.length() - CLASS_EXT.length()).replace('/', '.'); if (!className.startsWith(packageName)) { continue; } Class<?> c = makeClass(className, proceedOnExceptions); if (c != null) { if (!classes.add(c)) { LOG.warn("Ignoring duplicate class " + className); } } } return classes; } finally { jarFile.close(); } }
From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java
/** * Extracts the project files to the project directory. */// w w w .j av a2 s . co m private void extract(URL url) throws Exception { packageDirs = packageName.replaceAll("\\.", "/"); String puTemplate = DIR_TEMPLATES + "/" + template + "/"; int length = puTemplate.length() - 1; BufferedInputStream bis = new BufferedInputStream(url.openStream()); JarInputStream jis = new JarInputStream(bis); JarEntry je; byte[] buf = new byte[1024]; int n; while ((je = jis.getNextJarEntry()) != null) { String jarEntryName = je.getName(); PluginLog.getLog().debug("JAR entry: " + jarEntryName); if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) { continue; } String targetFileName = projectDir + jarEntryName.substring(length); // convert the ${gsGroupPath} to directory targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs); PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName); // read the bytes to the buffer ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); while ((n = jis.read(buf, 0, 1024)) > -1) { byteStream.write(buf, 0, n); } // replace property references with the syntax ${property_name} // to their respective property values. String data = byteStream.toString(); data = StringUtils.replace(data, FILTER_GROUP_ID, packageName); data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName()); data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs); // write the entire converted file content to the destination file. File f = new File(targetFileName); File dir = f.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileWriter writer = new FileWriter(f); writer.write(data); jis.closeEntry(); writer.close(); } jis.close(); }
From source file:com.ecyrd.jspwiki.ui.TemplateManager.java
/** * List all installed i18n language properties * //from www .j a v a 2 s . c om * @param pageContext * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez) * @since 2.7.x */ public Map listLanguages(PageContext pageContext) { LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>(); String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString(); JarInputStream jarStream = null; try { JarEntry entry; InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH); jarStream = new JarInputStream(inputStream); while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX) && name.endsWith(I18NRESOURCE_SUFFIX)) { name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX)); Locale locale = new Locale(name.substring(0, 2), ((name.indexOf("_") == -1) ? "" : name.substring(3, 5))); String defaultLanguage = ""; if (clientLanguage.startsWith(name)) { defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE); } resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage); } } } catch (IOException ioe) { if (log.isDebugEnabled()) log.debug("Could not search jar file '" + I18NRESOURCE_PATH + "'for properties files due to an IOException: \n" + ioe.getMessage()); } finally { if (jarStream != null) { try { jarStream.close(); } catch (IOException e) { } } } return resultMap; }
From source file:org.hecl.jarhack.JarHack.java
/** * The <code>substHecl</code> method takes the filenames of two * .jar's - one as input, the second as output, in addition to the * name of the application. Where it counts, the old name (Hecl, * usually) is overridden with the new name, and the new .jar file * is written to the specified outfile. Via the iconname argument * it is also possible to specify a new icon file to use. * * @param infile a <code>FileInputStream</code> value * @param outfile a <code>String</code> value * @param newname a <code>String</code> value * @param iconname a <code>String</code> value * @exception IOException if an error occurs *//*from w ww . j a va2 s.c o m*/ public static void substHecl(InputStream infile, String outfile, String newname, String iconname, String scriptfile) throws IOException { JarInputStream jif = new JarInputStream(infile); Manifest mf = jif.getManifest(); Attributes attrs = mf.getMainAttributes(); Set keys = attrs.keySet(); Iterator it = keys.iterator(); while (it.hasNext()) { Object key = it.next(); Object value = attrs.get(key); String keyname = key.toString(); /* These are the three cases that interest us in * particular, where we need to make changes. */ if (keyname.equals("MIDlet-Name")) { attrs.putValue(keyname, newname); } else if (keyname.equals("MIDlet-1")) { String valuestr = value.toString(); /* FIXME - the stringsplit method is used for older * versions of GCJ. Once newer versions are common, * it can go away. Or not - it works just fine. */ String properties[] = stringsplit(valuestr, ", "); attrs.putValue(keyname, newname + ", " + properties[1] + ", " + properties[2]); } else if (keyname.equals("MicroEdition-Configuration")) { cldcversion = value.toString(); } else if (keyname.equals("MicroEdition-Profile")) { midpversion = value.toString(); } else if (keyname.equals("MIDlet-Jar-URL")) { attrs.put(key, newname + ".jar"); } } JarOutputStream jof = new JarOutputStream(new FileOutputStream(outfile), mf); byte[] buf = new byte[4096]; /* Go through the various entries. */ JarEntry entry; int read; while ((entry = jif.getNextJarEntry()) != null) { /* Don't copy the manifest file. */ if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; /* Insert our own icon */ if (iconname != null && "Hecl.png".equals(entry.getName())) { jof.putNextEntry(new JarEntry("Hecl.png")); FileInputStream inf = new FileInputStream(iconname); while ((read = inf.read(buf)) != -1) { jof.write(buf, 0, read); } inf.close(); } /* Insert our own copy of the script file. */ else if ("script.hcl".equals(entry.getName())) { jof.putNextEntry(new JarEntry("script.hcl")); FileInputStream inf = new FileInputStream(scriptfile); while ((read = inf.read(buf)) != -1) { jof.write(buf, 0, read); } inf.close(); } else { /* Otherwise, just copy the entry. */ jof.putNextEntry(entry); while ((read = jif.read(buf)) != -1) { jof.write(buf, 0, read); } } jof.closeEntry(); } jof.flush(); jof.close(); jif.close(); }
From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java
/** * Initializes the class loader by pointing it to folder holding managed JAR files * @param componentFolder//from ww w. j a v a 2 s .c o m * @param componentJarIdentifier file to search for in component JAR which identifies it as component JAR * @throws IOException * @throws RequiredInputMissingException */ public void initialize(final String componentFolder, final String componentJarIdentifier) throws IOException, RequiredInputMissingException { /////////////////////////////////////////////////////////////////// // validate input if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'"); File folder = new File(componentFolder); if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder"); File[] jarFiles = folder.listFiles(); if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'"); // /////////////////////////////////////////////////////////////////// logger.info("Initializing component classloader [componentJarIdentifier=" + componentJarIdentifier + ", folder=" + componentFolder + "]"); // step through jar files, ensure it is a file and iterate through its contents for (File jarFile : jarFiles) { if (jarFile.isFile()) { JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); // if the current file references a class implementation, replace slashes by dots, strip // away the class suffix and add a reference to the classes-2-jar mapping if (StringUtils.endsWith(jarEntryName, ".class")) { jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); this.classesJarMapping.put(jarEntryName, jarFile.getAbsolutePath()); } else { // if the current file references a resource, check if it is the identifier file which // marks this jar to contain component implementation if (StringUtils.equalsIgnoreCase(jarEntryName, componentJarIdentifier)) this.componentJarFiles.add(jarFile.getAbsolutePath()); // ...and add a mapping for resource to jar file as well this.resourcesJarMapping.put(jarEntryName, jarFile.getAbsolutePath()); } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } } } } // load classes from jars marked component files and extract the deployment descriptors for (String cjf : this.componentJarFiles) { logger.info("Attempting to load pipeline components located in '" + cjf + "'"); // open JAR file and iterate through it's contents JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(cjf)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { // fetch name of current entry and ensure it is a class file String jarEntryName = jarEntry.getName(); if (jarEntryName.endsWith(".class")) { // replace slashes by dots and strip away '.class' suffix jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); Class<?> c = loadClass(jarEntryName); AsapComponent pc = c.getAnnotation(AsapComponent.class); if (pc != null) { this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()), new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(), pc.description())); logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name() + ", version=" + pc.version() + "]"); ; } } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + cjf + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + cjf + "'. Error: " + e.getMessage()); } } } }
From source file:org.apache.pluto.util.assemble.ear.EarAssembler.java
public void assembleInternal(AssemblerConfig config) throws UtilityException, IOException { File source = config.getSource(); File dest = config.getDestination(); JarInputStream earIn = new JarInputStream(new FileInputStream(source)); JarOutputStream earOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest), BUFLEN)); try {/*w w w . j a v a2s .c o m*/ JarEntry entry; // Iterate over entries in the EAR archive while ((entry = earIn.getNextJarEntry()) != null) { // If a war file is encountered, assemble it into a // ByteArrayOutputStream and write the assembled bytes // back to the EAR archive. if (entry.getName().toLowerCase().endsWith(".war")) { if (LOG.isDebugEnabled()) { LOG.debug("Assembling war file " + entry.getName()); } // keep a handle to the AssemblySink so we can write out // JarEntry metadata and the bytes later. AssemblySink warBytesOut = getAssemblySink(config, entry); JarOutputStream warOut = new JarOutputStream(warBytesOut); JarStreamingAssembly.assembleStream(new JarInputStream(earIn), warOut, config.getDispatchServletClass()); JarEntry warEntry = new JarEntry(entry); // Write out the assembled JarEntry metadata warEntry.setSize(warBytesOut.getByteCount()); warEntry.setCrc(warBytesOut.getCrc()); warEntry.setCompressedSize(-1); earOut.putNextEntry(warEntry); // Write out the assembled WAR file to the EAR warBytesOut.writeTo(earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } else { earOut.putNextEntry(entry); IOUtils.copy(earIn, earOut); earOut.flush(); earOut.closeEntry(); earIn.closeEntry(); } } } finally { earOut.close(); earIn.close(); } }
From source file:com.flexive.shared.FxSharedUtils.java
/** * This method returns all entries in a JarInputStream for a given search pattern within the jar as a Map * having the filename as the key and the file content as its respective value (String). * The boolean flag "isFile" marks the search pattern as a file, otherwise the pattern will be treated as * a path to be found in the jarStream//w w w . j a v a2s. co m * A successful search either returns a map of all entries for a given path or a map of all entries for a given file * (again, depending on the "isFile" flag). * Null will be returned if no occurrences of the search pattern were found. * * @param jarStream the given JarInputStream * @param searchPattern the pattern to be examined as a String * @param isFile if true, the searchPattern is treated as a file name, if false, the searchPattern will be treated as a path * @return Returns all entries found for the given search pattern as a Map<String, String>, or null if no matches were found * @throws IOException on I/O errors */ public static Map<String, String> getContentsFromJarStream(JarInputStream jarStream, String searchPattern, boolean isFile) throws IOException { Map<String, String> jarContents = new HashMap<String, String>(); int found = 0; try { if (jarStream != null) { JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { if (isFile) { if (!entry.isDirectory() && entry.getName().endsWith(searchPattern)) { final String name = entry.getName().substring(entry.getName().lastIndexOf("/") + 1); jarContents.put(name, readFromJarEntry(jarStream, entry)); found++; } } else { if (!entry.isDirectory() && entry.getName().startsWith(searchPattern)) { jarContents.put(entry.getName(), readFromJarEntry(jarStream, entry)); found++; } } } if (LOG.isDebugEnabled()) { LOG.debug("Found " + found + " entries in the JarInputStream for the pattern " + searchPattern); } } } finally { if (jarStream != null) { try { jarStream.close(); } catch (IOException e) { LOG.warn("Failed to close stream: " + e.getMessage(), e); } } else { LOG.warn("JarInputStream parameter was null, no search performed"); } } return jarContents.isEmpty() ? null : jarContents; }
From source file:org.jenkins.tools.test.PluginCompatTester.java
/** * Scans through a WAR file, accumulating plugin information * @param war WAR to scan// w w w. j a v a 2 s.c om * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION * @return Update center data * @throws IOException */ private UpdateSite.Data scanWAR(File war, Map<String, String> pluginGroupIds) throws IOException { JSONObject top = new JSONObject(); top.put("id", DEFAULT_SOURCE_ID); JSONObject plugins = new JSONObject(); JarFile jf = new JarFile(war); if (pluginGroupIds == null) { pluginGroupIds = new HashMap<String, String>(); } try { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); Matcher m = Pattern.compile("WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9.]+)?(?:-SNAPSHOT)?)[.]jar") .matcher(name); if (m.matches()) { if (top.has("core")) { throw new IOException(">1 jenkins-core.jar in " + war); } top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1)) .accumulate("url", "")); } m = Pattern.compile("WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi").matcher(name); if (m.matches()) { JSONObject plugin = new JSONObject().accumulate("url", ""); InputStream is = jf.getInputStream(entry); try { JarInputStream jis = new JarInputStream(is); try { Manifest manifest = jis.getManifest(); String shortName = manifest.getMainAttributes().getValue("Short-Name"); if (shortName == null) { shortName = manifest.getMainAttributes().getValue("Extension-Name"); if (shortName == null) { shortName = m.group(1); } } plugin.put("name", shortName); pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id")); plugin.put("version", manifest.getMainAttributes().getValue("Plugin-Version")); plugin.put("url", "jar:" + war.toURI() + "!/" + name); JSONArray dependenciesA = new JSONArray(); String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional for (String pair : dependencies.replace(";resolution:=optional", "").split(",")) { String[] nameVer = pair.split(":"); assert nameVer.length == 2; dependenciesA.add(new JSONObject().accumulate("name", nameVer[0]) .accumulate("version", nameVer[1]) ./* we do care about even optional deps here */accumulate("optional", "false")); } } plugin.accumulate("dependencies", dependenciesA); plugins.put(shortName, plugin); } finally { jis.close(); } } finally { is.close(); } } } } finally { jf.close(); } top.put("plugins", plugins); if (!top.has("core")) { throw new IOException("no jenkins-core.jar in " + war); } System.out.println("Scanned contents of " + war + ": " + top); return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top); }
From source file:org.apache.geode.internal.DeployedJar.java
/** * Scan the JAR file and attempt to register any function classes found. *//* w w w .jav a 2 s. co m*/ public synchronized void registerFunctions() throws ClassNotFoundException { final boolean isDebugEnabled = logger.isDebugEnabled(); if (isDebugEnabled) { logger.debug("Registering functions with DeployedJar: {}", this); } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.getJarContent()); JarInputStream jarInputStream = null; try { Collection<String> functionClasses = findFunctionsInThisJar(); jarInputStream = new JarInputStream(byteArrayInputStream); JarEntry jarEntry = jarInputStream.getNextJarEntry(); while (jarEntry != null) { if (jarEntry.getName().endsWith(".class")) { final String className = PATTERN_SLASH.matcher(jarEntry.getName()).replaceAll("\\.") .substring(0, jarEntry.getName().length() - 6); if (functionClasses.contains(className)) { if (isDebugEnabled) { logger.debug("Attempting to load class: {}, from JAR file: {}", jarEntry.getName(), this.file.getAbsolutePath()); } try { Class<?> clazz = ClassPathLoader.getLatest().forName(className); Collection<Function> registerableFunctions = getRegisterableFunctionsFromClass(clazz); for (Function function : registerableFunctions) { FunctionService.registerFunction(function); if (isDebugEnabled) { logger.debug("Registering function class: {}, from JAR file: {}", className, this.file.getAbsolutePath()); } this.registeredFunctions.add(function); } } catch (ClassNotFoundException | NoClassDefFoundError cnfex) { logger.error("Unable to load all classes from JAR file: {}", this.file.getAbsolutePath(), cnfex); throw cnfex; } } else { if (isDebugEnabled) { logger.debug("No functions found in class: {}, from JAR file: {}", jarEntry.getName(), this.file.getAbsolutePath()); } } } jarEntry = jarInputStream.getNextJarEntry(); } } catch (IOException ioex) { logger.error("Exception when trying to read class from ByteArrayInputStream", ioex); } finally { if (jarInputStream != null) { try { jarInputStream.close(); } catch (IOException ioex) { logger.error("Exception attempting to close JAR input stream", ioex); } } } }