List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
/** * * @see java.lang.ClassLoader#findLibrary(java.lang.String) *///from w w w .jav a2s. co m protected String findLibrary(String libname) { try { String name = System.mapLibraryName(libname + "-" + System.getProperty("os.arch")); URL url = getResourceURL(name); log.info("Loading " + name + " from " + url); if (url != null) { File jar = cachedJars.get(url); JarFile jarFile = new JarFile(jar); JarEntry entry = jarFile.getJarEntry(name); File library = new File(localLibDirectory, name); if (!library.exists()) { InputStream input = jarFile.getInputStream(entry); FileOutputStream output = new FileOutputStream(library); byte[] buffer = new byte[BUFFER_SIZE]; int totalBytes = 0; while (totalBytes < entry.getSize()) { int bytesRead = input.read(buffer); if (bytesRead < 0) { throw new IOException("Jar Entry too short!"); } output.write(buffer, 0, bytesRead); totalBytes += bytesRead; } output.close(); input.close(); jarFile.close(); } return library.getAbsolutePath(); } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java
/** * Copy the contents of a jar file to another archive * * @param file The input jar file//from w w w. j a v a 2 s . c o m * @param os The output archive * @throws IOException */ protected void extractJarToArchive(JarFile file, ArchiveOutputStream os, String[] excludes) throws IOException { Enumeration<? extends JarEntry> entries = file.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (excludes != null && excludes.length > 0) { for (String exclude : excludes) { if (SelectorUtils.match(exclude, j.getName())) { continue; } } } if (StringUtils.equalsIgnoreCase(j.getName(), "META-INF/MANIFEST.MF")) { continue; } os.putArchiveEntry(new JarArchiveEntry(j.getName())); IOUtils.copy(file.getInputStream(j), os); os.closeArchiveEntry(); } if (file != null) { file.close(); } }
From source file:org.hyperic.hq.plugin.websphere.WebsphereProductPlugin.java
private File runtimeJarHack(File file) throws Exception { String tmp = System.getProperty("java.io.tmpdir"); //agent/tmp File newJar = new File(tmp, file.getName()); if (newJar.exists()) { return newJar; }//from w ww . ja v a2 s . c o m log.debug("Creating " + newJar); JarFile jar = new JarFile(file); JarOutputStream os = new JarOutputStream(new FileOutputStream(newJar)); byte[] buffer = new byte[1024]; try { for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { int n; JarEntry entry = e.nextElement(); if (entry.getName().startsWith("org/apache/commons/logging/")) { continue; } InputStream entryStream = jar.getInputStream(entry); os.putNextEntry(entry); while ((n = entryStream.read(buffer)) != -1) { os.write(buffer, 0, n); } entryStream.close(); } } finally { jar.close(); os.close(); } return newJar; }
From source file:org.openeos.tools.maven.plugins.GenerateEntitiesMojo.java
private List<File> findLiquibaseFiles(Artifact artifact) throws IOException { if (artifact == null) { return Collections.emptyList(); }/*w ww . j av a2s .c om*/ List<File> result = new ArrayList<File>(); if (artifact.getType().equals("jar")) { File file = artifact.getFile(); FileSystem fs = FileSystems.newFileSystem(Paths.get(file.getAbsolutePath()), this.getClass().getClassLoader()); PathMatcher matcher = fs.getPathMatcher("glob:" + searchpath); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); TreeSet<JarEntry> setEntries = new TreeSet<JarEntry>(new Comparator<JarEntry>() { @Override public int compare(JarEntry o1, JarEntry o2) { return o1.getName().compareTo(o2.getName()); } }); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (matcher.matches(fs.getPath(entry.getName()))) { setEntries.add(entry); } } for (JarEntry entry : setEntries) { File resultFile = File.createTempFile("generate-entities-maven", ".xml"); FileOutputStream out = new FileOutputStream(resultFile); InputStream in = jarFile.getInputStream(entry); IOUtils.copy(in, out); in.close(); out.close(); result.add(resultFile); } jarFile.close(); } return result; }
From source file:org.moe.cli.ParameterParserTest.java
@Test public void linkUniversalLibrary() throws Exception { File project = tmpDir.newFolder(); File outputJar = new File(project, "TestLib.jar"); // prepare file with ldFlags String flags = "-lTestLibrary"; File ldFlags = new File(project, "ldflags"); ldFlags.createNewFile();/*from w w w. j ava 2 s .c om*/ PrintWriter write = new PrintWriter(ldFlags); write.print(flags); write.close(); ClassLoader cl = this.getClass().getClassLoader(); URL library = cl.getResource("natives/universal/libTestLibrary.a"); URL headersURL = cl.getResource("natives/Headers/TestFramework.h"); File headers = new File(headersURL.getPath()); URL bundle = cl.getResource("moe_logo.png"); CommandLine argc = parseArgs(new String[] { "--library", library.getPath(), "--headers", headers.getParentFile().getPath(), "--package-name", "org", "--output-file-path", outputJar.getPath(), "--ld-flags", ldFlags.getPath(), "--bundle", bundle.getPath() }); IExecutor executor = ExecutorManager.getExecutorByParams(argc); assertNotNull(executor); assertTrue(executor instanceof ThirdPartyLibraryLinkExecutor); // generate binding & prepare output jar executor.execute(); // check output jar file existence assertTrue(outputJar.exists()); JarFile jarFile = new JarFile(outputJar); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String manifestLDFlags = attributes.getValue("MOE_CUSTOM_LINKER_FLAGS"); Set<String> realLDFlags = new HashSet<String>(Arrays.asList(flags.split(";"))); realLDFlags.add("-ObjC"); assertEquals(realLDFlags, new HashSet<String>(Arrays.asList(manifestLDFlags.split(";")))); String manifestSimFramework = attributes.getValue("MOE_ThirdpartyFramework_universal"); assertEquals(manifestSimFramework, "./lib/libTestLibrary.a"); String manifestBundle = attributes.getValue("MOE_BUNDLE_FILE_RESOURCES"); assertEquals(manifestBundle, "./bundle/moe_logo.png;"); assertNotNull(jarFile.getEntry("bundle/moe_logo.png")); assertNotNull(jarFile.getEntry("lib/libTestLibrary.a")); jarFile.close(); }
From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java
/** * Creates a new job on the specified Jenkins server with the specified name and configuration, * or updates the job with the specified name if it already exists on the server. * * @param jsc The Jenkins server to add the new job to. * @param name The name of the job to add. * @param type The JobType of the job to add. * @param params The configuration parameters for the new job. * @throws IOException//from ww w. j a v a 2s.c o m * @throws RuntimeException if the job wasn't created for other reasons. */ public void createOrUpdateJob(JenkinsServerConfiguration jsc, String name, JobType type, Map<String, Object> params) throws IOException { JenkinsServer server = JenkinsProvider.getJenkinsServer(jsc); VelocityContext velocityContext = new VelocityContext(params); StringWriter writer = new StringWriter(); JarFile jarFile = new JarFile(sitePaths.plugins_dir.getAbsoluteFile() + File.separator + "gerrit-ci.jar"); if (params.get("junitEnabled").toString().equals("false")) { params.put("junitPath", ""); } IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("templates" + type.getTemplate())), writer); String jobTemplate = writer.toString(); writer = new StringWriter(); IOUtils.copy(jarFile.getInputStream(jarFile.getEntry("scripts/prebuild-commands.sh")), writer); // We must escape special characters as this will be rendered into XML String prebuildScript = writer.toString().replace("&", "&").replace(">", ">").replace("<", "<"); params.put("cleanCommands", prebuildScript); StringWriter xmlWriter = new StringWriter(); Velocity.evaluate(velocityContext, xmlWriter, "", jobTemplate); String jobXml = xmlWriter.toString(); jarFile.close(); if (JenkinsProvider.jobExists(jsc, name)) { try { server.updateJob(name, jobXml, false); } catch (IOException e) { throw new RuntimeException(String.format("Failed to update Jenkins job: %s", name), e); } } else { try { server.createJob(name, jobXml, false); } catch (IOException e) { throw new RuntimeException(String.format("Failed to create Jenkins job: %s", name), e); } } }
From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java
public FrameConfigAdmin() { super("Configuracion", true, //resizable true, //closable true, //maximizable true);//iconifiable try {/*from w ww . jav a2 s . c o m*/ initComponents(); final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); if (jarFile.isFile()) { // Run with JAR file final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { final String name = entries.nextElement().getName(); if (name.startsWith("sql/")) { //filter according to the path cboSqlFiles.addItem("/" + name); } } jar.close(); } else { // Run with IDE final URL url = getClass().getResource("/sql"); if (url != null) { try { final File apps = new File(url.toURI()); for (File app : apps.listFiles()) { cboSqlFiles.addItem("/sql/" + app.getName()); } } catch (URISyntaxException ex) { // never happens } } } /*CurrentUser currentUser = CurrentUser.getInstance(); if (currentUser.getUser().getId() == 9999) { cmdReset.setEnabled(true); jButton3.setEnabled(true); } else { cmdReset.setEnabled(false); jButton3.setEnabled(false); }*/ /* File[] files = (new File(getClass().getResource("/sql").toURI())).listFiles(); for (File f : files) { cboSqlFiles.addItem(f.getName()); }*/ } catch (Exception ex) { JOptionPane.showMessageDialog(null, Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage()); LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex); } }
From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java
protected FragmentDescriptor getJARFragment(File file) throws IOException { FragmentDescriptor fd = null;//w ww. j a v a 2 s.c o m JarFile jar = new JarFile(file); try { ZipEntry ze = jar.getEntry(FRAGMENT_FILE); if (ze != null) { InputStream in = new BufferedInputStream(jar.getInputStream(ze)); try { fd = (FragmentDescriptor) xmap.load(in); } finally { in.close(); } if (fd.name == null) { // fallback on symbolic name fd.name = getSymbolicName(file); } if (fd.name == null) { // fallback on artifact id fd.name = getJarArtifactName(file.getName()); } if (fd.version == 0) { // compat with versions < 5.4 processBundleForCompat(fd, file); } } } finally { jar.close(); } return fd; }
From source file:org.openmrs.module.ModuleUtil.java
/** * This loops over all FILES in this jar to get the package names. If there is an empty * directory in this jar it is not returned as a providedPackage. * * @param file jar file to look into/*from w ww.j a va2 s . c o m*/ * @return list of strings of package names in this jar */ public static Collection<String> getPackagesFromFile(File file) { // End early if we're given a non jar file if (!file.getName().endsWith(".jar")) { return Collections.<String>emptySet(); } Set<String> packagesProvided = new HashSet<String>(); JarFile jar = null; try { jar = new JarFile(file); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); if (jarEntry.isDirectory()) { // skip over directory entries, we only care about files continue; } String name = jarEntry.getName(); // Skip over some folders in the jar/omod if (name.startsWith("lib") || name.startsWith("META-INF") || name.startsWith("web/module")) { continue; } Integer indexOfLastSlash = name.lastIndexOf("/"); if (indexOfLastSlash <= 0) { continue; } String packageName = name.substring(0, indexOfLastSlash); packageName = packageName.replaceAll("/", "."); if (packagesProvided.add(packageName)) { if (log.isTraceEnabled()) { log.trace("Adding module's jarentry with package: " + packageName); } } } jar.close(); } catch (IOException e) { log.error("Error while reading file: " + file.getAbsolutePath(), e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { // Ignore quietly } } } return packagesProvided; }
From source file:cn.webwheel.DefaultMain.java
/** * Find action method under certain package recursively. * <p>/*from w w w . j a v a2s.c om*/ * Action method must be marked by {@link Action}(may be through parent class).<br/> * Url will be the package path under rootpkg.<br/> * <b>example</b><br/> * action class: * <p><blockquote><pre> * package com.my.app.web.user; * public class insert { * {@code @}Action * public Object act() {...} * } * </pre></blockquote><p> * This action method will be mapped to url: /user/insert.act * @see #map(String) * @see Action * @param rootpkg action class package */ @SuppressWarnings("deprecation") final protected void autoMap(String rootpkg) { DefaultAction.defPagePkg = rootpkg; try { Enumeration<URL> enm = getClass().getClassLoader().getResources(rootpkg.replace('.', '/')); while (enm.hasMoreElements()) { URL url = enm.nextElement(); if (url.getProtocol().equals("file")) { autoMap(rootpkg.replace('.', '/'), rootpkg, new File(URLDecoder.decode(url.getFile()))); } else if (url.getProtocol().equals("jar")) { String file = URLDecoder.decode(url.getFile()); String root = file.substring(file.lastIndexOf('!') + 2); file = file.substring(0, file.length() - root.length() - 2); URL jarurl = new URL(file); if (jarurl.getProtocol().equals("file")) { JarFile jarFile = new JarFile(URLDecoder.decode(jarurl.getFile())); try { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (!name.endsWith(".class")) continue; if (!name.startsWith(root + '/')) continue; name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); int i = name.lastIndexOf('.'); autoMap(root, name.substring(0, i), name.substring(i + 1)); } } finally { jarFile.close(); } } } } } catch (IOException e) { throw new RuntimeException(e); } }