List of usage examples for java.util.jar JarInputStream JarInputStream
public JarInputStream(InputStream in) throws IOException
JarInputStream
and reads the optional manifest. From source file:org.apache.sling.tooling.support.source.impl.SourceReferencesServlet.java
private void collectMavenSourceRerefences(JSONWriter w, URL entry) throws IOException, JSONException { InputStream wrappedIn = entry.openStream(); try {// w w w. j av a 2 s. c o m JarInputStream jarIs = new JarInputStream(wrappedIn); JarEntry jarEntry; while ((jarEntry = jarIs.getNextJarEntry()) != null) { String entryName = jarEntry.getName(); if (entryName.startsWith("META-INF/maven/") && entryName.endsWith("/pom.properties")) { writeMavenGav(w, jarIs); } } } finally { IOUtils.closeQuietly(wrappedIn); } }
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 .co 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:com.ottogroup.bi.asap.repository.ComponentClassloader.java
/** * Handle resource lookups by first checking the managed JARs and hand * it over to the parent if no entry exits * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String) *//*from www . ja va2s. co m*/ public InputStream getResourceAsStream(String name) { // lookup the name of the JAR file holding the resource String jarFileName = this.resourcesJarMapping.get(name); // if there is no such file, hand over the request to the parent class loader if (StringUtils.isBlank(jarFileName)) return super.getResourceAsStream(name); // try to find the resource inside the jar it is associated with JarInputStream jarInput = null; try { // open a stream on jar which contains the class jarInput = new JarInputStream(new FileInputStream(jarFileName)); // ... and iterate through all entries JarEntry jarEntry = null; while ((jarEntry = jarInput.getNextJarEntry()) != null) { // extract the name of the jar entry and check if it is equal to the provided name String entryFileName = jarEntry.getName(); if (StringUtils.equals(name, entryFileName)) { // load bytes from jar entry and return it as stream byte[] data = loadBytes(jarInput); if (data != null) return new ByteArrayInputStream(data); } } } catch (IOException e) { logger.error("Failed to read resource '" + name + "' from JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } finally { try { jarInput.close(); } catch (IOException e) { logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage()); } } return null; }
From source file:be.iminds.aiolos.ui.DemoServlet.java
private void getRepositoryBundles(PrintWriter writer) { JSONArray components = new JSONArray(); Repository[] repos = new Repository[] {}; repos = repositoryTracker.getServices(repos); for (Repository repo : repos) { try {/*from ww w. j a v a 2 s .co m*/ CapabilityRequirementImpl requirement = new CapabilityRequirementImpl("osgi.identity", null); requirement.addDirective("filter", String.format("(%s=%s)", "osgi.identity", "*")); Map<Requirement, Collection<Capability>> result = repo .findProviders(Collections.singleton(requirement)); for (Capability c : result.values().iterator().next()) { String type = (String) c.getAttributes().get("type"); if (type != null && type.equals("osgi.bundle")) { String componentId = (String) c.getAttributes().get("osgi.identity"); String version = c.getAttributes().get("version").toString(); String name = null; String description = null; try { RepositoryContent content = (RepositoryContent) c.getResource(); JarInputStream jar = new JarInputStream(content.getContent()); Manifest mf = jar.getManifest(); Attributes attr = mf.getMainAttributes(); name = attr.getValue("Bundle-Name"); description = attr.getValue("Bundle-Description"); } catch (Exception e) { e.printStackTrace(); } JSONObject component = new JSONObject(); component.put("componentId", componentId); component.put("version", version); component.put("name", name); component.put("description", description); components.add(component); } } } catch (Exception e) { } } writer.write(components.toJSONString()); }
From source file:net.sourceforge.jweb.maven.mojo.OneExecutablejarMojo.java
private JarInputStream openOnejarTemplateArchive() throws IOException { return new JarInputStream(getClass().getClassLoader().getResourceAsStream(getOnejarArchiveName())); }
From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java
private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) { try {/* w w w. ja v a 2 s .c om*/ final boolean oldExists = moveJarToOld(); if (javacresult.size() > 0) { final Set<String> entries = new HashSet<String>(); final JarOutputStream jos = new JarOutputStream( new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest()); try { for (final String key : javacresult.keySet()) { entries.add(key); byte[] bytecode = javacresult.get(key); // create entry for directory (required for classpath scanning) if (key.contains("/")) { String dir = key.substring(0, key.lastIndexOf('/') + 1); if (!entries.contains(dir)) { entries.add(dir); jos.putNextEntry(new JarEntry(dir)); jos.closeEntry(); } } // call postCompile() (weaving) on compiled sources for (CodeGenerator generator : generators) { if (!oldExists || generator.isRecompileNecessary()) { for (JavaSourceAsString src : generator.getSourceFiles()) { final String name = src.getFQName(); if (key.startsWith(name.replaceAll("\\.", "/"))) { LOG.debug("postCompile (weaving) " + key); bytecode = generator.postCompile(key, bytecode); // Can we break here??? // break outer; } } } } jos.putNextEntry(new ZipEntry(key)); LOG.debug("writing to " + key + " to jar " + JARFILE); jos.write(bytecode); jos.closeEntry(); } if (oldExists) { final JarInputStream in = new JarInputStream( new BufferedInputStream(new FileInputStream(JARFILE_OLD))); final byte[] buffer = new byte[2048]; try { int size; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { if (!entries.contains(entry.getName())) { jos.putNextEntry(entry); LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD); while ((size = in.read(buffer, 0, buffer.length)) != -1) { jos.write(buffer, 0, size); } jos.closeEntry(); } in.closeEntry(); } } finally { in.close(); } } } finally { jos.close(); } } } catch (IOException ex) { throw new NuclosFatalException(ex); } }
From source file:fr.gael.dhus.server.http.TomcatServer.java
public void install(WebApplication web_application) throws TomcatException { try {/*from ww w . j a va 2 s. com*/ String folder = web_application.getName() == "" ? "ROOT" : web_application.getName(); if (web_application.hasWarStream()) { InputStream stream = web_application.getWarStream(); if (stream == null) { throw new TomcatException("Cannot install WebApplication " + web_application.getName() + ". The referenced war " + "file does not exist."); } JarInputStream jis = new JarInputStream(stream); File destDir = new File(tomcatpath, "webapps/" + folder); byte[] buffer = new byte[4096]; JarEntry file; while ((file = jis.getNextJarEntry()) != null) { File f = new File(destDir + java.io.File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } java.io.FileOutputStream fos = new java.io.FileOutputStream(f); int read; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); fos.close(); } jis.close(); } web_application.configure(new File(tomcatpath, "webapps/" + folder).getPath()); StandardEngine engine = (StandardEngine) cat.getServer().findServices()[0].getContainer(); Container container = engine.findChild(engine.getDefaultHost()); StandardContext ctx = new StandardContext(); String url = (web_application.getName() == "" ? "" : "/") + web_application.getName(); ctx.setName(url); ctx.setPath(url); ctx.setDocBase(new File(tomcatpath, "webapps/" + folder).getPath()); ctx.addLifecycleListener(new DefaultWebXmlListener()); ctx.setConfigFile(getWebappConfigFile(new File(tomcatpath, "webapps/" + folder).getPath(), url)); ContextConfig ctxCfg = new ContextConfig(); ctx.addLifecycleListener(ctxCfg); ctxCfg.setDefaultWebXml("fr/gael/dhus/server/http/global-web.xml"); container.addChild(ctx); contexts.add(ctx); List<WebServlet> servlets = web_application.getServlets(); for (WebServlet servlet : servlets) { addServlet(ctx, servlet.getServletName(), servlet.getUrlPattern(), servlet.getServlet(), servlet.isLoadOnStartup()); } List<String> welcomeFiles = web_application.getWelcomeFiles(); for (String welcomeFile : welcomeFiles) { ctx.addWelcomeFile(welcomeFile); } if (web_application.getAllow() != null || web_application.getDeny() != null) { RemoteIpValve valve = new RemoteIpValve(); valve.setRemoteIpHeader("x-forwarded-for"); valve.setProxiesHeader("x-forwarded-by"); valve.setProtocolHeader("x-forwarded-proto"); ctx.addValve(valve); RemoteAddrValve valve_addr = new RemoteAddrValve(); valve_addr.setAllow(web_application.getAllow()); valve_addr.setDeny(web_application.getDeny()); ctx.addValve(valve_addr); } } catch (Exception e) { throw new TomcatException("Cannot install service", e); } }
From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java
/** * Returns a set containing all templates defined in this JAR file. *//*from w w w . ja v a 2 s .c o m*/ public HashMap getJarTemplates(URL url) throws Exception { PluginLog.getLog().debug("retrieving all templates from jar file: " + url); String lookFor = DIR_TEMPLATES + "/"; int length = lookFor.length(); HashMap templates = new HashMap(); BufferedInputStream bis = new BufferedInputStream(url.openStream()); JarInputStream jis = new JarInputStream(bis); JarEntry je; Set temp = new HashSet(); while ((je = jis.getNextJarEntry()) != null) { // find the template name String jarEntryName = je.getName(); PluginLog.getLog().debug("Found entry: " + jarEntryName); if (jarEntryName.length() <= length || !jarEntryName.startsWith(lookFor)) { continue; } int nextSlashIndex = jarEntryName.indexOf("/", length); if (nextSlashIndex == -1) { continue; } String jarTemplate = jarEntryName.substring(length, nextSlashIndex); PluginLog.getLog().debug("Found template: " + jarTemplate); if (templates.containsKey(jarTemplate)) { continue; } if (jarEntryName.endsWith("readme.txt")) { // a description found - add to templates String description = getShortDescription(jis); templates.put(jarTemplate, description); // remove from temp temp.remove(jarTemplate); } else { // add to temp until a description is found temp.add(jarTemplate); } } // add all templates that has no description Iterator iter = temp.iterator(); while (iter.hasNext()) { templates.put(iter.next(), "No description found."); } return templates; }
From source file:org.springframework.boot.loader.tools.JarWriter.java
/** * Write the required spring-boot-loader classes to the JAR. * @param loaderJarResourceName the name of the resource containing the loader classes * to be written//from w w w . j ava 2s .c o m * @throws IOException if the classes cannot be written */ @Override public void writeLoaderClasses(String loaderJarResourceName) throws IOException { URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName); try (JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream()))) { JarEntry entry; while ((entry = inputStream.getNextJarEntry()) != null) { if (entry.getName().endsWith(".class")) { writeEntry(new JarArchiveEntry(entry), new InputStreamEntryWriter(inputStream, false)); } } } }
From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java
private static Manifest readManifest(InputStream stream) throws IOException { if (!stream.markSupported()) throw new IOException("Stream must support mark/reset"); stream.mark(100000);/*from www. j a v a 2 s. c o m*/ try { @SuppressWarnings("resource") JarInputStream jarStream = new JarInputStream(stream); return jarStream.getManifest(); } finally { stream.reset(); } }