List of usage examples for java.util.jar JarFile getEntry
public ZipEntry getEntry(String name)
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlSourceArchive() throws IOException { File sourceArchiveFile = getSourceArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6"); sourceArchiveFile.delete();/* w w w. j a v a 2 s . co m*/ assertFalse(sourceArchiveFile.exists()); // compile one file compile("modules/single/module.ceylon"); // make sure it was created assertTrue(sourceArchiveFile.exists()); JarFile sourceArchive = new JarFile(sourceArchiveFile); assertEquals(2, countEntries(sourceArchive)); ZipEntry moduleClass = sourceArchive .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/module.ceylon"); assertNotNull(moduleClass); ZipEntry moduleClassDir = sourceArchive .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/"); assertNotNull(moduleClassDir); sourceArchive.close(); // now compile another file compile("modules/single/subpackage/Subpackage.ceylon"); // MUST reopen it sourceArchive = new JarFile(sourceArchiveFile); assertEquals(4, countEntries(sourceArchive)); ZipEntry subpackageClass = sourceArchive .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/Subpackage.ceylon"); assertNotNull(subpackageClass); ZipEntry subpackageClassDir = sourceArchive .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/subpackage/"); assertNotNull(subpackageClassDir); sourceArchive.close(); }
From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java
private void readVersionInformation() { InputStream stream = null;/*from w w w. j a v a2 s . c om*/ try { JarFile tgfmJar = null; URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation") .getResource("ConfigOperation.class"); JarURLConnection c = (JarURLConnection) jarname.openConnection(); tgfmJar = c.getJarFile(); stream = tgfmJar.getInputStream(tgfmJar.getEntry("META-INF/MANIFEST.MF")); Manifest manifest = new Manifest(stream); Attributes attributes = manifest.getMainAttributes(); for (Object attributeName : attributes.keySet()) { if (((Attributes.Name) attributeName).toString().equals(("Implementation-Version"))) { ConfigSettings.SOFTWARE_VERSION = attributes.getValue("Implementation-Version"); } else if (((Attributes.Name) attributeName).toString().equals(("Built-Date"))) { ConfigSettings.SOFTWARE_BUILD_DATE = attributes.getValue("Built-Date"); } LogManager .debug(attributeName + ": " + attributes.getValue((Attributes.Name) attributeName) + "\n"); } stream.close(); } catch (Exception e) { LogManager.error("Failed to retreive version information.", e); } finally { try { stream.close(); } catch (Exception e) { } } }
From source file:org.apache.jasper.compiler.TagLibraryInfoImpl.java
/** * Constructor./*from w w w. j a v a2 s . c o m*/ */ public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn, String[] location, ErrorDispatcher err) throws JasperException { super(prefix, uriIn); this.ctxt = ctxt; this.parserController = pc; this.err = err; InputStream in = null; JarFile jarFile = null; if (location == null) { // The URI points to the TLD itself or to a JAR file in which the // TLD is stored location = generateTLDLocation(uri, ctxt); } try { if (!location[0].endsWith("jar")) { // Location points to TLD file try { in = getResourceAsStream(location[0]); if (in == null) { throw new FileNotFoundException(location[0]); } } catch (FileNotFoundException ex) { err.jspError("jsp.error.file.not.found", location[0]); } parseTLD(ctxt, location[0], in, null); // Add TLD to dependency list PageInfo pageInfo = ctxt.createCompiler().getPageInfo(); if (pageInfo != null) { pageInfo.addDependant(location[0]); } } else { // Tag library is packaged in JAR file try { URL jarFileUrl = new URL("jar:" + location[0] + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); jarFile = conn.getJarFile(); ZipEntry jarEntry = jarFile.getEntry(location[1]); in = jarFile.getInputStream(jarEntry); parseTLD(ctxt, location[0], in, jarFileUrl); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString()); } } } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { } } } }
From source file:org.tinygroup.jspengine.compiler.TagLibraryInfoImpl.java
/** * Constructor which builds a TagLibraryInfoImpl by parsing a TLD. *//*from ww w .ja v a 2s .c o m*/ public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn, String[] location, ErrorDispatcher err) throws JasperException { super(prefix, uriIn); this.ctxt = ctxt; this.parserController = pc; this.pageInfo = pc.getCompiler().getPageInfo(); this.err = err; InputStream in = null; JarFile jarFile = null; if (location == null) { // The URI points to the TLD itself or to a JAR file in which the // TLD is stored location = generateTLDLocation(uri, ctxt); } try { if (!location[0].endsWith("jar")) { // Location points to TLD file try { in = getResourceAsStream(location[0]); if (in == null) { throw new FileNotFoundException(location[0]); } } catch (FileNotFoundException ex) { err.jspError("jsp.error.file.not.found", location[0]); } parseTLD(ctxt, location[0], in, null); // Add TLD to dependency list PageInfo pageInfo = ctxt.createCompiler(false).getPageInfo(); if (pageInfo != null) { pageInfo.addDependant(location[0]); } } else { // Tag library is packaged in JAR file try { URL jarFileUrl = new URL("jar:" + location[0] + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); jarFile = conn.getJarFile(); ZipEntry jarEntry = jarFile.getEntry(location[1]); in = jarFile.getInputStream(jarEntry); parseTLD(ctxt, location[0], in, jarFileUrl); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString()); } } } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { } } } }
From source file:org.apache.openejb.config.DeploymentLoader.java
private Class<? extends DeploymentModule> checkAnnotations(final URL urls, final ClassLoader classLoader, final boolean scanPotentialEjbModules, final boolean scanPotentialClientModules) { Class<? extends DeploymentModule> cls = null; if (scanPotentialEjbModules || scanPotentialClientModules) { final AnnotationFinder classFinder = new AnnotationFinder(classLoader, urls); final Set<Class<? extends DeploymentModule>> otherTypes = new LinkedHashSet<Class<? extends DeploymentModule>>(); final AnnotationFinder.Filter filter = new AnnotationFinder.Filter() { final String packageName = LocalClient.class.getName().replace("LocalClient", ""); @Override/*from w ww . j av a2 s . c om*/ public boolean accept(final String annotationName) { if (scanPotentialClientModules && annotationName.startsWith(packageName)) { if (LocalClient.class.getName().equals(annotationName)) { otherTypes.add(ClientModule.class); } if (RemoteClient.class.getName().equals(annotationName)) { otherTypes.add(ClientModule.class); } } else if (scanPotentialEjbModules) { if (annotationName.startsWith("javax.ejb.")) { if ("javax.ejb.Stateful".equals(annotationName)) { return true; } if ("javax.ejb.Stateless".equals(annotationName)) { return true; } if ("javax.ejb.Singleton".equals(annotationName)) { return true; } if ("javax.ejb.MessageDriven".equals(annotationName)) { return true; } } else if (scanManagedBeans && "javax.annotation.ManagedBean".equals(annotationName)) { return true; } } return false; } }; if (classFinder.find(filter)) { cls = EjbModule.class; // if it is a war just throw an error try { final File ar = URLs.toFile(urls); if (!ar.isDirectory() && !ar.getName().endsWith("ar")) { // guess no archive extension, check it is not a hidden war final JarFile war = new JarFile(ar); final ZipEntry entry = war.getEntry("WEB-INF/"); if (entry != null) { logger.warning("you deployed " + urls.toExternalForm() + ", it seems it is a war with no extension, please rename it"); } } } catch (final Exception ignored) { // no-op } } if (otherTypes.size() > 0) { // We may want some ordering/sorting if we add more type scanning cls = otherTypes.iterator().next(); } } return cls; }
From source file:mobac.mapsources.loader.MapPackManager.java
/** * Verifies the class file signatures of the specified map pack * //from www .j av a 2s .co m * @param mapPackFile * @throws IOException * @throws CertificateException */ public void testMapPack(File mapPackFile) throws IOException, CertificateException { String fileName = mapPackFile.getName(); JarFile jf = new JarFile(mapPackFile, true); try { Enumeration<JarEntry> it = jf.entries(); while (it.hasMoreElements()) { JarEntry entry = it.nextElement(); // We verify only class files if (!entry.getName().endsWith(".class")) continue; // directory or other entry // Get the input stream (triggers) the signature verification for the specific class Utilities.readFully(jf.getInputStream(entry)); if (entry.getCodeSigners() == null) throw new CertificateException("Unsigned class file found: " + entry.getName()); CodeSigner signer = entry.getCodeSigners()[0]; List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates(); if (cp.size() > 1) throw new CertificateException("Signature certificate not accepted: " + "certificate path contains more than one certificate"); // Compare the used certificate with the mapPack certificate if (!mapPackCert.equals(cp.get(0))) throw new CertificateException( "Signature certificate not accepted: " + "not the MapPack signer certificate"); } Manifest mf = jf.getManifest(); Attributes a = mf.getMainAttributes(); String mpv = a.getValue("MapPackVersion"); if (mpv == null) throw new IOException("MapPackVersion info missing!"); int mapPackVersion = Integer.parseInt(mpv); if (requiredMapPackVersion != mapPackVersion) throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version."); ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource"); if (entry == null) throw new IOException("MapSources services list is missing in file " + fileName); } finally { jf.close(); } }
From source file:osmcd.mapsources.loader.MapPackManager.java
/** * Verifies the class file signatures of the specified map pack * //from w w w . jav a 2s. c om * @param mapPackFile * @throws IOException * @throws CertificateException */ public void testMapPack(File mapPackFile) throws IOException, CertificateException { String fileName = mapPackFile.getName(); JarFile jf = new JarFile(mapPackFile, true); try { Enumeration<JarEntry> it = jf.entries(); while (it.hasMoreElements()) { JarEntry entry = it.nextElement(); // We verify only class files if (!entry.getName().endsWith(".class")) continue; // directory or other entry // Get the input stream (triggers) the signature verification for the specific class Utilities.readFully(jf.getInputStream(entry)); if (entry.getCodeSigners() == null) throw new CertificateException("Unsigned class file found: " + entry.getName()); CodeSigner signer = entry.getCodeSigners()[0]; List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates(); if (cp.size() > 1) throw new CertificateException("Signature certificate not accepted: " + "certificate path contains more than one certificate"); // Compare the used certificate with the mapPack certificate if (!mapPackCert.equals(cp.get(0))) throw new CertificateException( "Signature certificate not accepted: " + "not the MapPack signer certificate"); } Manifest mf = jf.getManifest(); Attributes a = mf.getMainAttributes(); String mpv = a.getValue("MapPackVersion"); if (mpv == null) throw new IOException("MapPackVersion info missing!"); int mapPackVersion = Integer.parseInt(mpv); if (requiredMapPackVersion != mapPackVersion) throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version."); ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource"); if (entry == null) throw new IOException("MapSources services list is missing in file " + fileName); } finally { jf.close(); } }
From source file:org.kepler.objectmanager.ActorMetadata.java
/** * try to locate and parse a moml file as a class *///from w w w . ja v a2 s .c om protected ComponentEntity parseMoMLFile(String className) throws Exception { if (isDebugging) log.debug("parseMoMLFile(" + className + ")"); JarFile jarFile = null; InputStream xmlStream = null; try { // first we need to find the file and read it File classFile = searchClasspath(className); StringWriter sw = new StringWriter(); if (classFile.getName().endsWith(".jar")) { jarFile = new JarFile(classFile); ZipEntry entry = jarFile.getEntry(className.replace('.', '/') + ".xml"); xmlStream = jarFile.getInputStream(entry); } else { xmlStream = new FileInputStream(classFile); } byte[] b = new byte[1024]; int numread = xmlStream.read(b, 0, 1024); while (numread != -1) { String s = new String(b, 0, numread); sw.write(s); numread = xmlStream.read(b, 0, 1024); } sw.flush(); // get the moml document String xmlDoc = sw.toString(); sw.close(); if (isDebugging) log.debug("**** MoMLParser ****"); // use the moml parser to parse the doc MoMLParser parser = new MoMLParser(); parser.reset(); // System.out.println("processing " + className); NamedObj obj = parser.parse(xmlDoc); return (ComponentEntity) obj; } finally { if (jarFile != null) { jarFile.close(); } if (xmlStream != null) { xmlStream.close(); } } }
From source file:org.netbeans.nbbuild.MakeJnlp2.java
private void generateFiles() throws IOException, BuildException { final Set<String> declaredLocales = new HashSet<String>(); final boolean useAllLocales; if ("*".equals(includelocales)) { useAllLocales = true;//from ww w . j a v a2s. c o m } else if ("".equals(includelocales)) { useAllLocales = false; } else { useAllLocales = false; StringTokenizer tokenizer = new StringTokenizer(includelocales, ","); while (tokenizer.hasMoreElements()) { declaredLocales.add(tokenizer.nextToken()); } } final Set<String> indirectFilePaths = new HashSet<String>(); for (FileSet fs : new FileSet[] { indirectJars, indirectFiles }) { if (fs != null) { DirectoryScanner scan = fs.getDirectoryScanner(getProject()); for (String f : scan.getIncludedFiles()) { indirectFilePaths.add(f.replace(File.pathSeparatorChar, '/')); } } } final ExecutorService executorService = Executors.newFixedThreadPool(nbThreads); final List<BuildException> exceptions = new ArrayList<BuildException>(); for (final Iterator fileIt = files.iterator(); fileIt.hasNext();) { if (!exceptions.isEmpty()) { break; } final FileResource fr = (FileResource) fileIt.next(); final File jar = fr.getFile(); if (!jar.canRead()) { throw new BuildException("Cannot read file: " + jar); } // if (optimize && checkDuplicate(jar).isPresent()) { continue; } // executorService.execute(new Runnable() { @Override public void run() { JarFile theJar = null; try { theJar = new JarFile(jar); String codenamebase = JarWithModuleAttributes .extractCodeName(theJar.getManifest().getMainAttributes()); if (codenamebase == null) { throw new BuildException("Not a NetBeans Module: " + jar); } { int slash = codenamebase.indexOf('/'); if (slash >= 0) { codenamebase = codenamebase.substring(0, slash); } } String dashcnb = codenamebase.replace('.', '-'); String title; String oneline; String shrt; String osDep = null; { String bundle = theJar.getManifest().getMainAttributes() .getValue("OpenIDE-Module-Localizing-Bundle"); Properties prop = new Properties(); if (bundle != null) { ZipEntry en = theJar.getEntry(bundle); if (en == null) { throw new BuildException("Cannot find entry: " + bundle + " in file: " + jar); } InputStream is = theJar.getInputStream(en); prop.load(is); is.close(); } title = prop.getProperty("OpenIDE-Module-Name", codenamebase); oneline = prop.getProperty("OpenIDE-Module-Short-Description", title); shrt = prop.getProperty("OpenIDE-Module-Long-Description", oneline); } { String osMan = theJar.getManifest().getMainAttributes() .getValue("OpenIDE-Module-Requires"); if (osMan != null) { if (osMan.indexOf("org.openide.modules.os.MacOSX") >= 0) { // NOI18N osDep = "Mac OS X"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Linux") >= 0) { // NOI18N osDep = "Linux"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Solaris") >= 0) { // NOI18N osDep = "Solaris"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Windows") >= 0) { // NOI18N osDep = "Windows"; // NOI18N } } } Map<String, List<File>> localizedFiles = verifyExtensions(jar, theJar.getManifest(), dashcnb, codenamebase, verify, indirectFilePaths); executedLocales = localizedFiles.keySet(); new File(targetFile, dashcnb).mkdir(); File signed = new File(new File(targetFile, dashcnb), jar.getName()); // +p final JarConfigResolved jarConfig = signOrCopy(jar, signed); File jnlp = new File(targetFile, dashcnb + ".jnlp"); StringWriter writeJNLP = new StringWriter(); writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n"); writeJNLP.write( "<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n"); writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n"); writeJNLP.write(" <information>\n"); writeJNLP.write(" <title>" + XMLUtil.toElementContent(title) + "</title>\n"); writeJNLP.write(" <vendor>NetBeans</vendor>\n"); writeJNLP.write(" <description kind='one-line'>" + XMLUtil.toElementContent(oneline) + "</description>\n"); writeJNLP.write(" <description kind='short'>" + XMLUtil.toElementContent(shrt) + "</description>\n"); writeJNLP.write(" </information>\n"); String realPermissions = permissions; if ((jarConfig != null) && (jarConfig.getExtraManifestAttributes() != null)) { String jarPermissions = jarConfig.getExtraManifestAttributes().getValue("Permissions"); if (jarPermissions != null) { if ("all-permissions".equals(jarPermissions)) { realPermissions = "<security><all-permissions/></security>\n"; } else { realPermissions = ""; } } } writeJNLP.write(realPermissions); if (osDep == null) { writeJNLP.write(" <resources>\n"); } else { writeJNLP.write(" <resources os='" + osDep + "'>\n"); } writeJNLP.write("<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n"); writeJNLP.write(constructJarHref(jar, dashcnb)); processExtensions(jar, theJar.getManifest(), writeJNLP, dashcnb, codebase, realPermissions); processIndirectJars(writeJNLP, dashcnb); processIndirectFiles(writeJNLP, dashcnb); writeJNLP.write(" </resources>\n"); if (useAllLocales || !declaredLocales.isEmpty()) { // write down locales for (Map.Entry<String, List<File>> e : localizedFiles.entrySet()) { final String locale = e.getKey(); if (!declaredLocales.isEmpty() && !declaredLocales.contains(locale)) { continue; } final List<File> allFiles = e.getValue(); writeJNLP.write(" <resources locale='" + locale + "'>\n"); for (File n : allFiles) { log("generating locale " + locale + " for " + n, Project.MSG_VERBOSE); String name = n.getName(); String clusterRootPrefix = jar.getParent() + File.separatorChar; String absname = n.getAbsolutePath(); if (absname.startsWith(clusterRootPrefix)) { name = absname.substring(clusterRootPrefix.length()) .replace(File.separatorChar, '-'); } File t = new File(new File(targetFile, dashcnb), name); signOrCopy(n, t); writeJNLP.write(constructJarHref(n, dashcnb, name)); } writeJNLP.write(" </resources>\n"); } } writeJNLP.write(" <component-desc/>\n"); writeJNLP.write("</jnlp>\n"); writeJNLP.close(); // +p Files.write(writeJNLP.toString(), jnlp, Charset.forName("UTF-8")); } catch (Exception e) { exceptions.add(new BuildException(e)); } finally { if (theJar != null) { try { theJar.close(); } catch (IOException e) { } } } } }); } executorService.shutdown(); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (Exception e) { throw new BuildException(e); } if (!exceptions.isEmpty()) { throw exceptions.get(0); } }
From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java
/** * Deploy the bundled files and unpack several jars including help, * and the TeraGrid trusted ca's.//from www .j a v a2 s.c o m */ private void setup() { appHome = getApplicationHome(); try { JarFile tgfmJar = null; URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation") .getResource("ConfigOperation.class"); readVersionInformation(); // delete the old certs directory FileUtils.deleteRecursive(getCertificateDir()); for (String caURL : TRUSTED_CA_TARBALLS) { deployRemoteCATarball(caURL); } if (jarname.getProtocol().startsWith("jar") || jarname.getProtocol().startsWith("htt")) { JarURLConnection c = (JarURLConnection) jarname.openConnection(); tgfmJar = c.getJarFile(); AppMain.updateSplash(-1, "Unpacking help system..."); try { FileUtils.unpackJarEntry(tgfmJar, BUNDLED_JAR_HELP, getHelpDir()); } catch (Exception e) { LogManager.error("Failed to unpack help files.", e); } // unpack keystore try { JarEntry keystoreEntry = new JarEntry(tgfmJar.getEntry("security/keystore")); FileUtils.extractJarEntry(tgfmJar, keystoreEntry, new File(getCertificateDir() + File.separator + "keystore")); } catch (Exception e) { LogManager.error("Failed to unpack keystore.", e); } } else { LogManager.debug("Not running from jar. Structure already in place."); // copy help AppMain.updateSplash(-1, "Unpacking help system..."); File srcHelpDir = new File(appHome + "help"); if (!srcHelpDir.exists()) { throw new IOException("Failed to copy help files from " + srcHelpDir.getAbsolutePath()); } try { org.apache.commons.io.FileUtils.copyDirectory(srcHelpDir, new File(getHelpDir())); } catch (Exception e) { LogManager.error("Failed to copy help files.", e); } File srcKeystore = new File(appHome + "security" + File.separator + "keystore"); if (!srcKeystore.exists()) { throw new IOException("Failed to copy keystore from " + srcKeystore.getAbsolutePath()); } try { File destKeystore = new File(getCertificateDir() + File.separator + "keystore"); org.apache.commons.io.FileUtils.copyFile(srcKeystore, destKeystore); System.out.println("length of copied keystore is " + destKeystore.length()); } catch (Exception e) { LogManager.error("Failed to copy keystore.", e); } } configureCoGProperties(); } catch (Exception e) { LogManager.error("Failed to set up user environment.", e); } }