List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.guvnor.m2repo.backend.server.M2MavenRepositoryServiceImplTest.java
@Test public void testDeployArtifact() throws Exception { deployArtifact(gavBackend);//from ww w .ja v a 2 s . c o m Collection<File> files = repo.listFiles(); boolean found = false; for (File file : files) { String fileName = file.getName(); if (fileName.startsWith("guvnor-m2repo-editor-backend-0.0.1") && fileName.endsWith(".jar")) { found = true; String path = file.getPath(); String jarPath = path.substring( repo.getM2RepositoryRootDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME).length()); String pom = repo.getPomText(jarPath); assertNotNull(pom); break; } } assertTrue("Did not find expected file after calling M2Repository.addFile()", found); // Test get artifact file File file = repo.getArtifactFileFromRepository(gavBackend); assertNotNull("Empty file for artifact", file); JarFile jarFile = new JarFile(file); int count = 0; String lastEntryName = null; for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { ++count; JarEntry entry = entries.nextElement(); assertNotEquals("Endless loop.", lastEntryName, entry.getName()); } assertTrue("Empty jar file!", count > 0); }
From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java
/** * <p> Creates a new {@link StandaloneProcessingUnitContainer} based on the configured * parameters. A standalone processing unit container is a container that understands a * processing unit archive structure (both when working with an "exploded" directory and when * working with a zip/jar archive of it). It is provided with the location of the processing * unit using {@link org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider#StandaloneProcessingUnitContainerProvider(String)}. * The location itself follows Spring resource loader syntax. * * <p> If {@link #addConfigLocation(String)} is used, the Spring xml context will be read based * on the provided locations. If no config location was provided the default config location * will be <code>classpath*:/META-INF/spring/pu.xml</code>. * * <p> If {@link #setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)} is * set will use the configured bean level properties in order to configure the application * context and specific beans within it based on properties. This is done by adding {@link * org.openspaces.core.properties.BeanLevelPropertyBeanPostProcessor} and {@link * org.openspaces.core.properties.BeanLevelPropertyPlaceholderConfigurer} to the application * context./*w ww. j av a 2 s .c o m*/ * * <p> If {@link #setClusterInfo(org.openspaces.core.cluster.ClusterInfo)} is set will use it to * inject {@link org.openspaces.core.cluster.ClusterInfo} into beans that implement {@link * org.openspaces.core.cluster.ClusterInfoAware}. * * @return An {@link StandaloneProcessingUnitContainer} instance */ public ProcessingUnitContainer createContainer() throws CannotCreateContainerException { File fileLocation = new File(location); if (!fileLocation.exists()) { throw new CannotCreateContainerException("Failed to locate pu location [" + location + "]"); } // in case we don't have a cluster info specific members final ClusterInfo clusterInfo = getClusterInfo(); if (clusterInfo != null && clusterInfo.getInstanceId() == null) { ClusterInfo origClusterInfo = clusterInfo; List<ProcessingUnitContainer> containers = new ArrayList<ProcessingUnitContainer>(); for (int i = 0; i < clusterInfo.getNumberOfInstances(); i++) { ClusterInfo containerClusterInfo = clusterInfo.copy(); containerClusterInfo.setInstanceId(i + 1); containerClusterInfo.setBackupId(null); setClusterInfo(containerClusterInfo); containers.add(createContainer()); if (clusterInfo.getNumberOfBackups() != null) { for (int j = 0; j < clusterInfo.getNumberOfBackups(); j++) { containerClusterInfo = containerClusterInfo.copy(); containerClusterInfo.setBackupId(j + 1); setClusterInfo(containerClusterInfo); containers.add(createContainer()); } } } setClusterInfo(origClusterInfo); return new CompoundProcessingUnitContainer( containers.toArray(new ProcessingUnitContainer[containers.size()])); } if (clusterInfo != null) { ClusterInfoParser.guessSchema(clusterInfo); } if (logger.isInfoEnabled()) { logger.info("Starting a Standalone processing unit container " + (clusterInfo != null ? "with " + clusterInfo : "")); } List<URL> urls = new ArrayList<URL>(); List<URL> sharedUrls = new ArrayList<URL>(); if (fileLocation.isDirectory()) { if (fileLocation.exists()) { if (logger.isDebugEnabled()) { logger.debug("Adding pu directory location [" + location + "] to classpath"); } try { urls.add(fileLocation.toURL()); } catch (MalformedURLException e) { throw new CannotCreateContainerException( "Failed to add classes to class loader with location [" + location + "]", e); } } addJarsLocation(fileLocation, urls, "lib"); addJarsLocation(fileLocation, sharedUrls, "shared-lib"); } else { JarFile jarFile; try { jarFile = new JarFile(fileLocation); } catch (IOException e) { throw new CannotCreateContainerException("Failed to open pu file [" + location + "]", e); } // add the root to the classpath try { urls.add(new URL("jar:" + fileLocation.toURL() + "!/")); } catch (MalformedURLException e) { throw new CannotCreateContainerException( "Failed to add pu location [" + location + "] to classpath", e); } // add jars in lib and shared-lib to the classpath for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry jarEntry = entries.nextElement(); if (isWithinDir(jarEntry, "lib") || isWithinDir(jarEntry, "shared-lib")) { // extract the jar into a temp location if (logger.isDebugEnabled()) { logger.debug("Adding jar [" + jarEntry.getName() + "] with pu location [" + location + "]"); } File tempLocation = new File(System.getProperty("java.io.tmpdir") + "/openspaces"); tempLocation.mkdirs(); File tempJar; String tempJarName = jarEntry.getName(); if (tempJarName.indexOf('/') != -1) { tempJarName = tempJarName.substring(tempJarName.lastIndexOf('/') + 1); } try { tempJar = File.createTempFile(tempJarName, ".jar", tempLocation); } catch (IOException e) { throw new CannotCreateContainerException("Failed to create temp jar at location [" + tempLocation + "] with name [" + tempJarName + "]", e); } tempJar.deleteOnExit(); if (logger.isTraceEnabled()) { logger.trace("Extracting jar [" + jarEntry.getName() + "] to temporary jar [" + tempJar.getAbsolutePath() + "]"); } FileOutputStream fos; try { fos = new FileOutputStream(tempJar); } catch (FileNotFoundException e) { throw new CannotCreateContainerException( "Failed to find temp jar [" + tempJar.getAbsolutePath() + "]", e); } InputStream is = null; try { is = jarFile.getInputStream(jarEntry); FileCopyUtils.copy(is, fos); } catch (IOException e) { throw new CannotCreateContainerException( "Failed to create temp jar [" + tempJar.getAbsolutePath() + "]"); } finally { if (is != null) { try { is.close(); } catch (IOException e1) { // do nothing } } try { fos.close(); } catch (IOException e1) { // do nothing } } try { if (isWithinDir(jarEntry, "lib")) { urls.add(tempJar.toURL()); } else if (isWithinDir(jarEntry, "shared-lib")) { sharedUrls.add(tempJar.toURL()); } } catch (MalformedURLException e) { throw new CannotCreateContainerException("Failed to add pu entry [" + jarEntry.getName() + "] with location [" + location + "]", e); } } } } List<URL> allUrls = new ArrayList<URL>(); allUrls.addAll(sharedUrls); allUrls.addAll(urls); addUrlsToContextClassLoader(allUrls.toArray(new URL[allUrls.size()])); StandaloneContainerRunnable containerRunnable = new StandaloneContainerRunnable(getBeanLevelProperties(), clusterInfo, configLocations); Thread standaloneContainerThread = new Thread(containerRunnable, "Standalone Container Thread"); standaloneContainerThread.setDaemon(false); standaloneContainerThread.start(); while (!containerRunnable.isInitialized()) { try { Thread.sleep(5000); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for standalone container to initialize"); } } if (containerRunnable.hasException()) { throw new CannotCreateContainerException("Failed to start container", containerRunnable.getException()); } return new StandaloneProcessingUnitContainer(containerRunnable); }
From source file:org.talend.updates.runtime.nexus.component.ComponentIndexManager.java
/** * /*from w w w. j av a2s . c o m*/ * create one default index bean which based one the component zip file directly. * * bundleId, version, mvn_uri are required */ public ComponentIndexBean create(File componentZipFile) { if (componentZipFile == null || !componentZipFile.exists() || componentZipFile.isDirectory() || !componentZipFile.getName().endsWith(FileExtensions.ZIP_FILE_SUFFIX)) { return null; } String name = null; String bundleId = null; String bundleVersion = null; String mvnUri = null; ZipFile zipFile = null; try { zipFile = new ZipFile(componentZipFile); Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile.entries(); while (enumeration.hasMoreElements()) { final ZipEntry zipEntry = enumeration.nextElement(); String path = zipEntry.getName(); if (path.endsWith(FileExtensions.JAR_FILE_SUFFIX)) { // is jar // if it's bundle, not from other folder, like lib, m2 repository. IPath p = new Path(path); // must be in plugins if (p.segmentCount() > 1 && p.removeLastSegments(1).lastSegment().equals(UpdatesHelper.FOLDER_PLUGINS)) { if (UpdatesHelper.isComponentJar(zipFile.getInputStream(zipEntry))) { JarInputStream jarEntryStream = null; try { // must use another stream jarEntryStream = new JarInputStream(zipFile.getInputStream(zipEntry)); // find the bundleId and version Manifest manifest = jarEntryStream.getManifest(); if (manifest != null) { bundleId = JarMenifestUtil.getBundleSymbolicName(manifest); bundleVersion = JarMenifestUtil.getBundleVersion(manifest); } boolean checkManifest = StringUtils.isBlank(bundleId) || StringUtils.isBlank(bundleVersion); // find the pom.properties JarEntry jarEntry = null; while ((jarEntry = jarEntryStream.getNextJarEntry()) != null) { final String entryPath = jarEntry.getName(); if (checkManifest && JarFile.MANIFEST_NAME.equalsIgnoreCase(entryPath)) { manifest = new Manifest(); manifest.read(jarEntryStream); bundleId = JarMenifestUtil.getBundleSymbolicName(manifest); bundleVersion = JarMenifestUtil.getBundleVersion(manifest); checkManifest = false; } final Path fullPath = new Path(entryPath); final String fileName = fullPath.lastSegment(); /* * for example, * META-INF/maven/org.talend.components/components-splunk/pom.properties */ if (fileName.equals("pom.properties") //$NON-NLS-1$ && entryPath.contains("META-INF/maven/")) { //$NON-NLS-1$ // FIXME, didn't find one way to read the inner jar // final InputStream propStream = jarFile.getInputStream(jarEntry); // if (propStream != null) { // Properties pomProp = new Properties(); // pomProp.load(propStream); // // String version = pomProp.getProperty("version"); //$NON-NLS-1$ // String groupId = pomProp.getProperty("groupId"); //$NON-NLS-1$ // String artifactId = pomProp.getProperty("artifactId"); //$NON-NLS-1$ // mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, version, // FileExtensions.ZIP_FILE_SUFFIX, null); // // propStream.close(); // } // FIXME, try the path way // META-INF/maven/org.talend.components/components-splunk IPath tmpMavenPath = fullPath.removeLastSegments(1); String artifactId = tmpMavenPath.lastSegment(); // components-splunk // META-INF/maven/org.talend.components tmpMavenPath = tmpMavenPath.removeLastSegments(1); String groupId = tmpMavenPath.lastSegment(); // org.talend.components mvnUri = MavenUrlHelper.generateMvnUrl(groupId, artifactId, bundleVersion, FileExtensions.ZIP_EXTENSION, null); } else /* * /OSGI-INF/installer$$splunk.xml */ if (fileName.endsWith(FileExtensions.XML_FILE_SUFFIX) && fileName.startsWith(UpdatesHelper.NEW_COMPONENT_PREFIX) && entryPath.contains(UpdatesHelper.FOLDER_OSGI_INF + '/')) { name = fullPath.removeFileExtension().lastSegment(); name = name.substring(name.indexOf(UpdatesHelper.NEW_COMPONENT_PREFIX) + UpdatesHelper.NEW_COMPONENT_PREFIX.length()); } } } catch (IOException e) { // } finally { try { if (jarEntryStream != null) { jarEntryStream.close(); } } catch (IOException e) { // } } } } } } } catch (ZipException e) { if (CommonsPlugin.isDebugMode()) { ExceptionHandler.process(e); } } catch (IOException e) { if (CommonsPlugin.isDebugMode()) { ExceptionHandler.process(e); } } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // } } } // set the required if (name != null && bundleId != null && bundleVersion != null && mvnUri != null) { final ComponentIndexBean indexBean = new ComponentIndexBean(); final boolean set = indexBean.setRequiredFieldsValue(name, bundleId, bundleVersion, mvnUri); indexBean.setValue(ComponentIndexNames.types, PathUtils.convert2StringTypes(Arrays.asList(Type.TCOMP_V0))); if (set) { return indexBean; } } return null; }
From source file:org.drools.guvnor.server.RepositoryPackageService.java
private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException { JarInputStream jis;/*from w ww .j a v a2 s . c om*/ jis = new JarInputStream(asset.getBinaryContentAttachment()); JarEntry entry = null; while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().endsWith(".class")) { res.add(ModelContentHandler.convertPathToName(entry.getName())); } } } return jis; }
From source file:org.phenotips.tool.packager.PackageMojo.java
private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException { String parsedExtension = ".vm"; getLog().info("Copying Configuration files ..."); VelocityContext context = createVelocityContext(); Artifact configurationResourcesArtifact = this.repositorySystem.createArtifact(XWIKI_PLATFORM_GROUPID, "xwiki-platform-tool-configuration-resources", this.xwikiVersion, "", TYPE_JAR); resolveArtifact(configurationResourcesArtifact); configurationFileTargetDirectory.mkdirs(); try (JarInputStream jarInputStream = new JarInputStream( new FileInputStream(configurationResourcesArtifact.getFile()))) { JarEntry entry; while ((entry = jarInputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(parsedExtension)) { String fileName = entry.getName().replace(parsedExtension, ""); File outputFile = new File(configurationFileTargetDirectory, fileName); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile)); getLog().debug("Writing config file: " + outputFile); // Note: Init is done once even if this method is called several times... Velocity.init();/* ww w.j a v a 2 s. co m*/ Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream)); writer.close(); jarInputStream.closeEntry(); } } } catch (Exception e) { throw new MojoExecutionException("Failed to extract configuration files", e); } }
From source file:org.jenkins.tools.test.PluginCompatTester.java
/** * Scans through a WAR file, accumulating plugin information * @param war WAR to scan// w ww. j ava 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.catalina.startup.TldConfig.java
/** * Scans all TLD entries in the given JAR for application listeners. * * @param file JAR file whose TLD entries are scanned for application * listeners//from w w w. j a v a 2 s. c o m */ private void tldScanJar(File file) throws Exception { JarFile jarFile = null; String name = null; String jarPath = file.getAbsolutePath(); try { jarFile = new JarFile(file); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); name = entry.getName(); if (!name.startsWith("META-INF/")) { continue; } if (!name.endsWith(".tld")) { continue; } if (log.isTraceEnabled()) { log.trace(" Processing TLD at '" + name + "'"); } try { tldScanStream(new InputSource(jarFile.getInputStream(entry))); } catch (Exception e) { log.error(sm.getString("contextConfig.tldEntryException", name, jarPath, context.getPath()), e); } } } catch (Exception e) { log.error(sm.getString("contextConfig.tldJarException", jarPath, context.getPath()), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // Ignore } } } }
From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java
private void loadClasses(File[] jarFiles, URLClassLoader cl) throws Exception { for (File input : jarFiles) { try {//from www. j a v a2 s .c o m //load classes from plugin's jar files using the classloader above //loadClassesFromJar(input, cl); JarFile jarFile = new JarFile(input.getAbsolutePath()); Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry je = (JarEntry) e.nextElement(); if (je.isDirectory() || !je.getName().endsWith(".class")) { continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); try { cl.loadClass(className); } catch (Throwable ex) { String error = "Error loadin class: " + className; _logger.error(error); } } } catch (Throwable e) { String error = "Unexpected error loading class for file: " + input.getName() + " - " + e.getMessage(); _logger.error(error, e); throw new Exception(error, e); } } }
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 {// www .j a v a 2 s . 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.apache.storm.utils.ServerUtils.java
public void extractDirFromJarImpl(String jarpath, String dir, File destdir) { try (JarFile jarFile = new JarFile(jarpath)) { Enumeration<JarEntry> jarEnums = jarFile.entries(); while (jarEnums.hasMoreElements()) { JarEntry entry = jarEnums.nextElement(); if (!entry.isDirectory() && entry.getName().startsWith(dir)) { File aFile = new File(destdir, entry.getName()); aFile.getParentFile().mkdirs(); try (FileOutputStream out = new FileOutputStream(aFile); InputStream in = jarFile.getInputStream(entry)) { IOUtils.copy(in, out); }/*w w w . j a v a 2 s. c o m*/ } } } catch (IOException e) { LOG.info("Could not extract {} from {}", dir, jarpath); } }