List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:com.izforge.izpack.util.SelfModifier.java
/** * @throws IOException if an error occured *//*w w w . j ava2 s . c o m*/ private void extractJarFile() throws IOException { int extracted = 0; InputStream in = null; String MANIFEST = "META-INF/MANIFEST.MF"; JarFile jar = new JarFile(jarFile, true); try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String pathname = entry.getName(); if (MANIFEST.equals(pathname.toUpperCase())) { continue; } in = jar.getInputStream(entry); FileUtils.copyToFile(in, new File(sandbox, pathname)); extracted++; } log("Extracted " + extracted + " file" + (extracted > 1 ? "s" : "") + " into " + sandbox.getPath()); } finally { try { jar.close(); } catch (IOException ignore) { } IOUtils.closeQuietly(in); } }
From source file:org.sakaiproject.kernel1.Activator.java
/** * {@inheritDoc}//from ww w . j a v a 2 s.c om * * @see org.sakaiproject.kernel.api.ComponentActivator#activate(org.sakaiproject.kernel.api.Kernel) */ public void activate(Kernel kernel) throws ComponentActivatorException { this.kernel = kernel; // here I want to create my services and register them // I could use Guice or Spring to do this, but I am going to do manual IoC // to keep it really simple InternalDateServiceImpl internalDateService = new InternalDateServiceImpl(); HelloWorldService helloWorldService = new HelloWorldServiceImpl(internalDateService); org.sakaiproject.component.api.ComponentManager cm = null; long start = System.currentTimeMillis(); try { LOG.info("START---------------------- Loading kernel 1"); cm = ComponentManager.getInstance(); } catch (Throwable t) { LOG.error("Failed to Startup ", t); } LOG.info("END------------------------ Loaded kernel 1 in " + (System.currentTimeMillis() - start) + "ms"); Properties localProperties = new Properties(); try { InputStream is = ResourceLoader.openResource(K1_PROPERTIES, this.getClass().getClassLoader()); localProperties.load(is); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } /** * plagerized from k2 bootstrap module ** */ for (Entry<Object, Object> o : localProperties.entrySet()) { String k = o.getKey().toString(); if (k.startsWith("+")) { String p = properties.getProperty(k.substring(1)); if (p != null) { properties.put(k.substring(1), p + o.getValue()); } else { properties.put(o.getKey(), o.getValue()); } } else { properties.put(o.getKey(), o.getValue()); } } LOG.info("Loaded " + localProperties.size() + " properties from " + K1_PROPERTIES); /** * plagerized from the ComponentLoaderService */ ArtifactResolverService artifactResolverService = new Maven2ArtifactResolver(); List<URL> locations = new ArrayList<URL>(); String[] locs = StringUtils.split(properties.getProperty(K1_COMPONENT_LOCATION), ';'); if (locs != null) { for (String location : locs) { location = location.trim(); if (location.startsWith("maven-repo")) { Artifact dep = DependencyImpl.fromString(location); URL u = null; try { u = artifactResolverService.resolve(null, dep); } catch (ComponentSpecificationException e) { LOG.error("Can't resolve " + K1_COMPONENT_LOCATION + " property in file " + K1_PROPERTIES); e.printStackTrace(); } LOG.info("added k1 api bundle:" + u); locations.add(u); } else if (location.endsWith(".jar")) { if (location.indexOf("://") < 0) { File f = new File(location); if (!f.exists()) { LOG.warn("Jar file " + f.getAbsolutePath() + " does not exist, will be ignored "); } else { try { location = "file://" + f.getCanonicalPath(); locations.add(new URL(location)); LOG.info("added k1 api bundle:" + location); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { LOG.info("added api bundle:" + location); try { locations.add(new URL(location)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { LOG.info("Locating api bundle in " + location); for (File f : FileUtil.findAll(location, ".jar")) { String path = null; try { path = f.getCanonicalPath(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (path.indexOf("://") < 0) { path = "file://" + path; } LOG.info(" added api bundle:" + path); try { locations.add(new URL(path)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } LOG.info(" bundle contains " + locations.size() + " uri's"); // find all the instances URLClassLoader uclassloader = new URLClassLoader(locations.toArray(new URL[0]), null); /** * end plagerism.... for now */ JarFile jar = null; for (URL url : locations) { try { jar = new JarFile(new File(url.toURI())); Enumeration<JarEntry> entries = jar.entries(); for (; entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); if (entry != null && entry.getName().endsWith(".class")) { ifcClassNames.add(entry.getName().replaceAll("/", ".")); } } jar.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // thats it. my service is ready to go, so lets register it // get the service manager ServiceManager serviceManager = kernel.getServiceManager(); List<Class> ifcClasses = new ArrayList<Class>(); String className = null; for (Iterator<String> i = ifcClassNames.iterator(); i.hasNext();) { try { className = i.next(); ifcClasses.add(Class.forName(className)); } catch (ClassNotFoundException e) { LOG.error("Can't find '" + className + "' in the classpath"); i.remove(); // / with a sharp stick e.printStackTrace(); } } for (Class clazz : ifcClasses) { ServiceSpec serviceSpec = new ServiceSpec(clazz); // register the service try { serviceManager.registerService(serviceSpec, cm.get(clazz)); } catch (ServiceManagerException e) { // oops something happened, re-throw as an activation issue throw new ComponentActivatorException("Failed to register service ", e); } } // just for fun.. resolve the JCRService and get a reference to the // respository. LOG.info("Getting JCR ============================="); JCRService service = serviceManager.getService(new ServiceSpec(JCRService.class)); Repository repo = service.getRepository(); for (String k : repo.getDescriptorKeys()) { LOG.info(" JCR Repo Key " + k + "::" + repo.getDescriptor(k)); } LOG.info("Logged In OK-============================="); // create a ServiceSpecification for the class I want to register, // the class here MUST be a class that was exported (see component.xml) // otherwise // nothing else will be able to see it. The service manager might enforce // this if I get // arround to it. ServiceSpec serviceSpec = new ServiceSpec(HelloWorldService.class); // register the service try { serviceManager.registerService(serviceSpec, helloWorldService); } catch (ServiceManagerException e) { // oops something happened, re-throw as an activation issue throw new ComponentActivatorException("Failed to register service ", e); } }
From source file:ffx.FFXClassLoader.java
protected void listScripts() { if (extensionJars != null) { List<String> scripts = new ArrayList<>(); for (JarFile extensionJar : extensionJars) { Enumeration<JarEntry> entries = extensionJar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); // System.out.println(name); if (name.startsWith("ffx") && name.endsWith(".groovy")) { name = name.replace('/', '.'); name = name.replace("ffx.scripts.", ""); name = name.replace(".groovy", ""); scripts.add(name);//from w w w .ja va 2 s . com } } } String[] scriptArray = scripts.toArray(new String[scripts.size()]); Arrays.sort(scriptArray); for (String script : scriptArray) { System.out.println(" " + script); } } }
From source file:org.wso2.carbon.automation.test.utils.common.FileManager.java
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory) throws IOException, URISyntaxException { File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI()); File destinationFileDirectory = new File(destinationDirectory); JarFile jarFile = new JarFile(sourceFile); String fileName = jarFile.getName(); String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); File destinationFile = new File(destinationFileDirectory, fileNameLastPart); JarOutputStream jarOutputStream = null; try {//from w w w. j a v a 2 s . c o m jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile)); Enumeration<JarEntry> entries = jarFile.entries(); InputStream inputStream = null; while (entries.hasMoreElements()) { try { JarEntry jarEntry = entries.nextElement(); inputStream = jarFile.getInputStream(jarEntry); //jarOutputStream.putNextEntry(jarEntry); //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName())); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { jarOutputStream.write(buffer, 0, bytesRead); } } finally { if (inputStream != null) { inputStream.close(); jarOutputStream.flush(); jarOutputStream.closeEntry(); } } } } finally { if (jarOutputStream != null) { jarOutputStream.close(); } } }
From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java
/** * Gets the resources from jar./*from ww w . j a v a 2s. com*/ * * @param jar * the jar * * @return the resources from jar * * @throws IOException * Signals that an I/O exception has occurred. */ private static LinkedList<String> getResourcesFromJar(File jar) throws IOException { JarFile j = new JarFile(jar); LinkedList<String> list = new LinkedList<String>(); Enumeration<JarEntry> entries = j.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class") && !entry.isDirectory() && !entry.getName().startsWith("META-INF")) { String resourceName = entry.getName(); list.add(resourceName); } } return list; }
From source file:de.nmichael.efa.Daten.java
public static Vector getEfaInfos(boolean efaInfos, boolean pluginInfos, boolean javaInfos, boolean hostInfos, boolean jarInfos) { Vector infos = new Vector(); // efa-Infos// w w w . j av a 2 s.c o m if (efaInfos) { infos.add("efa.version=" + Daten.VERSIONID); if (EFALIVE_VERSION != null && EFALIVE_VERSION.length() > 0) { infos.add("efalive.version=" + Daten.EFALIVE_VERSION); } if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { if (Daten.efaMainDirectory != null) { infos.add("efa.dir.main=" + Daten.efaMainDirectory); } if (Daten.efaBaseConfig != null && Daten.efaBaseConfig.efaUserDirectory != null) { infos.add("efa.dir.user=" + Daten.efaBaseConfig.efaUserDirectory); } if (Daten.efaProgramDirectory != null) { infos.add("efa.dir.program=" + Daten.efaProgramDirectory); } if (Daten.efaPluginDirectory != null) { infos.add("efa.dir.plugin=" + Daten.efaPluginDirectory); } if (Daten.efaDocDirectory != null) { infos.add("efa.dir.doc=" + Daten.efaDocDirectory); } if (Daten.efaDataDirectory != null) { infos.add("efa.dir.data=" + Daten.efaDataDirectory); } if (Daten.efaCfgDirectory != null) { infos.add("efa.dir.cfg=" + Daten.efaCfgDirectory); } if (Daten.efaBakDirectory != null) { infos.add("efa.dir.bak=" + Daten.efaBakDirectory); } if (Daten.efaTmpDirectory != null) { infos.add("efa.dir.tmp=" + Daten.efaTmpDirectory); } } } // efa Plugin-Infos if (pluginInfos) { try { File dir = new File(Daten.efaPluginDirectory); if ((applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) && Logger.isDebugLogging()) { File[] files = dir.listFiles(); for (File file : files) { if (file.isFile()) { infos.add("efa.plugin.file=" + file.getName() + ":" + file.length()); } } } Plugins plugins = Plugins.getPluginInfoFromLocalFile(); String[] names = plugins.getAllPluginNames(); for (String name : names) { infos.add("efa.plugin." + name + "=" + (Plugins.isPluginInstalled(name) ? "installed" : "not installed")); } } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, International.getString("Programminformationen konnten nicht ermittelt werden") + ": " + e.toString()); return null; } } // Java Infos if (javaInfos) { infos.add("java.version=" + System.getProperty("java.version")); infos.add("java.vendor=" + System.getProperty("java.vendor")); infos.add("java.home=" + System.getProperty("java.home")); infos.add("java.vm.version=" + System.getProperty("java.vm.version")); infos.add("java.vm.vendor=" + System.getProperty("java.vm.vendor")); infos.add("java.vm.name=" + System.getProperty("java.vm.name")); infos.add("os.name=" + System.getProperty("os.name")); infos.add("os.arch=" + System.getProperty("os.arch")); infos.add("os.version=" + System.getProperty("os.version")); if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { infos.add("user.home=" + System.getProperty("user.home")); infos.add("user.name=" + System.getProperty("user.name")); infos.add("user.dir=" + System.getProperty("user.dir")); infos.add("java.class.path=" + System.getProperty("java.class.path")); } } // Host Infos if (hostInfos) { if (applID != APPL_EFABH || applMode == APPL_MODE_ADMIN) { try { infos.add("host.name=" + InetAddress.getLocalHost().getCanonicalHostName()); infos.add("host.ip=" + InetAddress.getLocalHost().getHostAddress()); infos.add("host.interface=" + EfaUtil .getInterfaceInfo(NetworkInterface.getByInetAddress(InetAddress.getLocalHost()))); } catch (Exception eingore) { } } } // JAR methods if (jarInfos && Logger.isDebugLogging()) { try { String cp = System.getProperty("java.class.path"); while (cp != null && cp.length() > 0) { int pos = cp.indexOf(";"); if (pos < 0) { pos = cp.indexOf(":"); } String jarfile; if (pos >= 0) { jarfile = cp.substring(0, pos); cp = cp.substring(pos + 1); } else { jarfile = cp; cp = null; } if (jarfile != null && jarfile.length() > 0 && new File(jarfile).isFile()) { try { infos.add("java.jar.filename=" + jarfile); JarFile jar = new JarFile(jarfile); Enumeration _enum = jar.entries(); Object o; while (_enum.hasMoreElements() && (o = _enum.nextElement()) != null) { infos.add( "java.jar.content=" + o + ":" + (jar.getEntry(o.toString()) == null ? "null" : Long.toString(jar.getEntry(o.toString()).getSize()))); } jar.close(); } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, e.toString()); return null; } } } } catch (Exception e) { Logger.log(Logger.ERROR, Logger.MSG_CORE_INFOFAILED, International.getString("Programminformationen konnten nicht ermittelt werden") + ": " + e.toString()); return null; } } return infos; }
From source file:plaid.compilerjava.CompilerCore.java
private void handlePlaidPathEntry(String base, PackageRep plaidpath, Stack<File> directoryWorklist) throws Exception { File baseDir = new File(base); if (baseDir.getAbsolutePath().contains("..")) { //relative paths need to be processed String absPath = baseDir.getAbsolutePath(); while (absPath.contains("..")) { int dotDotLoc = absPath.indexOf(".."); String prefix = absPath.substring(0, dotDotLoc - 1); //don't include previous separator String suffix = absPath.substring(dotDotLoc + 2); String sep = suffix.substring(0, 1); absPath = prefix.substring(0, prefix.lastIndexOf(sep)) + suffix; //get rid of .. and previous dir }/* w w w .j a v a2 s . c o m*/ baseDir = new File(absPath); //update the file to have the correct path without ".."'s } if (!baseDir.isDirectory()) { if (baseDir.isFile() && baseDir.getName().endsWith(".jar")) { JarFile jarFile = new JarFile(baseDir.getAbsolutePath()); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); handleFileInJar(jarFile, entry, plaidpath); } } else throw new RuntimeException("plaidpath entry " + base + " is not a directory"); } else { directoryWorklist.push(baseDir); String absoluteBase = baseDir.getAbsolutePath() + System.getProperty("file.separator"); File currentDirectory; while (!directoryWorklist.isEmpty()) { currentDirectory = directoryWorklist.pop(); File[] listOfFiles = currentDirectory.listFiles(); // listOfFiles can be null, for example if the current user doesn't have enough permissions // to access currentDirectory. In that case, we just skip the directory. if (listOfFiles == null) continue; for (File file : listOfFiles) { if (file.isFile()) handleFileInPlaidPath(file, absoluteBase, plaidpath); else if (file.isDirectory()) directoryWorklist.add(file); } } } }
From source file:org.hyperic.hq.product.server.session.ProductPluginDeployer.java
private void unpackJar(File pluginJarFile, File destDir, String prefix) throws Exception { JarFile jar = null; try {// w ww.ja v a 2s . c om jar = new JarFile(pluginJarFile); for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); String name = entry.getName(); if (name.startsWith(prefix)) { name = name.substring(prefix.length()); if (name.length() == 0) { continue; } File file = new File(destDir, name); if (entry.isDirectory()) { file.mkdirs(); } else { FileUtil.copyStream(jar.getInputStream(entry), new FileOutputStream(file)); } } } } catch (Throwable t) { t.printStackTrace(); } finally { if (jar != null) jar.close(); } }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {//from w w w. ja v a 2s . co m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Extract the Bourbon assets to the build directory. * @param destinationDir directory for the Bourbon resources *//*from ww w . ja v a 2s .c o m*/ private void extractBourbonResources(String destinationDir) { final Log log = this.getLog(); try { File destDir = new File(destinationDir); if (destDir.isDirectory()) { // skip extracting Bourbon, as it seems to hav been done log.info("Bourbon resources seems to have been extracted before."); return; } log.info("Extracting Bourbon resources to: " + destinationDir); destDir.mkdirs(); // find the jar with the Bourbon directory in the classloader URL urlJar = this.getClass().getClassLoader().getResource("scss-report.xsl"); String resourceFilePath = urlJar.getFile(); int index = resourceFilePath.indexOf("!"); String jarFileURI = resourceFilePath.substring(0, index); File jarFile = new File(new URI(jarFileURI)); JarFile jar = new JarFile(jarFile); // extract app/assets/stylesheets to destinationDir for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) { JarEntry entry = enums.nextElement(); if (entry.getName().contains("app/assets/stylesheets")) { // shorten the path a bit index = entry.getName().indexOf("app/assets/stylesheets"); String fileName = destinationDir + File.separator + entry.getName().substring(index); File f = new File(fileName); if (fileName.endsWith("/")) { f.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(f); try { IOUtil.copy(jar.getInputStream(entry), fos); } finally { IOUtil.close(fos); } } } } } catch (IOException | URISyntaxException ex) { log.error("Error extracting Bourbon resources.", ex); } }