List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:org.springfield.lou.application.ApplicationManager.java
private void processUploadedWar(File warfile, String wantedname) { // lets first check some vitals to check what it is String warfilename = warfile.getName(); if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) { // ok so filename checks out is smt_[name]app.war format String appname = warfilename.substring(4, warfilename.length() - 7); if (wantedname.equals(appname)) { // ok found file is the wanted file // format "29-Aug-2013-16:55" System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING"); Date now = new Date(); SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy-HH:mm"); String datestring = df.format(now); String writedir = "/springfield/lou/apps/" + appname + "/" + datestring; // create the node Html5AvailableApplication vapp = getAvailableApplication(appname); String newbody = "<fsxml><properties></properties></fsxml>"; ServiceInterface smithers = ServiceManager.getService("smithers"); if (smithers == null) return; FsNode tnode = Fs.getNode("/domain/internal/service/lou/apps/" + appname); if (tnode == null) { smithers.put("/domain/internal/service/lou/apps/" + appname + "/properties", newbody, "text/xml"); }/*w w w . ja v a 2 s .c om*/ smithers.put( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring + "/properties", newbody, "text/xml"); // make all the dirs we need File md = new File(writedir); md.mkdirs(); md = new File(writedir + "/war"); md.mkdirs(); md = new File(writedir + "/jar"); md.mkdirs(); md = new File(writedir + "/components"); md.mkdirs(); md = new File(writedir + "/css"); md.mkdirs(); md = new File(writedir + "/libs"); md.mkdirs(); try { JarFile war = new JarFile(warfile); // ok lets first find the jar file ! JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar"); if (entry != null) { byte[] bytes = readJarEntryToBytes(war.getInputStream(entry)); writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar"); } // unpack all in eddie dir Enumeration<JarEntry> iter = war.entries(); while (iter.hasMoreElements()) { JarEntry lentry = iter.nextElement(); //System.out.println("LI="+lentry.getName()); String lname = lentry.getName(); if (!lname.endsWith("/")) { int pos = lname.indexOf("/" + appname + "/"); if (pos != -1) { String nname = lname.substring(pos + appname.length() + 2); String dname = nname.substring(0, nname.lastIndexOf('/')); File de = new File(writedir + "/" + dname); de.mkdirs(); byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry)); writeBytesToFile(bytes, writedir + "/" + nname); } } } war.close(); File ren = new File("/springfield/lou/uploaddir/" + warfilename); File nen = new File(writedir + "/war/smt_" + appname + "app.war"); //System.out.println("REN="+warfilename); //System.out.println("REN="+writedir+"/war/smt_"+appname+"app.war"); ren.renameTo(nen); loadAvailableApps(); // should we make in development or production based on autodeploy ? vapp = getAvailableApplication(appname); if (vapp != null) { String mode = vapp.getAutoDeploy(); if (appname.equals("dashboard")) { mode = "development/production"; } System.out.println("APPNAME=" + appname + " mode=" + mode); if (mode.equals("production")) { makeProduction(appname, datestring); } else if (mode.equals("development")) { makeDevelopment(appname, datestring); } else if (mode.equals("development/production")) { makeDevelopment(appname, datestring); makeProduction(appname, datestring); } } /* Html5ApplicationInterface app = getApplication("/domain/webtv/html5application/dashboard"); if (app!=null) { DashboardApplication dapp = (DashboardApplication)app; dapp.newApplicationFound(appname); } */ // lets tell set the available variable to tell the others we have it. FsNode unode = Fs .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring); if (unode != null) { String warlist = unode.getProperty("waravailableat"); if (warlist == null || warlist.equals("")) { Fs.setProperty( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring, "waravailableat", LazyHomer.myip); } else { System.out.println("BUG ? Already available war " + warlist + " a=" + appname); } } } catch (Exception e) { System.out.println("VERSION NOT READY STILL UPLOADING? RETRY WILL HAPPEN SOON"); } } } }
From source file:org.tinygroup.jspengine.compiler.TagLibraryInfoImpl.java
/** * Constructor which builds a TagLibraryInfoImpl by parsing a TLD. *///w w w. j ava2 s . c o m public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn, String[] location, ErrorDispatcher err) throws JasperException { super(prefix, uriIn); this.ctxt = ctxt; this.parserController = pc; this.pageInfo = pc.getCompiler().getPageInfo(); this.err = err; InputStream in = null; JarFile jarFile = null; if (location == null) { // The URI points to the TLD itself or to a JAR file in which the // TLD is stored location = generateTLDLocation(uri, ctxt); } try { if (!location[0].endsWith("jar")) { // Location points to TLD file try { in = getResourceAsStream(location[0]); if (in == null) { throw new FileNotFoundException(location[0]); } } catch (FileNotFoundException ex) { err.jspError("jsp.error.file.not.found", location[0]); } parseTLD(ctxt, location[0], in, null); // Add TLD to dependency list PageInfo pageInfo = ctxt.createCompiler(false).getPageInfo(); if (pageInfo != null) { pageInfo.addDependant(location[0]); } } else { // Tag library is packaged in JAR file try { URL jarFileUrl = new URL("jar:" + location[0] + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); jarFile = conn.getJarFile(); ZipEntry jarEntry = jarFile.getEntry(location[1]); in = jarFile.getInputStream(jarEntry); parseTLD(ctxt, location[0], in, jarFileUrl); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString()); } } } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { } } } }
From source file:org.b3log.latke.ioc.ClassPathResolver.java
/** * scan the jar to get the URLS of the Classes. * * @param rootDirResource which is "Jar" * @param subPattern subPattern/* w w w.jav a 2s . co m*/ * @return the URLs of all the matched classes */ private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource, final String subPattern) { final Set<URL> result = new LinkedHashSet<URL>(); JarFile jarFile = null; String jarFileUrl; String rootEntryPath = null; URLConnection con; boolean newJarFile = false; try { con = rootDirResource.openConnection(); if (con instanceof JarURLConnection) { final JarURLConnection jarCon = (JarURLConnection) con; jarCon.setUseCaches(false); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); final JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = jarEntry != null ? jarEntry.getName() : ""; } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the // protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" // prefix. final String urlFile = rootDirResource.getFile(); final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } } catch (final IOException e) { LOGGER.log(Level.ERROR, "reslove jar File error", e); return result; } try { if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { // Root entry path must end with slash to allow for proper // matching. // The Sun JRE does not return a slash here, but BEA JRockit // does. rootEntryPath = rootEntryPath + "/"; } for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { final JarEntry entry = (JarEntry) entries.nextElement(); final String entryPath = entry.getName(); String relativePath = null; if (entryPath.startsWith(rootEntryPath)) { relativePath = entryPath.substring(rootEntryPath.length()); if (AntPathMatcher.match(subPattern, relativePath)) { if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } result.add(new URL(rootDirResource, relativePath)); } } } return result; } catch (final IOException e) { LOGGER.log(Level.ERROR, "parse the JarFile error", e); } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { try { jarFile.close(); } catch (final IOException e) { LOGGER.log(Level.WARN, " occur error when closing jarFile", e); } } } return result; }
From source file:org.openmrs.module.SqlDiffFileParser.java
/** * Get the diff map. Return a sorted map<version, sql statements> * * @return SortedMap<String, String> * @throws ModuleException// w w w .jav a2 s . c o m */ public static SortedMap<String, String> getSqlDiffs(Module module) throws ModuleException { if (module == null) { throw new ModuleException("Module cannot be null"); } SortedMap<String, String> map = new TreeMap<String, String>(new VersionComparator()); InputStream diffStream = null; // get the diff stream JarFile jarfile = null; try { try { jarfile = new JarFile(module.getFile()); } catch (IOException e) { throw new ModuleException("Unable to get jar file", module.getName(), e); } diffStream = ModuleUtil.getResourceFromApi(jarfile, module.getModuleId(), module.getVersion(), SQLDIFF_CHANGELOG_FILENAME); if (diffStream == null) { // Try the old way. Loading from the root of the omod ZipEntry diffEntry = jarfile.getEntry(SQLDIFF_CHANGELOG_FILENAME); if (diffEntry == null) { log.debug("No sqldiff.xml found for module: " + module.getName()); return map; } else { try { diffStream = jarfile.getInputStream(diffEntry); } catch (IOException e) { throw new ModuleException("Unable to get sql diff file stream", module.getName(), e); } } } try { // turn the diff stream into an xml document Document diffDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a DTD) we return an InputSource // with no data at the end, causing the parser to ignore the DTD. return new InputSource(new StringReader("")); } }); diffDoc = db.parse(diffStream); } catch (Exception e) { throw new ModuleException("Error parsing diff sqldiff.xml file", module.getName(), e); } Element rootNode = diffDoc.getDocumentElement(); String diffVersion = rootNode.getAttribute("version"); if (!validConfigVersions().contains(diffVersion)) { throw new ModuleException("Invalid config version: " + diffVersion, module.getModuleId()); } NodeList diffNodes = getDiffNodes(rootNode, diffVersion); if (diffNodes != null && diffNodes.getLength() > 0) { int i = 0; while (i < diffNodes.getLength()) { Element el = (Element) diffNodes.item(i++); String version = getElement(el, diffVersion, "version"); String sql = getElement(el, diffVersion, "sql"); map.put(version, sql); } } } catch (ModuleException e) { if (diffStream != null) { try { diffStream.close(); } catch (IOException io) { log.error("Error while closing config stream for module: " + module.getModuleId(), io); } } // rethrow the moduleException throw e; } } finally { try { if (jarfile != null) { jarfile.close(); } } catch (IOException e) { log.warn("Unable to close jarfile: " + jarfile.getName()); } } return map; }
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl.java
protected void dispose(JarFile jarFile) { try {/* www . j a va2 s . c o m*/ jarFile.close(); } catch (IOException e) { log.warn("Unable to close jar file \"" + jarFile.getName() + "\"", e); } File file = new File(jarFile.getName()); if (file.exists() && !file.delete()) { log.warn("Unable to delete jar file \"" + jarFile.getName() + "\""); } }
From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java
/** * Parse the passed war file, try to read an enclosed jboss-web.xml and look for * virtual-hosts in it. If found, return one virtual host name. Else return localhost. * @param warFile File pointer pointing to a .war file * @return The name of a defined virtual host or localhost *//* www .ja v a 2 s . c om*/ private String getVhostFromWarFile(File warFile) { JarFile jfile = null; InputStream is = null; try { jfile = new JarFile(warFile); JarEntry entry = jfile.getJarEntry("WEB-INF/jboss-web.xml"); if (entry != null) { is = jfile.getInputStream(entry); SAXBuilder saxBuilder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver .getDtdAndXsdSkippingInstance(); saxBuilder.setEntityResolver(entityResolver); Document doc = saxBuilder.build(is); Element root = doc.getRootElement(); // <jboss-web> List<Element> vHosts = root.getChildren("virtual-host"); if (vHosts == null || vHosts.isEmpty()) { if (log.isDebugEnabled()) log.debug("No vhosts found in war file, using " + LOCALHOST); return LOCALHOST; } // So we have vhost, just return one of them, this is enough Element vhost = vHosts.get(0); return vhost.getText(); } } catch (Exception ioe) { log.warn("Exception when getting vhost from war file : " + ioe.getMessage()); } finally { if (jfile != null) { if (is != null) { try { // see http://bugs.sun.com/view_bug.do?bug_id=6735255 for why we do this is.close(); } catch (IOException e) { log.info("Exception when trying to close the war file stream: " + e.getMessage()); } } try { jfile.close(); } catch (IOException e) { log.info("Exception when trying to close the war file: " + e.getMessage()); } } } // We're not able to determine a vhost, so return localhost return LOCALHOST; }
From source file:com.vectorcast.plugins.vectorcastexecution.VectorCASTSetup.java
/** * Perform the build step. Copy the scripts from the archive/directory to the workspace * @param build build//from w w w .j a v a 2 s. c o m * @param workspace workspace * @param launcher launcher * @param listener listener */ @Override public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) { FilePath destScriptDir = new FilePath(workspace, "vc_scripts"); JarFile jFile = null; try { String path = null; String override_path = System.getenv("VCAST_VC_SCRIPTS"); String extra_script_path = SCRIPT_DIR; Boolean directDir = false; if (override_path != null && !override_path.isEmpty()) { path = override_path; extra_script_path = ""; directDir = true; String msg = "VectorCAST - overriding vc_scripts. Copying from '" + path + "'"; Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.ALL, msg); } else { path = VectorCASTSetup.class.getProtectionDomain().getCodeSource().getLocation().getPath(); path = URLDecoder.decode(path, "utf-8"); } File testPath = new File(path); if (testPath.isFile()) { // Have jar file... jFile = new JarFile(testPath); Enumeration<JarEntry> entries = jFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith("scripts")) { String fileOrDir = entry.getName().substring(8); // length of scripts/ FilePath dest = new FilePath(destScriptDir, fileOrDir); if (entry.getName().endsWith("/")) { // Directory, create destination dest.mkdirs(); } else { // File, copy it InputStream is = VectorCASTSetup.class.getResourceAsStream("/" + entry.getName()); dest.copyFrom(is); } } } } else { // Have directory File scriptDir = new File(path + extra_script_path); processDir(scriptDir, "./", destScriptDir, directDir); } } catch (IOException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } finally { if (jFile != null) { try { jFile.close(); } catch (IOException ex) { // Ignore } } } }
From source file:org.kepler.objectmanager.ActorMetadata.java
/** * search the classpath for a specific class and return the file. In the * tradition of ptolemy, this will also search for moml files with a class * definition. this is required for composite actors. * /*from w w w .j a va 2 s. c o m*/ * @param className * the name of the class to search for * @param workDir * the directory where temp files can be created */ protected File searchClasspath(String className) throws FileNotFoundException { // separate the class name from the package path String actualClassName = className.substring(className.lastIndexOf(".") + 1, className.length()); String packagePath = className.substring(0, className.lastIndexOf(".")); String[] packagePathStruct = packagePath.split("\\."); // get the classpath so we can search for the class files String classpath = System.getProperty("java.class.path"); String sep = System.getProperty("path.separator"); StringTokenizer st = new StringTokenizer(classpath, sep); while (st.hasMoreTokens()) { String path = st.nextToken(); File pathDir = new File(path); if (pathDir.isDirectory()) { // search the directory for the file if (matchDirectoryPath(pathDir, packagePathStruct, 0)) { // now we found a candidate...see if the class is in there File classDir = new File(pathDir.getAbsolutePath() + File.separator + packagePath.replace('.', File.separator.toCharArray()[0])); File[] classDirFiles = classDir.listFiles(); for (int i = 0; i < classDirFiles.length; i++) { String dirFileName = classDirFiles[i].getName(); if (dirFileName.indexOf(".") != -1) { String extension = dirFileName.substring(dirFileName.lastIndexOf("."), dirFileName.length()); String prefix = dirFileName.substring(0, dirFileName.lastIndexOf(".")); if (actualClassName.equals(prefix) && (extension.equals(".class") || extension.equals(".xml"))) { // search for xml or class files return classDirFiles[i]; } } } } } else if (pathDir.isFile()) { // search a jar file for the file. if it's not a jar file, // ignore it try { String entryName = className.replace('.', '/') + ".class"; JarFile jarFile = null; try { jarFile = new JarFile(pathDir); // this looks for a class file JarEntry entry = jarFile.getJarEntry(entryName); if (entry != null) { // get the class file from the jar and return it return pathDir; } else { // look for the xml file instead entryName = className.replace('.', '/') + ".xml"; entry = jarFile.getJarEntry(entryName); if (entry != null) { return pathDir; } } } finally { if (jarFile != null) { jarFile.close(); } } } catch (Exception e) { // keep going if this isn't a jar file continue; } } } throw new FileNotFoundException("Cannot find the specified class " + "file in the classpath."); }
From source file:org.colombbus.tangara.Configuration.java
private boolean testExecutionMode() { executionMode = false;/*ww w . ja v a2s.c o m*/ JarFile file = null; try { file = new JarFile(getTangaraPath()); ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME); if (entry != null) { executionMode = true; System.out.println("execution mode detected"); Properties executionProperties = new Properties(); InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME); executionProperties.load(ips); if (executionProperties.containsKey("main-program")) { String mainTangaraFile = executionProperties.getProperty("main-program"); System.out.println("main tangara file: " + mainTangaraFile); properties.setProperty("main-program", mainTangaraFile); } else { System.err.println("error : main program not specified"); } if (executionProperties.containsKey("language")) { String language = executionProperties.getProperty("language"); properties.setProperty("language", language); System.out.println("language: " + language); } else { System.err.println("error : language not specified"); } if (executionProperties.containsKey("resources")) { String resources = executionProperties.getProperty("resources"); properties.setProperty("program.resources", resources); System.out.println("resources: " + resources); } else { System.err.println("error : resources not specified"); } } } catch (IOException e) { e.printStackTrace(); } finally { if (file != null) { try { file.close(); } catch (IOException e) { System.err.println("error while closing tangara JAR file"); } } } return executionMode; }
From source file:com.orange.mmp.dao.flf.ModuleDaoFlfImpl.java
public Module[] find(Module module) throws MMPDaoException { if (module == null) { throw new MMPDaoException("missing or bad data access object"); }/*ww w . j a va 2 s . c om*/ FilenameFilter jarFilter = new SuffixFileFilter(".jar"); File widgetsFiles[] = new File(this.path).listFiles(jarFilter); if (widgetsFiles == null) return new Module[0]; ArrayList<Module> list = new ArrayList<Module>(); JarFile jarFile = null; try { for (File found : widgetsFiles) { jarFile = new JarFile(found); Manifest manifest = jarFile.getManifest(); boolean match = (module.getId() == null && module.getLocation() == null && module.getVersion() == null && module.getName() == null && module.getCategory() == null); if (!match) { boolean goOnchecking = true; if (module.getLocation() != null && goOnchecking) { match = found.toURI().toString().equals(module.getLocation().toString()); goOnchecking = false; } if (module.getId() != null) { match = (manifest.getMainAttributes().getValue(MODULE_ID_HEADER) != null && manifest.getMainAttributes().getValue(MODULE_ID_HEADER).equals(module.getId())); goOnchecking = false; } if (module.getVersion() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_VERSION_HEADER).equals(module.getVersion())); goOnchecking = match; } if (module.getName() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_NAME_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_NAME_HEADER).equals(module.getName())); goOnchecking = match; } if (module.getCategory() != null && goOnchecking) { match = (manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER) != null && manifest .getMainAttributes().getValue(MODULE_CATEGORY_HEADER).equals(module.getCategory())); goOnchecking = match; } } if (match) { Module foundModule = new Module(); foundModule.setId(manifest.getMainAttributes().getValue(MODULE_ID_HEADER)); foundModule.setName(manifest.getMainAttributes().getValue(MODULE_NAME_HEADER)); foundModule .setVersion(new Version(manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER))); foundModule.setCategory(manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER)); foundModule.setLastModified(found.lastModified()); foundModule.setLocation(found.toURI()); list.add(foundModule); } jarFile.close(); } } catch (IOException ioe) { throw new MMPDaoException("failed to load module"); } finally { try { if (jarFile != null) jarFile.close(); } catch (IOException ioe) { //Nop just log } } Module[] modulesList = new Module[list.size()]; return list.toArray(modulesList); }