List of usage examples for java.util.jar JarInputStream close
public void close() throws IOException
From source file:JarHelper.java
/** * Given an InputStream on a jar file, unjars the contents into the given * directory./*from w w w. j a v a 2 s . c om*/ */ public void unjar(InputStream in, File destDir) throws IOException { BufferedOutputStream dest = null; JarInputStream jis = new JarInputStream(in); JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { if (entry.isDirectory()) { File dir = new File(destDir, entry.getName()); dir.mkdir(); if (entry.getTime() != -1) dir.setLastModified(entry.getTime()); continue; } int count; byte data[] = new byte[BUFFER_SIZE]; File destFile = new File(destDir, entry.getName()); if (mVerbose) System.out.println("unjarring " + destFile + " from " + entry.getName()); FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); if (entry.getTime() != -1) destFile.setLastModified(entry.getTime()); } jis.close(); }
From source file:gov.nih.nci.restgen.util.JarHelper.java
/** * Given an InputStream on a jar file, unjars the contents into the given * directory.// www . j a v a 2 s . co m */ public void unjar(InputStream in, File destDir) throws IOException { BufferedOutputStream dest = null; JarInputStream jis = new JarInputStream(in); JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { if (entry.isDirectory()) { File dir = new File(destDir, entry.getName()); dir.mkdir(); if (entry.getTime() != -1) dir.setLastModified(entry.getTime()); continue; } int count; byte data[] = new byte[BUFFER_SIZE]; File destFile = new File(destDir, entry.getName()); if (mVerbose) { //System.out.println("unjarring " + destFile + " from " + entry.getName()); } FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); if (entry.getTime() != -1) destFile.setLastModified(entry.getTime()); } jis.close(); }
From source file:JarUtils.java
public static void unjar(InputStream in, File dest) throws IOException { if (!dest.exists()) { dest.mkdirs();//from w w w . j a v a2 s . c o m } if (!dest.isDirectory()) { throw new IOException("Destination must be a directory."); } JarInputStream jin = new JarInputStream(in); byte[] buffer = new byte[1024]; ZipEntry entry = jin.getNextEntry(); while (entry != null) { String fileName = entry.getName(); if (fileName.charAt(fileName.length() - 1) == '/') { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.charAt(0) == '/') { fileName = fileName.substring(1); } if (File.separatorChar != '/') { fileName = fileName.replace('/', File.separatorChar); } File file = new File(dest, fileName); if (entry.isDirectory()) { // make sure the directory exists file.mkdirs(); jin.closeEntry(); } else { // make sure the directory exists File parent = file.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } // dump the file OutputStream out = new FileOutputStream(file); int len = 0; while ((len = jin.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } out.flush(); out.close(); jin.closeEntry(); file.setLastModified(entry.getTime()); } entry = jin.getNextEntry(); } /* Explicity write out the META-INF/MANIFEST.MF so that any headers such as the Class-Path are see for the unpackaged jar */ Manifest mf = jin.getManifest(); if (mf != null) { File file = new File(dest, "META-INF/MANIFEST.MF"); File parent = file.getParentFile(); if (parent.exists() == false) { parent.mkdirs(); } OutputStream out = new FileOutputStream(file); mf.write(out); out.flush(); out.close(); } jin.close(); }
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 w ww. ja v a 2 s.c o 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:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java
/** * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable, * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark. * * @param dependencyJar {@link Location} of the job jar to be updated * @param context {@link BasicSparkContext} of this job *//* w ww.jav a 2 s .com*/ private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException { final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB, ApplicationBundler.SUBDIR_RESOURCES }; Id.Program programId = context.getProgram().getId(); Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar", ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(), programId.getId(), context.getRunId().getId())); // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest); try { JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream()); try { JarEntry jarEntry = jarInput.getNextJarEntry(); while (jarEntry != null) { boolean isDir = jarEntry.isDirectory(); String entryName = jarEntry.getName(); String newEntryName = entryName; for (String prefix : prefixToStrip) { if (entryName.startsWith(prefix) && !entryName.equals(prefix)) { newEntryName = entryName.substring(prefix.length()); } } jarEntry = new JarEntry(newEntryName); jarOutput.putNextEntry(jarEntry); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } jarEntry = jarInput.getNextJarEntry(); } } finally { jarInput.close(); Locations.deleteQuietly(dependencyJar); } } finally { jarOutput.close(); } return updatedJar; }
From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java
private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) { try {/*from ww w . j av a 2s . 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 {// w ww .j a v a 2 s . c o m 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:fr.gael.dhus.server.http.TomcatServer.java
public void install(fr.gael.dhus.server.http.WebApplication web_application) throws TomcatException { logger.info("Installing webapp " + web_application); String appName = web_application.getName(); String folder;//from w w w .j a v a 2 s . co m if (appName.trim().isEmpty()) { folder = "ROOT"; } else { folder = appName; } try { 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); 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); } web_application.checkInstallation(); } catch (Exception e) { throw new TomcatException("Cannot install webApplication " + web_application.getName(), e); } }
From source file:org.schemaspy.Config.java
public static Set<String> getBuiltInDatabaseTypes(String loadedFromJar) { Set<String> databaseTypes = new TreeSet<>(); JarInputStream jar = null; try {/*from ww w . ja v a 2 s . c o m*/ jar = new JarInputStream(new FileInputStream(loadedFromJar)); JarEntry entry; while ((entry = jar.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.indexOf("types") != -1) { int dotPropsIndex = entryName.indexOf(".properties"); if (dotPropsIndex != -1) databaseTypes.add(entryName.substring(0, dotPropsIndex)); } } } catch (IOException exc) { } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } return databaseTypes; }
From source file:io.squark.nestedjarclassloader.Module.java
private void addResource0(URL url) throws IOException { if (url.getPath().endsWith(".jar")) { if (logger != null) logger.debug("Adding jar " + url.getPath()); InputStream urlStream = url.openStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(urlStream); JarInputStream jarInputStream = new JarInputStream(bufferedInputStream); JarEntry jarEntry;/*from w w w.jav a 2 s . c o m*/ while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (resources.containsKey(jarEntry.getName())) { if (logger != null) logger.trace("Already have resource " + jarEntry.getName() + ". If different versions, unexpected behaviour " + "might occur. Available in " + resources.get(jarEntry.getName())); } String spec; if (url.getProtocol().equals("jar")) { spec = url.getPath(); } else { spec = url.getProtocol() + ":" + url.getPath(); } URL contentUrl = new URL(null, "jar:" + spec + "!/" + jarEntry.getName(), new NestedJarURLStreamHandler(false)); resources.put(jarEntry.getName(), contentUrl); addClassIfClass(jarInputStream, jarEntry.getName()); if (logger != null) logger.trace("Added resource " + jarEntry.getName() + " to ClassLoader"); if (jarEntry.getName().endsWith(".jar")) { addResource0(contentUrl); } } jarInputStream.close(); bufferedInputStream.close(); urlStream.close(); } else if (url.getPath().endsWith(".class")) { throw new IllegalStateException("Cannot add classes directly"); } else { try { addDirectory(new File(url.toURI())); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } }