List of usage examples for java.util.jar JarInputStream close
public void close() throws IOException
From source file:com.izforge.izpack.compiler.helper.CompilerHelper.java
/** * Returns the qualified class name for the given class. This method expects as the url param a * jar file which contains the given class. It scans the zip entries of the jar file. * * @param url url of the jar file which contains the class * @param className short name of the class for which the full name should be resolved * @return full qualified class name//w w w .j a va2s .c om * @throws IOException if the jar cannot be read */ public String getFullClassName(URL url, String className) throws IOException { JarInputStream jis = new JarInputStream(url.openStream()); ZipEntry zentry; while ((zentry = jis.getNextEntry()) != null) { String name = zentry.getName(); int lastPos = name.lastIndexOf(".class"); if (lastPos < 0) { continue; // No class file. } name = name.replace('/', '.'); int pos = -1; int nonCasePos = -1; if (className != null) { pos = name.indexOf(className); nonCasePos = name.toLowerCase().indexOf(className.toLowerCase()); } if (pos != -1 && name.length() == pos + className.length() + 6) // "Main" class found { jis.close(); return (name.substring(0, lastPos)); } if (nonCasePos != -1 && name.length() == nonCasePos + className.length() + 6) // "Main" class with different case found { throw new IllegalArgumentException("Fatal error! The declared panel name in the xml file (" + className + ") differs in case to the founded class file (" + name + ")."); } } jis.close(); return (null); }
From source file:org.rhq.core.clientapi.descriptor.PluginTransformer.java
private String getVersionFromPluginJarManifest(URL pluginJarUrl) throws IOException { JarInputStream jarInputStream = new JarInputStream(pluginJarUrl.openStream()); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { // BZ 682116 (ips, 03/25/11): The manifest file is not in the standard place as the 2nd entry of the JAR, // but we want to be flexible and support JARs that have a manifest file somewhere else, so scan the entire // JAR for one. JarEntry jarEntry;/* w w w .ja va 2 s. com*/ while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (JarFile.MANIFEST_NAME.equalsIgnoreCase(jarEntry.getName())) { manifest = new Manifest(jarInputStream); break; } } } try { jarInputStream.close(); } catch (IOException e) { LOG.error("Failed to close plugin jar input stream for plugin jar [" + pluginJarUrl + "].", e); } if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); return attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION); } else { return null; } }
From source file:com.cloudera.sqoop.orm.TestClassWriter.java
/** * Run a test to verify that we can generate code and it emits the output * files where we expect them.//from w ww .ja v a 2s . c om */ private void runGenerationTest(String[] argv, String classNameToCheck) { File codeGenDirFile = new File(CODE_GEN_DIR); File classGenDirFile = new File(JAR_GEN_DIR); try { options = new ImportTool().parseArguments(argv, null, options, true); } catch (Exception e) { LOG.error("Could not parse options: " + e.toString()); } CompilationManager compileMgr = new CompilationManager(options); ClassWriter writer = new ClassWriter(options, manager, HsqldbTestServer.getTableName(), compileMgr); try { writer.generate(); compileMgr.compile(); compileMgr.jar(); } catch (IOException ioe) { LOG.error("Got IOException: " + ioe.toString()); fail("Got IOException: " + ioe.toString()); } String classFileNameToCheck = classNameToCheck.replace('.', File.separatorChar); LOG.debug("Class file to check for: " + classFileNameToCheck); // Check that all the files we expected to generate (.java, .class, .jar) // exist. File tableFile = new File(codeGenDirFile, classFileNameToCheck + ".java"); assertTrue("Cannot find generated source file for table!", tableFile.exists()); LOG.debug("Found generated source: " + tableFile); File tableClassFile = new File(classGenDirFile, classFileNameToCheck + ".class"); assertTrue("Cannot find generated class file for table!", tableClassFile.exists()); LOG.debug("Found generated class: " + tableClassFile); File jarFile = new File(compileMgr.getJarFilename()); assertTrue("Cannot find compiled jar", jarFile.exists()); LOG.debug("Found generated jar: " + jarFile); // check that the .class file made it into the .jar by enumerating // available entries in the jar file. boolean foundCompiledClass = false; try { JarInputStream jis = new JarInputStream(new FileInputStream(jarFile)); LOG.debug("Jar file has entries:"); while (true) { JarEntry entry = jis.getNextJarEntry(); if (null == entry) { // no more entries. break; } if (entry.getName().equals(classFileNameToCheck + ".class")) { foundCompiledClass = true; LOG.debug(" * " + entry.getName()); } else { LOG.debug(" " + entry.getName()); } } jis.close(); } catch (IOException ioe) { fail("Got IOException iterating over Jar file: " + ioe.toString()); } assertTrue("Cannot find .class file " + classFileNameToCheck + ".class in jar file", foundCompiledClass); LOG.debug("Found class in jar - test success!"); }
From source file:org.bimserver.plugins.classloaders.JarClassLoader.java
public JarClassLoader(ClassLoader parentClassLoader, File jarFile) throws FileNotFoundException, IOException { super(parentClassLoader); this.jarFile = jarFile; JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); 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 {/*www .j a v a 2 s. c o m*/ // 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(); } jarInputStream.close(); }
From source file:org.bimserver.plugins.classloaders.MemoryJarClassLoader.java
public MemoryJarClassLoader(ClassLoader parentClassLoader, File jarFile) throws FileNotFoundException, IOException { super(parentClassLoader); this.jarFile = jarFile; JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); 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 {//from ww w .j a va 2 s. co m // 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(); } jarInputStream.close(); }
From source file:com.sachviet.bookman.server.util.ResolverUtil.java
public void loadImplementationsInJar(String parent, URL jarfile, Test... tests) { JarInputStream jarStream = null; try {/*from ww w .j a v a 2s . c o m*/ JarEntry entry; jarStream = new JarInputStream(jarfile.openStream()); while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { //$NON-NLS-1$ addIfMatching(name, tests); } } } catch (IOException ioe) { LOG.trace("Could not search jar file \\\'" + jarfile //$NON-NLS-1$ + "\\\' for classes matching criteria: " + tests //$NON-NLS-1$ + " due to an IOException", ioe); //$NON-NLS-1$ } finally { if (jarStream != null) try { jarStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java
private void chooseArchive(IFile jarIFile, File jarFile) { try {/*w w w . j av a2 s . c o m*/ // prepare path boolean canFile = jarIFile == null; m_jarPath = canFile ? jarFile.getAbsolutePath() : jarIFile.getLocation().toPortableString(); // load elements over manifest boolean ignoreManifest = m_ignoreManifestButton.getSelection(); m_elements = Collections.emptyList(); if (!ignoreManifest) { JarInputStream jarStream = new JarInputStream( canFile ? new FileInputStream(jarFile) : jarIFile.getContents(true)); m_elements = extractElementsFromJarByManifest(jarStream); jarStream.close(); } // check load all elements if (ignoreManifest || m_elements.isEmpty()) { if (!ignoreManifest) { String message = MessageFormat.format(Messages.ImportArchiveDialog_hasManifestMessage, m_jarPath); ignoreManifest = MessageDialog.openQuestion(getShell(), Messages.ImportArchiveDialog_hasManifestTitle, message); } if (ignoreManifest) { JarInputStream jarStream = new JarInputStream( canFile ? new FileInputStream(jarFile) : jarIFile.getContents(true)); m_elements = extractElementsFromJarAllClasses(jarStream); jarStream.close(); } } // sets elements m_classesViewer.setInput(m_elements.toArray()); // handle jar combo int removeIndex = m_fileArchiveCombo.indexOf(m_jarPath); if (removeIndex != -1) { m_fileArchiveCombo.remove(removeIndex); } m_fileArchiveCombo.add(m_jarPath, 0); int archiveCount = m_fileArchiveCombo.getItemCount(); if (archiveCount > JAR_COMBO_SIZE) { m_fileArchiveCombo.remove(JAR_COMBO_SIZE, archiveCount - 1); } if (!m_fileArchiveCombo.getText().equals(m_jarPath)) { m_fileArchiveCombo.setText(m_jarPath); m_fileArchiveCombo.setSelection(new Point(0, m_jarPath.length())); } // handle category if (m_elements.isEmpty()) { m_categoryText.setText(""); } else { // convert 'foo.jar' to 'foo' String categoryName = canFile ? jarFile.getName() : jarIFile.getName(); m_categoryText.setText(categoryName.substring(0, categoryName.length() - JAR_SUFFIX.length())); } } catch (Throwable t) { m_jarPath = null; m_elements = Collections.emptyList(); m_classesViewer.setInput(ArrayUtils.EMPTY_OBJECT_ARRAY); m_categoryText.setText(""); } finally { calculateFinish(); } }
From source file:org.jahia.modules.serversettings.portlets.BasePortletHelper.java
/** * Returns a file descriptor for the modified (prepared) portlet WAR file. * /*from w w w .ja v a 2 s. c om*/ * @param sourcePortletWar * the source portlet WAR file * @return a file descriptor for the modified (prepared) portlet WAR file * @throws IOException * in case of processing error */ public File process(File sourcePortletWar) throws IOException { JarFile jar = new JarFile(sourcePortletWar); File dest = new File(FilenameUtils.getFullPathNoEndSeparator(sourcePortletWar.getPath()), FilenameUtils.getBaseName(sourcePortletWar.getName()) + ".war"); try { boolean needsServerSpecificProcessing = needsProcessing(jar); if (portletTldsPresent(jar) && !needsServerSpecificProcessing) { return sourcePortletWar; } jar.close(); final JarInputStream jarIn = new JarInputStream(new FileInputStream(sourcePortletWar)); final Manifest manifest = jarIn.getManifest(); final JarOutputStream jarOut; if (manifest != null) { jarOut = new JarOutputStream(new FileOutputStream(dest), manifest); } else { jarOut = new JarOutputStream(new FileOutputStream(dest)); } try { copyEntries(jarIn, jarOut); process(jarIn, jarOut); if (!hasPortletTld) { addToJar("META-INF/portlet-resources/portlet.tld", "WEB-INF/portlet.tld", jarOut); } if (!hasPortlet2Tld) { addToJar("META-INF/portlet-resources/portlet_2_0.tld", "WEB-INF/portlet_2_0.tld", jarOut); } } finally { jarIn.close(); jarOut.close(); FileUtils.deleteQuietly(sourcePortletWar); } return dest; } finally { jar.close(); } }
From source file:com.asual.summer.bundle.BundleDescriptorMojo.java
public void execute() throws MojoExecutionException { try {/*w w w. j av a 2 s . c o m*/ String webXml = "WEB-INF/web.xml"; File warDir = new File(buildDirectory, finalName); File warFile = new File(buildDirectory, finalName + ".war"); File webXmlFile = new File(warDir, webXml); FileUtils.copyFile(new File(basedir, "src/main/webapp/" + webXml), webXmlFile); Configuration[] configurations = new Configuration[] { new WebXmlConfiguration(), new FragmentConfiguration() }; WebAppContext context = new WebAppContext(); context.setDefaultsDescriptor(null); context.setDescriptor(webXmlFile.getAbsolutePath()); context.setConfigurations(configurations); for (Artifact artifact : artifacts) { JarInputStream in = new JarInputStream(new FileInputStream(artifact.getFile())); while (true) { ZipEntry entry = in.getNextEntry(); if (entry != null) { if ("META-INF/web-fragment.xml".equals(entry.getName())) { Resource fragment = Resource .newResource("file:" + artifact.getFile().getAbsolutePath()); context.getMetaData().addFragment(fragment, Resource .newResource("jar:" + fragment.getURL() + "!/META-INF/web-fragment.xml")); context.getMetaData().addWebInfJar(fragment); } } else { break; } } in.close(); } for (int i = 0; i < configurations.length; i++) { configurations[i].preConfigure(context); } for (int i = 0; i < configurations.length; i++) { configurations[i].configure(context); } for (int i = 0; i < configurations.length; i++) { configurations[i].postConfigure(context); } Descriptor descriptor = context.getMetaData().getWebXml(); Node root = descriptor.getRoot(); List<Object> nodes = new ArrayList<Object>(); List<FragmentDescriptor> fragmentDescriptors = context.getMetaData().getOrderedFragments(); for (FragmentDescriptor fd : fragmentDescriptors) { for (int i = 0; i < fd.getRoot().size(); i++) { Object el = fd.getRoot().get(i); if (el instanceof Node && ((Node) el).getTag().matches("^name|ordering$")) { continue; } nodes.add(el); } } root.addAll(nodes); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(warDir, webXml))); writer.write(root.toString()); writer.close(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(warFile)); zip(warDir, warDir, zos); zos.close(); } catch (Exception e) { getLog().error(e.getMessage(), e); throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java
/** * Loads a plugin descriptor from the given plugin jar and returns it. If the given jar does not * have a server plugin descriptor, <code>null</code> will be returned, meaning this is not * a server plugin jar./* www . j a v a 2 s . c om*/ * * @param pluginJarFileUrl URL to a plugin jar file * @return the plugin descriptor found in the given plugin jar file, or <code>null</code> if there * is no plugin descriptor in the jar file * @throws Exception if failed to parse the descriptor file found in the plugin jar */ public static ServerPluginDescriptorType loadPluginDescriptorFromUrl(URL pluginJarFileUrl) throws Exception { final Log logger = LogFactory.getLog(ServerPluginDescriptorUtil.class); if (pluginJarFileUrl == null) { throw new Exception("A valid plugin JAR URL must be supplied."); } if (logger.isDebugEnabled()) { logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]..."); } testPluginJarIsReadable(pluginJarFileUrl); JarInputStream jis = null; JarEntry descriptorEntry = null; try { jis = new JarInputStream(pluginJarFileUrl.openStream()); JarEntry nextEntry = jis.getNextJarEntry(); while (nextEntry != null && descriptorEntry == null) { if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) { descriptorEntry = nextEntry; } else { jis.closeEntry(); nextEntry = jis.getNextJarEntry(); } } ServerPluginDescriptorType pluginDescriptor = null; if (descriptorEntry != null) { Unmarshaller unmarshaller = null; try { unmarshaller = getServerPluginDescriptorUnmarshaller(); Object jaxbElement = unmarshaller.unmarshal(jis); pluginDescriptor = ((JAXBElement<? extends ServerPluginDescriptorType>) jaxbElement).getValue(); } finally { if (unmarshaller != null) { ValidationEventCollector validationEventCollector = (ValidationEventCollector) unmarshaller .getEventHandler(); logValidationEvents(pluginJarFileUrl, validationEventCollector); } } } return pluginDescriptor; } catch (Exception e) { throw new Exception("Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH + "] found in plugin jar at [" + pluginJarFileUrl + "]", e); } finally { if (jis != null) { try { jis.close(); } catch (Exception e) { logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e); } } } }