List of usage examples for java.util.jar JarInputStream close
public void close() throws IOException
From source file:org.sherlok.utils.BundleCreatorUtil.java
private static void createBundle(Set<BundleDef> bundleDefs) throws Exception { // create fake POM from bundles and copy it String fakePom = MavenPom.writePom(bundleDefs, "BundleCreator", System.currentTimeMillis() + "");// must be unique Artifact rootArtifact = new DefaultArtifact(fakePom); LOG.trace("* rootArtifact: '{}'", rootArtifact); // add remote repository urls RepositorySystem system = AetherResolver.newRepositorySystem(); RepositorySystemSession session = AetherResolver.newRepositorySystemSession(system, AetherResolver.LOCAL_REPO_PATH); Map<String, String> repositoriesDefs = map(); for (BundleDef b : bundleDefs) { b.validate(b.getId());//from w w w . j a v a 2s . c o m for (Entry<String, String> id_url : b.getRepositories().entrySet()) { repositoriesDefs.put(id_url.getKey(), id_url.getValue()); } } List<RemoteRepository> repos = AetherResolver.newRepositories(system, session, repositoriesDefs); // solve dependencies CollectRequest collectRequest = new CollectRequest(); collectRequest.setRoot(new Dependency(rootArtifact, "")); collectRequest .setRepositories(AetherResolver.newRepositories(system, session, new HashMap<String, String>())); CollectResult collectResult = system.collectDependencies(session, collectRequest); collectResult.getRoot().accept(new AetherResolver.ConsoleDependencyGraphDumper()); PreorderNodeListGenerator p = new PreorderNodeListGenerator(); collectResult.getRoot().accept(p); // now do the real fetching, and add jars to classpath List<Artifact> resolvedArtifacts = list(); for (Dependency dependency : p.getDependencies(true)) { Artifact resolvedArtifact = system .resolveArtifact(session, new ArtifactRequest(dependency.getArtifact(), repos, "")) .getArtifact(); resolvedArtifacts.add(resolvedArtifact); File jar = resolvedArtifact.getFile(); // add this jar to the classpath ClassPathHack.addFile(jar); LOG.trace("* resolved artifact '{}', added to classpath: '{}'", resolvedArtifact, jar.getAbsolutePath()); } BundleDef createdBundle = new BundleDef(); createdBundle.setVersion("TODO!"); createdBundle.setName("TODO!"); for (BundleDef bundleDef : bundleDefs) { for (BundleDependency dep : bundleDef.getDependencies()) { createdBundle.addDependency(dep); } } for (Artifact a : resolvedArtifacts) { // only consider artifacts that were included in the initial bundle boolean found = false; for (BundleDef bundleDef : bundleDefs) { for (BundleDependency dep : bundleDef.getDependencies()) { if (a.getArtifactId().equals(dep.getArtifactId())) { found = true; break; } } } if (found) { JarInputStream is = new JarInputStream(new FileInputStream(a.getFile())); JarEntry entry; while ((entry = is.getNextJarEntry()) != null) { if (entry.getName().endsWith(".class")) { try { Class<?> clazz = Class.forName(entry.getName().replace('/', '.').replace(".class", "")); // scan for all uimafit AnnotationEngines if (JCasAnnotator_ImplBase.class.isAssignableFrom(clazz)) { LOG.debug("AnnotationEngine: {}", clazz.getSimpleName()); final EngineDef engine = new EngineDef().setClassz(clazz.getName()) .setName(clazz.getSimpleName()).setBundle(createdBundle); createdBundle.addEngine(engine); LOG.debug("{}", engine); ReflectionUtils.doWithFields(clazz, new FieldCallback() { public void doWith(final Field f) throws IllegalArgumentException, IllegalAccessException { ConfigurationParameter c = f.getAnnotation(ConfigurationParameter.class); if (c != null) { LOG.debug("* param: {} {} {} {}", new Object[] { c.name(), c.defaultValue(), c.mandatory(), f.getType() }); String deflt = c.mandatory() ? "TODO" : "IS OPTIONAL"; String value = c.defaultValue()[0] .equals(ConfigurationParameter.NO_DEFAULT_VALUE) ? deflt : c.defaultValue()[0].toString(); engine.addParameter(c.name(), list(value)); } } }); } } catch (Throwable e) { System.err.println("something wrong with class " + entry.getName() + " " + e); } } } is.close(); } } // delete fake pom deleteDirectory(new File(LOCAL_REPO_PATH + "/org/sherlok/BundleCreator")); System.out.println(FileBased.writeAsString(createdBundle)); }
From source file:com.ottogroup.bi.asap.repository.CachedComponentClassLoader.java
/** * Initializes the class loader by pointing it to folder holding managed JAR files * @param componentFolder//from www . ja va 2s.c o m * @throws IOException * @throws RequiredInputMissingException */ public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException { /////////////////////////////////////////////////////////////////// // validate input if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'"); File folder = new File(componentFolder); if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder"); File[] jarFiles = folder.listFiles(); if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'"); // /////////////////////////////////////////////////////////////////// logger.info("Initializing component classloader [folder=" + componentFolder + "]"); // step through jar files, ensure it is a file and iterate through its contents for (File jarFile : jarFiles) { if (jarFile.isFile()) { JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); // if the current file references a class implementation, replace slashes by dots, strip // away the class suffix and add a reference to the classes-2-jar mapping if (StringUtils.endsWith(jarEntryName, ".class")) { jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); this.byteCode.put(jarEntryName, loadBytes(jarInputStream)); } else { // ...and add a mapping for resource to jar file as well this.resources.put(jarEntryName, loadBytes(jarInputStream)); } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } } } } logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation"); // load classes from jars marked component files and extract the deployment descriptors for (String cjf : this.byteCode.keySet()) { try { Class<?> c = loadClass(cjf); AsapComponent pc = c.getAnnotation(AsapComponent.class); if (pc != null) { this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()), new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(), pc.description())); logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name() + ", version=" + pc.version() + "]"); ; } } catch (Throwable e) { //logger.info("Failed to load class '"+cjf+"'. Error: " + e.getMessage()); } } }
From source file:org.vafer.jdependency.Clazzpath.java
public ClazzpathUnit addClazzpathUnit(final InputStream pInputStream, final String pId) throws IOException { final JarInputStream inputStream = new JarInputStream(pInputStream); try {/* w w w .j a v a2 s.c o m*/ final JarEntry[] entryHolder = new JarEntry[1]; return addClazzpathUnit(new Iterable<Resource>() { public Iterator<Resource> iterator() { return new Iterator<Resource>() { public boolean hasNext() { try { do { entryHolder[0] = inputStream.getNextJarEntry(); } while (entryHolder[0] != null && !Resource.isValidName(entryHolder[0].getName())); } catch (IOException e) { throw new RuntimeException(e); } return entryHolder[0] != null; } public Resource next() { return new Resource(entryHolder[0].getName()) { @Override InputStream getInputStream() { return inputStream; } }; } public void remove() { throw new UnsupportedOperationException(); } }; } }, pId, false); } finally { inputStream.close(); } }
From source file:com.paniclauncher.workers.InstanceInstaller.java
public void deleteMetaInf() { File inputFile = getMinecraftJar(); File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar"); try {// w w w .j a v a 2s.co m JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); inputFile.delete(); outputTmpFile.renameTo(inputFile); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } }
From source file:org.xwiki.tool.packager.PackageMojo.java
private void generateConfigurationFiles(File configurationFileTargetDirectory) throws MojoExecutionException { VelocityContext context = createVelocityContext(); Artifact configurationResourcesArtifact = this.factory.createArtifact("org.xwiki.platform", "xwiki-platform-tool-configuration-resources", this.project.getVersion(), "", "jar"); resolveArtifact(configurationResourcesArtifact); configurationFileTargetDirectory.mkdirs(); try {//w w w .jav a2s .c o m JarInputStream jarInputStream = new JarInputStream( new FileInputStream(configurationResourcesArtifact.getFile())); JarEntry entry; while ((entry = jarInputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(".vm")) { String fileName = entry.getName().replace(".vm", ""); File outputFile = new File(configurationFileTargetDirectory, fileName); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile)); getLog().info("Writing config file: " + outputFile); // Note: Init is done once even if this method is called several times... Velocity.init(); Velocity.evaluate(context, writer, "", IOUtils.toString(jarInputStream)); writer.close(); jarInputStream.closeEntry(); } } // Flush and close all the streams jarInputStream.close(); } catch (Exception e) { throw new MojoExecutionException("Failed to extract configuration files", e); } }
From source file:com.ottogroup.bi.spqr.repository.CachedComponentClassLoader.java
/** * Initializes the class loader by pointing it to folder holding managed JAR files * @param componentFolder//from w w w . j a v a2 s . c o m * @throws IOException * @throws RequiredInputMissingException */ public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException { /////////////////////////////////////////////////////////////////// // validate input if (StringUtils.isBlank(componentFolder)) throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'"); File folder = new File(componentFolder); if (!folder.isDirectory()) throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder"); File[] jarFiles = folder.listFiles(); if (jarFiles == null || jarFiles.length < 1) throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'"); // /////////////////////////////////////////////////////////////////// logger.info("Initializing component classloader [folder=" + componentFolder + "]"); // step through jar files, ensure it is a file and iterate through its contents for (File jarFile : jarFiles) { if (jarFile.isFile()) { JarInputStream jarInputStream = null; try { jarInputStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = null; while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); // if the current file references a class implementation, replace slashes by dots, strip // away the class suffix and add a reference to the classes-2-jar mapping if (StringUtils.endsWith(jarEntryName, ".class")) { jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.'); this.byteCode.put(jarEntryName, loadBytes(jarInputStream)); } else { // ...and add a mapping for resource to jar file as well this.resources.put(jarEntryName, loadBytes(jarInputStream)); } } } catch (Exception e) { logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } finally { try { jarInputStream.close(); } catch (Exception e) { logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: " + e.getMessage()); } } } } logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation"); // load classes from jars marked component files and extract the deployment descriptors for (String cjf : this.byteCode.keySet()) { try { Class<?> c = loadClass(cjf); Annotation spqrComponentAnnotation = getSPQRComponentAnnotation(c); if (spqrComponentAnnotation != null) { Method spqrAnnotationTypeMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_TYPE_METHOD, (Class[]) null); Method spqrAnnotationNameMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_NAME_METHOD, (Class[]) null); Method spqrAnnotationVersionMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_VERSION_METHOD, (Class[]) null); Method spqrAnnotationDescriptionMethod = spqrComponentAnnotation.getClass() .getMethod(ANNOTATION_DESCRIPTION_METHOD, (Class[]) null); @SuppressWarnings("unchecked") Enum<MicroPipelineComponentType> o = (Enum<MicroPipelineComponentType>) spqrAnnotationTypeMethod .invoke(spqrComponentAnnotation, (Object[]) null); final MicroPipelineComponentType componentType = Enum.valueOf(MicroPipelineComponentType.class, o.name()); final String componentName = (String) spqrAnnotationNameMethod.invoke(spqrComponentAnnotation, (Object[]) null); final String componentVersion = (String) spqrAnnotationVersionMethod .invoke(spqrComponentAnnotation, (Object[]) null); final String componentDescription = (String) spqrAnnotationDescriptionMethod .invoke(spqrComponentAnnotation, (Object[]) null); this.managedComponents.put(getManagedComponentKey(componentName, componentVersion), new ComponentDescriptor(c.getName(), componentType, componentName, componentVersion, componentDescription)); logger.info("pipeline component found [type=" + componentType + ", name=" + componentName + ", version=" + componentVersion + "]"); ; } } catch (Throwable e) { e.printStackTrace(); logger.error("Failed to load class '" + cjf + "'. Error: " + e.getMessage()); } } }
From source file:org.exist.repo.Deployment.java
public DocumentImpl getDescriptor(File jar) throws IOException, PackageException { final InputStream istream = new BufferedInputStream(new FileInputStream(jar)); final JarInputStream jis = new JarInputStream(istream); JarEntry entry;//w ww.j ava 2 s.c om DocumentImpl doc = null; while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory() && "expath-pkg.xml".equals(entry.getName())) { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c; final byte[] b = new byte[4096]; while ((c = jis.read(b)) > 0) { bos.write(b, 0, c); } bos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); try { doc = DocUtils.parse(broker.getBrokerPool(), null, bis); } catch (final XPathException e) { throw new PackageException("Error while parsing expath-pkg.xml: " + e.getMessage(), e); } break; } } jis.close(); return doc; }
From source file:org.jahia.utils.maven.plugin.osgi.DependenciesMojo.java
private int scanJar(File jarFile, boolean externalDependency, String packageDirectory, String version, boolean optional, ParsingContext parsingContext, String logPrefix) throws IOException { int scanned = 0; if (jarFile.isDirectory()) { getLog().debug(logPrefix + "Processing dependency directory " + jarFile + "..."); processDirectoryTlds(jarFile, version, parsingContext); processDirectory(jarFile, false, version, parsingContext); return scanned; }/* ww w . j a v a 2 s. c o m*/ JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); try { JarEntry jarEntry = null; getLog().debug(logPrefix + "Processing JAR file " + jarFile + "..."); if (processJarManifest(jarFile, parsingContext, jarInputStream)) { getLog().debug(logPrefix + "Used OSGi bundle manifest information, but scanning for additional resources (taglibs, CNDs, etc)... "); } scanned = processJarInputStream(jarFile.getPath(), externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, jarInputStream); } finally { jarInputStream.close(); } if (parsingContext.getBundleClassPath().size() > 0) { getLog().debug(logPrefix + "Processing embedded dependencies..."); JarFile jar = new JarFile(jarFile); for (String embeddedJar : parsingContext.getBundleClassPath()) { if (".".equals(embeddedJar)) { continue; } JarEntry jarEntry = jar.getJarEntry(embeddedJar); if (jarEntry != null) { getLog().debug(logPrefix + "Processing embedded JAR..." + jarEntry); InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); JarInputStream entryJarInputStream = new JarInputStream( new ByteArrayInputStream(entryOutputStream.toByteArray())); processJarInputStream(jarFile.getPath() + "!" + jarEntry, externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, entryJarInputStream); IOUtils.closeQuietly(jarEntryInputStream); IOUtils.closeQuietly(entryJarInputStream); } else { getLog().warn(logPrefix + "Couldn't find embedded JAR to parse " + embeddedJar + " in JAR " + jarFile); } } } if (parsingContext.getAdditionalFilesToParse().size() > 0) { getLog().debug(logPrefix + "Processing additional files to parse..."); JarFile jar = new JarFile(jarFile); for (String fileToParse : parsingContext.getAdditionalFilesToParse()) { JarEntry jarEntry = jar.getJarEntry(fileToParse); if (jarEntry != null) { InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); if (processNonTldFile(jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFile.getPath(), optional, version, parsingContext)) { scanned++; } IOUtils.closeQuietly(jarEntryInputStream); } else { getLog().warn(logPrefix + "Couldn't find additional file to parse " + fileToParse + " in JAR " + jarFile); } } parsingContext.clearAdditionalFilesToParse(); } return scanned; }
From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * * @param list paths/*www .ja va2 s .c o m*/ * @param url url * @param pattern pattern */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }
From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * // w ww .ja v a2s . c o m * @param list * @param ur */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<String>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }