List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java
/** Return a List with all the available bankruptcy functions by using dynamic class loading */ public List getAvailableBankruptcyFunctions() { try {//from www . ja v a 2 s. com List bankruptcyFunctions = new ArrayList(); String pckgname = "edu.caltechUcla.sselCassel.projects.jMarkets.shared.functions"; String name = "/edu/caltechUcla/sselCassel/projects/jMarkets/shared/functions"; // Get a File object for the package URL url = SessionBean.class.getResource(name); URI uri = new URI(url.getPath()); URL ori_url = new URL(url.getProtocol() + ":" + uri.getPath()); File directory = new File(ori_url.getFile()); if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension String classname = files[i].substring(0, files[i].length() - 6); try { // Try to create an instance of the object Object o = Class.forName(pckgname + "." + classname).newInstance(); if (o instanceof BankruptcyFunction && classname.endsWith("Function")) { BankruptcyBean bankruptcyBean = new BankruptcyBean(); String bankruptcyName = classname.substring(0, classname.length() - 8); bankruptcyBean.setName(bankruptcyName); bankruptcyFunctions.add(bankruptcyBean); } } catch (ClassNotFoundException e) { log.warn("Error loading bankruptcy function class", e); } catch (InstantiationException e) { //log.warn("Loaded verifier class does not have a default constructor!" + MSConstants.newline + e); } catch (IllegalAccessException e) { log.warn("Loaded bankruptcy function class is not public!", e); } } } } //check the jar file if the verifiers are not in the file system else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { // Try to create an instance of the object Object o = Class.forName(classname).newInstance(); if (o instanceof BankruptcyFunction && classname.endsWith("Function")) { String cname = classname.substring(classname.lastIndexOf('.') + 1); BankruptcyBean bankruptcyBean = new BankruptcyBean(); String bankruptcyName = cname.substring(0, cname.length() - 8); bankruptcyBean.setName(bankruptcyName); bankruptcyFunctions.add(bankruptcyBean); } } catch (ClassNotFoundException cnfex) { log.warn("Error loading bankruptcy function class", cnfex); } catch (InstantiationException iex) { // We try to instanciate an interface // or an object that does not have a // default constructor } catch (IllegalAccessException iaex) { log.warn("Loaded bankruptcy function class is not public!", iaex); } } } } catch (IOException e) { log.warn("Unknown IO Error", e); } } return bankruptcyFunctions; } catch (Exception e) { log.error("Failed to return a list of bankruptcy functions", e); } return null; }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java
/** Return a List with all the available payoff functions by using dynamic class loading */ public List getAvailablePayoffFunctions() { try {//from w w w. j a va 2 s. c o m List payoffFunctions = new ArrayList(); String pckgname = "edu.caltechUcla.sselCassel.projects.jMarkets.shared.functions"; String name = "/edu/caltechUcla/sselCassel/projects/jMarkets/shared/functions"; // Get a File object for the package URL url = SessionBean.class.getResource(name); URI uri = new URI(url.getPath()); URL ori_url = new URL(url.getProtocol() + ":" + uri.getPath()); File directory = new File(ori_url.getFile()); if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // we are only interested in .class files if (files[i].endsWith(".class")) { // removes the .class extension String classname = files[i].substring(0, files[i].length() - 6); try { // Try to create an instance of the object Object o = Class.forName(pckgname + "." + classname).newInstance(); if (o instanceof PayoffFunction && classname.endsWith("Function")) { PayoffBean payoffBean = new PayoffBean(); String payoffName = classname.substring(0, classname.length() - 8); payoffBean.setName(payoffName); payoffFunctions.add(payoffBean); } } catch (ClassNotFoundException e) { log.warn("Error loading payoff function class", e); } catch (InstantiationException e) { //log.warn("Loaded verifier class does not have a default constructor!" + MSConstants.newline + e); } catch (IllegalAccessException e) { log.warn("Loaded payoff function class is not public!", e); } } } } //check the jar file if the verifiers are not in the file system else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { // Try to create an instance of the object Object o = Class.forName(classname).newInstance(); if (o instanceof PayoffFunction && classname.endsWith("Function")) { String cname = classname.substring(classname.lastIndexOf('.') + 1); PayoffBean payoffBean = new PayoffBean(); String payoffName = cname.substring(0, cname.length() - 8); payoffBean.setName(payoffName); payoffFunctions.add(payoffBean); } } catch (ClassNotFoundException cnfex) { log.warn("Error loading payoff function class", cnfex); } catch (InstantiationException iex) { // We try to instanciate an interface // or an object that does not have a // default constructor } catch (IllegalAccessException iaex) { log.warn("Loaded payoff function class is not public!", iaex); } } } } catch (IOException e) { log.warn("Unknown IO Error", e); } } return payoffFunctions; } catch (Exception e) { log.error("Failed to return a list of payoff functions", e); } return null; }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java
private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix) throws IOException { JarFile jarFile = null; try {// w w w. ja v a 2 s .com jarFile = new JarFile(archiveFile); final Manifest manifest = jarFile.getManifest(); assertNotNull("Manifest should be present", manifest); assertEquals("Manifest version should be 1.0", "1.0", manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION)); final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry jarEntry = entries.nextElement(); if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) { // It is the manifest file, not added by use continue; } if (jarEntry.isDirectory()) { assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.dirs.contains(jarEntry.getName())); archiveEntries.dirs.remove(jarEntry.getName()); } else { assertTrue("File in jar should be from us [" + jarEntry.getName() + "]", archiveEntries.files.containsKey(jarEntry.getName())); final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false); assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]", archiveEntries.files.get(jarEntry.getName()), inflatedMd5); archiveEntries.files.remove(jarEntry.getName()); } } // Check that all files and directories have been accounted for assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty()); assertTrue("All files should be in the jar", archiveEntries.files.isEmpty()); } finally { if (null != jarFile) { jarFile.close(); } } }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
public void buildTypeGraph() { Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>(); Map<String, File> openClassFiles = new HashMap<String, File>(); // use global cache to load resource in/out of the same jar as the classes Set<String> resourceCacheSet = new HashSet<>(); try {// w ww .j av a 2 s .co m for (String path : pathsToScan) { File f = null; try { f = new File(path); if (!f.exists() || f.isDirectory() || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) { continue; } if (GENERATED_CLASSES_JAR.equals(f.getName())) { continue; } if (f.getName().endsWith("class")) { typeGraph.addNode(f); openClassFiles.put(path, f); } else { JarFile jar = new JarFile(path); openJarFiles.put(path, jar); java.util.Enumeration<JarEntry> entriesEnum = jar.entries(); while (entriesEnum.hasMoreElements()) { final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { continue; } if (entryName.endsWith("-javadoc.xml")) { try { processJavadocXml(jar.getInputStream(jarEntry)); // break; } catch (Exception ex) { LOG.warn("Cannot process javadoc {} : ", entryName, ex); } } else if (entryName.endsWith(".class")) { TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar); // check if any visited resources belong to this type for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext();) { String entry = iter.next(); if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) { newNode.setHasResource(true); iter.remove(); } } } else { String className = entryName; boolean foundClass = false; // check if this resource belongs to any visited type while (className.contains("/")) { className = className.substring(0, className.lastIndexOf('/')); TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.')); if (tgv != null) { tgv.setHasResource(true); foundClass = true; break; } } if (!foundClass) { resourceCacheSet.add(entryName); } } } } } catch (IOException ex) { LOG.warn("Cannot process file {}", f, ex); } } typeGraph.trim(); } finally { for (Entry<String, JarFile> entry : openJarFiles.entrySet()) { try { entry.getValue().close(); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } } }
From source file:net.minecraftforge.fml.common.discovery.JarDiscoverer.java
@Override public List<ModContainer> discover(ModCandidate candidate, ASMDataTable table) { List<ModContainer> foundMods = Lists.newArrayList(); FMLLog.fine("Examining file %s for potential mods", candidate.getModContainer().getName()); JarFile jar = null; try {// w w w . j ava 2 s . c om jar = new JarFile(candidate.getModContainer()); ZipEntry modInfo = jar.getEntry("mcmod.info"); MetadataCollection mc = null; if (modInfo != null) { FMLLog.finer("Located mcmod.info file in file %s", candidate.getModContainer().getName()); InputStream inputStream = jar.getInputStream(modInfo); try { mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName()); } finally { IOUtils.closeQuietly(inputStream); } } else { FMLLog.fine("The mod container %s appears to be missing an mcmod.info file", candidate.getModContainer().getName()); mc = MetadataCollection.from(null, ""); } for (ZipEntry ze : Collections.list(jar.entries())) { if (ze.getName() != null && ze.getName().startsWith("__MACOSX")) { continue; } Matcher match = classFile.matcher(ze.getName()); if (match.matches()) { ASMModParser modParser; try { InputStream inputStream = jar.getInputStream(ze); try { modParser = new ASMModParser(inputStream); } finally { IOUtils.closeQuietly(inputStream); } candidate.addClassEntry(ze.getName()); } catch (LoaderException e) { FMLLog.log(Level.ERROR, e, "There was a problem reading the entry %s in the jar %s - probably a corrupt zip", ze.getName(), candidate.getModContainer().getPath()); jar.close(); throw e; } modParser.validate(); modParser.sendToTable(table, candidate); ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate); if (container != null) { table.addContainer(container); foundMods.add(container); container.bindMetadata(mc); container.setClassVersion(modParser.getClassVersion()); } } } } catch (Exception e) { FMLLog.log(Level.WARN, e, "Zip file %s failed to read properly, it will be ignored", candidate.getModContainer().getName()); } finally { Java6Utils.closeZipQuietly(jar); } return foundMods; }
From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java
public FrameConfigAdmin() { super("Configuracion", true, //resizable true, //closable true, //maximizable true);//iconifiable try {/*from ww w . j av a 2s . c om*/ initComponents(); final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); if (jarFile.isFile()) { // Run with JAR file final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { final String name = entries.nextElement().getName(); if (name.startsWith("sql/")) { //filter according to the path cboSqlFiles.addItem("/" + name); } } jar.close(); } else { // Run with IDE final URL url = getClass().getResource("/sql"); if (url != null) { try { final File apps = new File(url.toURI()); for (File app : apps.listFiles()) { cboSqlFiles.addItem("/sql/" + app.getName()); } } catch (URISyntaxException ex) { // never happens } } } /*CurrentUser currentUser = CurrentUser.getInstance(); if (currentUser.getUser().getId() == 9999) { cmdReset.setEnabled(true); jButton3.setEnabled(true); } else { cmdReset.setEnabled(false); jButton3.setEnabled(false); }*/ /* File[] files = (new File(getClass().getResource("/sql").toURI())).listFiles(); for (File f : files) { cboSqlFiles.addItem(f.getName()); }*/ } catch (Exception ex) { JOptionPane.showMessageDialog(null, Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage()); LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); } }
From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java
/** * Deployes an EAR to the container specified in the DeployerConfig. The EAR's * applicationContext.xml is parsed and the module/web entries are deployed using * {@link #deployWar(WebModule, JarFile, DeployerConfig)}. Then all JARs in the EAR are * deployed using {@link #deployJar(JarEntry, JarFile, DeployerConfig)}. * /*www .j a v a 2s.co m*/ * @param deployerConfig * @throws MojoFailureException * @throws Exception */ public final void deploy(DeployerConfig deployerConfig) throws MojoExecutionException, MojoFailureException { final JarFile earFile = this.getEarFile(deployerConfig); final Document descriptorDom = this.getDescriptorDom(earFile); final NodeList webModules = this.getWebModules(descriptorDom); //Iterate through the WebModules, deploying each for (int index = 0; index < webModules.getLength(); index++) { final Node webModuleNode = webModules.item(index); final WebModule webModuleInfo = this.getWebModuleInfo(webModuleNode); this.deployWar(webModuleInfo, earFile, deployerConfig); } //Iterate through all the entries in the EAR, deploying each that ends in .jar for (final Enumeration<JarEntry> earEntries = earFile.entries(); earEntries.hasMoreElements();) { final JarEntry entry = earEntries.nextElement(); if (entry.getName().endsWith(".jar")) { this.deployJar(entry, earFile, deployerConfig); } } }
From source file:org.rhq.enterprise.server.core.plugin.ProductPluginDeployer.java
private boolean isDeploymentValidZipFile(File pluginFile) { boolean isValid; JarFile jarFile = null; try {/* w w w . j ava2 s .co m*/ // Try to access the plugin jar using the JarFile API. // Any weird errors usually mean the file is currently being written but isn't finished yet. // Errors could also mean the file is simply corrupted. jarFile = new JarFile(pluginFile); if (jarFile.size() <= 0) { throw new Exception("There are no entries in the plugin file"); } JarEntry entry = jarFile.entries().nextElement(); entry.getName(); isValid = true; } catch (Exception e) { log.info("File [" + pluginFile + "] is not a valid jarfile - " + " the file may not have been fully written yet. Cause: " + e); isValid = false; } finally { if (jarFile != null) { try { jarFile.close(); } catch (Exception e) { log.error("Failed to close jar file [" + pluginFile + "]"); } } } return isValid; }
From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java
/** * Extract template from class//from w w w .j ava 2s . c o m */ private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException { LOGGER.info("Extracting OpenDJ template...."); if (!dst.exists()) { LOGGER.debug("Creating target dir {}", dst.getPath()); dst.mkdirs(); } templateRoot = new File(DATA_TEMPLATE_DIR, templateName); String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource) // Determing if we need to extract from JAR or directory if (templateRoot.isDirectory()) { LOGGER.trace("Need to do directory copy."); MiscUtil.copyDirectory(templateRoot, dst); return; } LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath); URL srcUrl = ClassLoader.getSystemResource(templateRootPath); LOGGER.debug("srcUrl " + srcUrl); // sample: // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template // output: // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar // // beware that in the URL there can be spaces encoded as %20, e.g. // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template // if (srcUrl.getPath().contains("!/")) { URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar File srcFile = new File(srcFileUri); JarFile jar = new JarFile(srcFile); LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath()); Enumeration<JarEntry> entries = jar.entries(); JarEntry e; byte buf[] = new byte[655360]; while (entries.hasMoreElements()) { e = entries.nextElement(); // skip other files if (!e.getName().contains(templateRootPath)) { continue; } // prepare destination file String filepath = e.getName().substring(templateRootPath.length()); File dstFile = new File(dst, filepath); // test if directory if (e.isDirectory()) { LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath()); dstFile.mkdirs(); continue; } LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath()); // Find file on classpath InputStream is = ClassLoader.getSystemResourceAsStream(e.getName()); // InputStream is = jar.getInputStream(e); //old way // Copy content OutputStream out = new FileOutputStream(dstFile); int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); is.close(); } jar.close(); } else { try { File file = new File(srcUrl.toURI()); File[] files = file.listFiles(); for (File subFile : files) { if (subFile.isDirectory()) { MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName())); } else { MiscUtil.copyFile(subFile, new File(dst, subFile.getName())); } } } catch (Exception ex) { throw new IOException(ex); } } LOGGER.debug("OpenDJ Extracted"); }
From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java
private void extractHtmlReportSummary() throws IOException, URISyntaxException { final String path = "html-summary-report"; final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); forceMkdir(reportsDirectory);/*from w w w . ja va 2 s.c o m*/ if (jarFile.isFile()) { // Run with JAR file JarFile jar = new JarFile(jarFile); Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.startsWith(path)) { //filter according to the path File file = getFile(reportsDirectory, substringAfter(name, path)); if (jarEntry.isDirectory()) { forceMkdir(file); } else { forceMkdir(file.getParentFile()); if (!file.exists()) { copyInputStreamToFile(jar.getInputStream(jarEntry), file); } } } } jar.close(); } else { // Run with IDE URL url = getClass().getResource("/" + path); if (url != null) { File apps = FileUtils.toFile(url); if (apps.isDirectory()) { copyDirectory(apps, reportsDirectory); } else { throw new IllegalStateException( format("Internal resource '%s' should be a directory.", apps.getAbsolutePath())); } } else { throw new IllegalStateException(format("Internal resource '/%s' should be here.", path)); } } }