List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:fr.gael.dhus.server.http.TomcatServer.java
private URL getWebappConfigFileFromJar(File docBase, String url) { URL result = null;/* w w w .j a v a 2 s .c om*/ JarFile jar = null; try { jar = new JarFile(docBase); JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml); if (entry != null) { result = new URL("jar:" + docBase.toURI().toString() + "!/" + Constants.ApplicationContextXml); } } catch (IOException e) { logger.warn("Unable to determine web application context.xml " + docBase, e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { // ignore } } } return result; }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
/** * Get the manifest from the File./* w ww.j ava 2s .c om*/ * @param bundleFile The bundle jar * @return The manifest. * @throws IOException */ protected Manifest getManifest(final File bundleFile) throws IOException { JarFile file = null; try { file = new JarFile(bundleFile); return file.getManifest(); } finally { if (file != null) { try { file.close(); } catch (IOException ignore) { } } } }
From source file:org.sakaiproject.kernel1.Activator.java
/** * {@inheritDoc}//from w ww. j a v a2 s.c om * * @see org.sakaiproject.kernel.api.ComponentActivator#activate(org.sakaiproject.kernel.api.Kernel) */ public void activate(Kernel kernel) throws ComponentActivatorException { this.kernel = kernel; // here I want to create my services and register them // I could use Guice or Spring to do this, but I am going to do manual IoC // to keep it really simple InternalDateServiceImpl internalDateService = new InternalDateServiceImpl(); HelloWorldService helloWorldService = new HelloWorldServiceImpl(internalDateService); org.sakaiproject.component.api.ComponentManager cm = null; long start = System.currentTimeMillis(); try { LOG.info("START---------------------- Loading kernel 1"); cm = ComponentManager.getInstance(); } catch (Throwable t) { LOG.error("Failed to Startup ", t); } LOG.info("END------------------------ Loaded kernel 1 in " + (System.currentTimeMillis() - start) + "ms"); Properties localProperties = new Properties(); try { InputStream is = ResourceLoader.openResource(K1_PROPERTIES, this.getClass().getClassLoader()); localProperties.load(is); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } /** * plagerized from k2 bootstrap module ** */ for (Entry<Object, Object> o : localProperties.entrySet()) { String k = o.getKey().toString(); if (k.startsWith("+")) { String p = properties.getProperty(k.substring(1)); if (p != null) { properties.put(k.substring(1), p + o.getValue()); } else { properties.put(o.getKey(), o.getValue()); } } else { properties.put(o.getKey(), o.getValue()); } } LOG.info("Loaded " + localProperties.size() + " properties from " + K1_PROPERTIES); /** * plagerized from the ComponentLoaderService */ ArtifactResolverService artifactResolverService = new Maven2ArtifactResolver(); List<URL> locations = new ArrayList<URL>(); String[] locs = StringUtils.split(properties.getProperty(K1_COMPONENT_LOCATION), ';'); if (locs != null) { for (String location : locs) { location = location.trim(); if (location.startsWith("maven-repo")) { Artifact dep = DependencyImpl.fromString(location); URL u = null; try { u = artifactResolverService.resolve(null, dep); } catch (ComponentSpecificationException e) { LOG.error("Can't resolve " + K1_COMPONENT_LOCATION + " property in file " + K1_PROPERTIES); e.printStackTrace(); } LOG.info("added k1 api bundle:" + u); locations.add(u); } else if (location.endsWith(".jar")) { if (location.indexOf("://") < 0) { File f = new File(location); if (!f.exists()) { LOG.warn("Jar file " + f.getAbsolutePath() + " does not exist, will be ignored "); } else { try { location = "file://" + f.getCanonicalPath(); locations.add(new URL(location)); LOG.info("added k1 api bundle:" + location); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { LOG.info("added api bundle:" + location); try { locations.add(new URL(location)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { LOG.info("Locating api bundle in " + location); for (File f : FileUtil.findAll(location, ".jar")) { String path = null; try { path = f.getCanonicalPath(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (path.indexOf("://") < 0) { path = "file://" + path; } LOG.info(" added api bundle:" + path); try { locations.add(new URL(path)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } LOG.info(" bundle contains " + locations.size() + " uri's"); // find all the instances URLClassLoader uclassloader = new URLClassLoader(locations.toArray(new URL[0]), null); /** * end plagerism.... for now */ JarFile jar = null; for (URL url : locations) { try { jar = new JarFile(new File(url.toURI())); Enumeration<JarEntry> entries = jar.entries(); for (; entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); if (entry != null && entry.getName().endsWith(".class")) { ifcClassNames.add(entry.getName().replaceAll("/", ".")); } } jar.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // thats it. my service is ready to go, so lets register it // get the service manager ServiceManager serviceManager = kernel.getServiceManager(); List<Class> ifcClasses = new ArrayList<Class>(); String className = null; for (Iterator<String> i = ifcClassNames.iterator(); i.hasNext();) { try { className = i.next(); ifcClasses.add(Class.forName(className)); } catch (ClassNotFoundException e) { LOG.error("Can't find '" + className + "' in the classpath"); i.remove(); // / with a sharp stick e.printStackTrace(); } } for (Class clazz : ifcClasses) { ServiceSpec serviceSpec = new ServiceSpec(clazz); // register the service try { serviceManager.registerService(serviceSpec, cm.get(clazz)); } catch (ServiceManagerException e) { // oops something happened, re-throw as an activation issue throw new ComponentActivatorException("Failed to register service ", e); } } // just for fun.. resolve the JCRService and get a reference to the // respository. LOG.info("Getting JCR ============================="); JCRService service = serviceManager.getService(new ServiceSpec(JCRService.class)); Repository repo = service.getRepository(); for (String k : repo.getDescriptorKeys()) { LOG.info(" JCR Repo Key " + k + "::" + repo.getDescriptor(k)); } LOG.info("Logged In OK-============================="); // create a ServiceSpecification for the class I want to register, // the class here MUST be a class that was exported (see component.xml) // otherwise // nothing else will be able to see it. The service manager might enforce // this if I get // arround to it. ServiceSpec serviceSpec = new ServiceSpec(HelloWorldService.class); // register the service try { serviceManager.registerService(serviceSpec, helloWorldService); } catch (ServiceManagerException e) { // oops something happened, re-throw as an activation issue throw new ComponentActivatorException("Failed to register service ", e); } }
From source file:org.xwiki.webjars.internal.WebJarsExportURLFactoryActionHandler.java
private void copyResourceFromJAR(String resourcePath, String prefix, ExportURLFactoryContext factoryContext) throws IOException { // Note that we cannot use ClassLoader.getResource() to access the resource since the resourcePath may point // to a directory inside the JAR, and in this case we need to copy all resources inside that directory in the // JAR!/* w w w . j a v a 2s. co m*/ JarFile jar = new JarFile(getJARFile(resourcePath)); for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements();) { JarEntry entry = enumeration.nextElement(); if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) { // Copy the resource! String targetPath = prefix + entry.getName(); File targetLocation = new File(factoryContext.getExportDir(), targetPath); if (!targetLocation.exists()) { targetLocation.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(targetLocation); InputStream is = jar.getInputStream(entry); IOUtils.copy(is, fos); fos.close(); is.close(); } } } jar.close(); }
From source file:ml.shifu.shifu.ShifuCLI.java
/** * print version info for shifu/*from w w w . j a va 2 s .co m*/ */ private static void printLogoAndVersion() { String findContainingJar = JarManager.findContainingJar(ShifuCLI.class); JarFile jar = null; try { jar = new JarFile(findContainingJar); final Manifest manifest = jar.getManifest(); String vendor = manifest.getMainAttributes().getValue("vendor"); String title = manifest.getMainAttributes().getValue("title"); String version = manifest.getMainAttributes().getValue("version"); String timestamp = manifest.getMainAttributes().getValue("timestamp"); System.out.println(" ____ _ _ ___ _____ _ _ "); System.out.println("/ ___|| | | |_ _| ___| | | |"); System.out.println("\\___ \\| |_| || || |_ | | | |"); System.out.println(" ___) | _ || || _| | |_| |"); System.out.println("|____/|_| |_|___|_| \\___/ "); System.out.println(" "); System.out.println(vendor + " " + title + " version " + version + " \ncompiled " + timestamp); } catch (Exception e) { throw new RuntimeException("unable to read pigs manifest file", e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { throw new RuntimeException("jar closed failed", e); } } } }
From source file:org.lpe.common.util.system.LpeSystemUtils.java
/** * Extracts a file/folder identified by the URL that resides in the * classpath, into the destiation folder. * /*from w w w .j a v a 2 s . c o m*/ * @param url * URL of the JAR file * @param dirOfInterest * the name of the directory of interest * @param dest * destination folder * * @throws IOException * ... * @throws URISyntaxException * ... */ public static void extractJARtoTemp(URL url, String dirOfInterest, String dest) throws IOException, URISyntaxException { if (!url.getProtocol().equals("jar")) { throw new IllegalArgumentException("Cannot locate the JAR file."); } // create a temp lib directory File tempJarDirFile = new File(dest); if (!tempJarDirFile.exists()) { boolean ok = tempJarDirFile.mkdir(); if (!ok) { logger.warn("Could not create directory {}", tempJarDirFile.getAbsolutePath()); } } else { FileUtils.cleanDirectory(tempJarDirFile); } String urlStr = url.getFile(); // if (urlStr.startsWith("jar:file:") || urlStr.startsWith("jar:") || // urlStr.startsWith("file:")) { // urlStr = urlStr.replaceFirst("jar:", ""); // urlStr = urlStr.replaceFirst("file:", ""); // } if (urlStr.contains("!")) { final int endIndex = urlStr.indexOf("!"); urlStr = urlStr.substring(0, endIndex); } URI uri = new URI(urlStr); final File jarFile = new File(uri); logger.debug("Unpacking jar file {}...", jarFile.getAbsolutePath()); java.util.jar.JarFile jar = null; InputStream is = null; OutputStream fos = null; try { jar = new JarFile(jarFile); java.util.Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { java.util.jar.JarEntry file = (JarEntry) entries.nextElement(); String destFileName = dest + File.separator + file.getName(); if (destFileName.indexOf(dirOfInterest + File.separator) < 0 && destFileName.indexOf(dirOfInterest + "/") < 0) { continue; } logger.debug("unpacking {}...", file.getName()); java.io.File f = new java.io.File(destFileName); if (file.isDirectory()) { // if its a directory, create it boolean ok = f.mkdir(); if (!ok) { logger.warn("Could not create directory {}", f.getAbsolutePath()); } continue; } is = new BufferedInputStream(jar.getInputStream(file)); fos = new BufferedOutputStream(new FileOutputStream(f)); LpeStreamUtils.pipe(is, fos); } logger.debug("Unpacking jar file done."); } catch (IOException e) { throw e; } finally { if (jar != null) { jar.close(); } if (fos != null) { fos.close(); } if (is != null) { is.close(); } } }
From source file:rubah.runtime.classloader.RubahClassloader.java
@Override public InputStream getResourceAsStream(String name) { JarFile jarFile = null; try {//from w w w.java 2s .c om VersionManager u = VersionManager.getInstance(); Version v = u.getRunningVersion(); File f = VersionManager.getInstance().getJarFile(v); jarFile = new JarFile(f); JarEntry entry = jarFile.getJarEntry(name); if (entry != null) { try { byte[] ret = IOUtils.toByteArray(jarFile.getInputStream(entry)); return new ByteArrayInputStream(ret); } catch (IOException e) { throw new Error(e); } } } catch (IOException e) { throw new Error(e); } finally { if (jarFile != null) try { jarFile.close(); } catch (IOException e) { // Don't care } } return super.getResourceAsStream(name); }
From source file:org.apache.archiva.rest.services.DefaultBrowseService.java
private void closeQuietly(JarFile jarFile) { if (jarFile != null) { try {// w w w .j a va 2 s . c om jarFile.close(); } catch (IOException e) { log.warn("ignore error closing jarFile {}", jarFile.getName()); } } }
From source file:org.apache.hadoop.hive.ql.exec.tez.HivePreWarmProcessor.java
@Override public void run(Map<String, LogicalInput> inputs, Map<String, LogicalOutput> outputs) throws Exception { if (prewarmed) { /* container reuse */ return;/* ww w. j av a 2s .co m*/ } for (LogicalInput input : inputs.values()) { input.start(); } for (LogicalOutput output : outputs.values()) { output.start(); } /* these are things that goes through singleton initialization on most queries */ FileSystem fs = FileSystem.get(conf); Mac mac = Mac.getInstance("HmacSHA1"); ReadaheadPool rpool = ReadaheadPool.getInstance(); ShimLoader.getHadoopShims(); URL hiveurl = new URL("jar:" + DagUtils.getInstance().getExecJarPathLocal() + "!/"); JarURLConnection hiveconn = (JarURLConnection) hiveurl.openConnection(); JarFile hivejar = hiveconn.getJarFile(); try { Enumeration<JarEntry> classes = hivejar.entries(); while (classes.hasMoreElements()) { JarEntry je = classes.nextElement(); if (je.getName().endsWith(".class")) { String klass = je.getName().replace(".class", "").replaceAll("/", "\\."); if (klass.indexOf("ql.exec") != -1 || klass.indexOf("ql.io") != -1) { /* several hive classes depend on the metastore APIs, which is not included * in hive-exec.jar. These are the relatively safe ones - operators & io classes. */ if (klass.indexOf("vector") != -1 || klass.indexOf("Operator") != -1) { JavaUtils.loadClass(klass); } } } } } finally { hivejar.close(); } prewarmed = true; }
From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java
@Override protected InputStream createPackStream(File source) throws IOException { File tmpfile = null;/*from w ww . j ava 2s. c o m*/ JarFile jar = null; try { tmpfile = File.createTempFile("izpack-compress", ".pack200", FileUtils.getTempDirectory()); CountingOutputStream proxyOutputStream = new CountingOutputStream(FileUtils.openOutputStream(tmpfile)); OutputStream bufferedStream = IOUtils.buffer(proxyOutputStream); Pack200.Packer packer = createPack200Packer(this.packFile); jar = new JarFile(this.packFile.getFile()); packer.pack(jar, bufferedStream); bufferedStream.flush(); this.packFile.setSize(proxyOutputStream.getByteCount()); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(FileUtils.openInputStream(tmpfile), out); out.close(); return new ByteArrayInputStream(out.toByteArray()); } finally { if (jar != null) { jar.close(); } FileUtils.deleteQuietly(tmpfile); } }