List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:it.geosolutions.geoserver.rest.GeoServerRESTPublisher.java
/** * Create a new ImageMosaic with the provided configuration provided as a zip file. * /* w w w . ja va 2 s . c o m*/ * <p> * With the options configure we can decide whether or not to configure or not the coverages contained in the ImageMosaic. * * @param workspace the GeoServer workspace * @param coverageStore the GeoServer coverageStore * @param the absolute path to the file to upload * @param configureOpt tells GeoServer whether to configure all coverages in this mosaic (ALL) or none of them (NONE). * * @return <code>true</code> if the call succeeds or <code>false</code> otherwise. * @since geoserver-2.4.0, geoserver-mng-1.6.0 */ public boolean createImageMosaic(String workspace, String coverageStore, String path, ConfigureCoveragesOption configureOpt) { // checks checkString(workspace); checkString(coverageStore); checkString(path); final File zipFile = new File(path); if (!zipFile.exists() || !zipFile.isFile() || !zipFile.canRead()) { throw new IllegalArgumentException( "The provided pathname does not point to a valide zip file: " + path); } // is it a zip? ZipFile zip = null; try { zip = new ZipFile(zipFile); zip.getName(); } catch (Exception e) { LOGGER.trace(e.getLocalizedMessage(), e.getStackTrace()); throw new IllegalArgumentException( "The provided pathname does not point to a valide zip file: " + path); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { // swallow LOGGER.trace(e.getLocalizedMessage(), e.getStackTrace()); } } } // create URL StringBuilder ss = HTTPUtils.append(restURL, "/rest/workspaces/", workspace, "/coveragestores/", coverageStore, "/", UploadMethod.EXTERNAL.toString(), ".imagemosaic"); switch (configureOpt) { case ALL: break; case NONE: ss.append("?configure=none"); break; default: throw new IllegalArgumentException("Unrecognized COnfigureOption: " + configureOpt); } String sUrl = ss.toString(); // POST request String result = HTTPUtils.put(sUrl, zipFile, "application/zip", gsuser, gspass); return result != null; }
From source file:com.web.server.WarDeployer.java
/** * This method deploys the war in exploded form and configures it. * @param file/*from ww w. j a va 2 s. c o m*/ * @param customClassLoader * @param warDirectoryPath */ public void extractWar(File file, WebClassLoader customClassLoader) { StringBuffer classPath = new StringBuffer(); int numBytes; try { ConcurrentHashMap jspMap = new ConcurrentHashMap(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; //String fileName=file.getName(); String directoryName = file.getName(); directoryName = directoryName.substring(0, directoryName.indexOf('.')); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); //logger.info("file://"+warDirectoryPath+"/WEB-INF/classes/"); new WebServer().addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"), customClassLoader); //new WebServer().addURL(new URL("file://"+warDirectoryPath+"/"),customClassLoader); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ze = entries.nextElement(); // //System.out.println("Unzipping " + ze.getName()); String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //System.out.println(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jsp")) { jspMap.put(ze.getName(), filePath); } else if (ze.getName().endsWith(".jar")) { new WebServer().addURL( new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()), customClassLoader); classPath.append(filePath); classPath.append(";"); } } } zip.close(); Set jsps = jspMap.keySet(); Iterator jspIterator = jsps.iterator(); classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes/;"); ArrayList<String> jspFiles = new ArrayList(); //System.out.println(classPath.toString()); if (jspIterator.hasNext()) new WebServer().addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"), customClassLoader); while (jspIterator.hasNext()) { String filepackageInternal = (String) jspIterator.next(); String filepackageInternalTmp = filepackageInternal; if (filepackageInternal.lastIndexOf('/') == -1) { filepackageInternal = ""; } else { filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/')) .replace("/", "."); filepackageInternal = "." + filepackageInternal; } createDirectory(scanDirectory + "/temp/" + directoryName); File jspFile = new File((String) jspMap.get(filepackageInternalTmp)); String fName = jspFile.getName(); String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp"; //String fileCreated=new JspCompiler().compileJsp((String) jspMap.get(filepackageInternalTmp), scanDirectory+"/temp/"+fileName, "com.web.server"+filepackageInternal,classPath.toString()); synchronized (customClassLoader) { String fileNameInWar = filepackageInternalTmp; jspFiles.add(fileNameInWar.replace("/", "\\")); if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) { customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"), "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension); } else { customClassLoader.addURL("/" + fileNameInWar, "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension); } } } if (jspFiles.size() > 0) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(customClassLoader); try { JspC jspc = new JspC(); jspc.setUriroot(scanDirectory + "/" + directoryName + "/"); jspc.setAddWebXmlMappings(false); jspc.setCompile(true); jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/"); jspc.setPackage("com.web.server"); StringBuffer buffer = new StringBuffer(); for (String jspFile : jspFiles) { buffer.append(","); buffer.append(jspFile); } String jsp = buffer.toString(); jsp = jsp.substring(1, jsp.length()); System.out.println(jsp); jspc.setJspFiles(jsp); jspc.execute(); } catch (Throwable je) { je.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(oldCL); } Thread.currentThread().setContextClassLoader(customClassLoader); } try { new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"), customClassLoader); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } try { new MessagingClassConstruct().getMessagingClass(messagedigester, new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"), customClassLoader, messagingClassMap); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } webxmldigester.setNamespaceAware(true); webxmldigester.setValidating(true); //digester.setRules(null); FileInputStream webxml = new FileInputStream( scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml"); InputSource is = new InputSource(webxml); try { System.out.println("SCHEMA"); synchronized (webxmldigester) { //webxmldigester.set("config/web-app_2_4.xsd"); WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is); servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig); } webxml.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (FileNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (Exception ex) { } }
From source file:org.hippoecm.frontend.plugins.console.menu.content.ContentImportDialog.java
@Override protected void onOk() { final FileUpload upload = fileUploadField.getFileUpload(); int uuidOpt = uuidOpts.getFirstKey(uuidBehavior); int derefOpt = derefOpts.getFirstKey(derefBehavior); try {/*from w ww .j a v a 2 s . c o m*/ if (upload == null && StringUtils.isEmpty(xmlInput)) { warn("No file was uploaded and no xml input provided. Nothing to import"); return; } String absPath = nodeModel.getNode().getPath(); // If save-after-import is enabled and the import fails, we do a Session.refresh(false) to revert any // changes done by the import. However, any changes done *before* the import will then also be lost. // We therefore have to save before importing, so all changes before the import are persisted regardless // of what happens during the import. if (saveBehavior) { nodeModel.getNode().getSession().save(); } File tempFile = null; ZipFile zipFile = null; InputStream in = null; InputStream esvIn = null; OutputStream out = null; try { final HippoSession session = (HippoSession) UserSession.get().getJcrSession(); List<String> nodesBefore = new ArrayList<>(); if (generate) { for (NodeIterator nodeIterator = nodeModel.getNode().getNodes(); nodeIterator.hasNext();) { final Node node = nodeIterator.nextNode(); nodesBefore.add(node.getPath()); } } if (upload != null) { final String fileName = upload.getClientFileName(); if (fileName.endsWith(".zip")) { tempFile = File.createTempFile("package", "zip"); out = new FileOutputStream(tempFile); in = upload.getInputStream(); IOUtils.copy(in, out); out.close(); out = null; zipFile = new ZipFile(tempFile); ContentResourceLoader contentResourceLoader = new ZipFileContentResourceLoader(zipFile); esvIn = contentResourceLoader.getResourceAsStream("esv.xml"); session.importEnhancedSystemViewXML(absPath, esvIn, uuidOpt, derefOpt, contentResourceLoader); } else if (fileName.endsWith(".xml")) { in = new BufferedInputStream(upload.getInputStream()); session.importEnhancedSystemViewXML(absPath, in, uuidOpt, derefOpt, null); } else { warn("Unrecognized file: only .xml and .zip can be processed"); return; } } else { in = new ByteArrayInputStream(xmlInput.getBytes("UTF-8")); session.importEnhancedSystemViewXML(absPath, in, uuidOpt, derefOpt, null); } if (generate) { final Node newNode = findNewNode(nodesBefore, nodeModel.getNode()); if (newNode != null) { log.debug("Applying new translation ids on node: " + newNode.getPath()); newNode.accept(new GenerateNewTranslationIdsVisitor()); } } if (saveBehavior) { nodeModel.getNode().getSession().save(); } } finally { if (saveBehavior) { nodeModel.getNode().getSession().refresh(false); } IOUtils.closeQuietly(out); IOUtils.closeQuietly(esvIn); IOUtils.closeQuietly(in); if (zipFile != null) { try { zipFile.close(); } catch (Exception ignore) { } } FileUtils.deleteQuietly(tempFile); } } catch (RepositoryException ex) { log.error("Error initializing content in '" + nodeModel.getItemModel().getPath() + "' : " + ex.getMessage(), ex); error("Import failed: " + ex.getMessage()); } catch (IOException ex) { log.error("IOException initializing content in '" + nodeModel.getItemModel().getPath() + "' : " + ex.getMessage(), ex); error("Import failed: " + ex.getMessage()); } }
From source file:org.nuxeo.build.ant.ZipDiffTask.java
@Override public void execute() throws BuildException { ZipFile zipfile1 = null; ZipFile zipfile2 = null;/*from ww w.j a v a 2 s . c om*/ try { zipfile1 = new ZipFile(file1); zipfile2 = new ZipFile(file2); Set<String> set1 = new LinkedHashSet<>(); for (Enumeration<? extends ZipEntry> zipEntries = zipfile1.entries(); zipEntries.hasMoreElements();) { set1.add((zipEntries.nextElement()).getName()); } Set<String> set2 = new LinkedHashSet<>(); for (Enumeration<? extends ZipEntry> zipEntries = zipfile2.entries(); zipEntries.hasMoreElements();) { set2.add((zipEntries.nextElement()).getName()); } try { if (includesfile != null) { includesfile.createNewFile(); fileWriter = new FileWriter(includesfile); } // includes (files from file1 not present or differ in file2) for (Iterator<String> i = set1.iterator(); i.hasNext();) { String filename = i.next(); if (!set2.contains(filename)) { log("Only in " + file1.getName() + ": " + filename, Project.MSG_INFO); include(filename, fileWriter); continue; } set2.remove(filename); if (!ignoreContent && !filename.matches(ignoreContentPattern)) { try { if (!IOUtils.contentEquals(zipfile1.getInputStream(zipfile1.getEntry(filename)), zipfile2.getInputStream(zipfile2.getEntry(filename)))) { log("Content differs: " + filename, Project.MSG_INFO); include(filename, fileWriter); } } catch (IOException e) { log(e, Project.MSG_WARN); } } } } catch (IOException e) { throw new BuildException(e); } finally { IOUtils.closeQuietly(fileWriter); } // excludes (files from file2 not present in file1) try { if (excludesfile != null) { excludesfile.createNewFile(); fileWriter = new FileWriter(excludesfile); } for (Iterator<String> i = set2.iterator(); i.hasNext();) { String filename = i.next(); log("Only in " + file2.getName() + ": " + filename, Project.MSG_INFO); exclude(filename, fileWriter); } } catch (IOException e) { throw new BuildException(e); } finally { IOUtils.closeQuietly(fileWriter); } } catch (IOException e) { throw new BuildException("Error opening " + file1 + " or " + file2, e); } finally { if (zipfile1 != null) { try { zipfile1.close(); } catch (IOException e) { throw new BuildException(e); } } if (zipfile2 != null) { try { zipfile2.close(); } catch (IOException e) { throw new BuildException(e); } } } }
From source file:com.serotonin.m2m2.Main.java
private static void openZipFiles() throws Exception { ProcessEPoll pep = new ProcessEPoll(); try {// w w w. j a v a 2s .c om new Thread(pep).start(); File[] zipFiles = new File(new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString()) .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".zip"); } }); if ((zipFiles == null) || (zipFiles.length == 0)) return; for (File file : zipFiles) { if (!file.isFile()) { continue; } ZipFile zip = new ZipFile(file); try { Properties props = getProperties(zip); String moduleName = props.getProperty("name"); if (moduleName == null) { throw new RuntimeException("name not defined in module properties"); } if (!ModuleUtils.validateName(moduleName)) { throw new RuntimeException(new StringBuilder().append("Module name '").append(moduleName) .append("' is invalid").toString()); } File moduleDir = new File( new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString(), moduleName); if (moduleDir.exists()) LOG.info(new StringBuilder().append("Upgrading module ").append(moduleName).toString()); else { LOG.info(new StringBuilder().append("Installing module ").append(moduleName).toString()); } String persistDirs = props.getProperty("persistPaths"); File moduleSaveDir = new File(new StringBuilder().append(moduleDir).append(".save").toString()); if (!org.apache.commons.lang3.StringUtils.isBlank(persistDirs)) { String[] paths = persistDirs.split(","); for (String path : paths) { path = path.trim(); if (!org.apache.commons.lang3.StringUtils.isBlank(path)) { File from = new File(moduleDir, path); File to = new File(moduleSaveDir, path); if (from.exists()) { if (from.isDirectory()) moveDir(from, to); else { FileUtils.moveFile(from, to); } } } } } deleteDir(moduleDir); if (moduleSaveDir.exists()) moveDir(moduleSaveDir, moduleDir); else { moduleDir.mkdirs(); } Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(moduleDir, name); if (entry.isDirectory()) entryFile.mkdirs(); else { writeFile(entryFile, zip.getInputStream(entry)); } } File moduleWorkDir = new File(moduleDir, "work"); if (moduleWorkDir.exists()) { moveDir(moduleWorkDir, new File(Common.MA_HOME, "work")); } if (HostUtils.isLinux()) { String permissions = props.getProperty("permissions"); if (!org.apache.commons.lang3.StringUtils.isBlank(permissions)) { String[] s = permissions.split(","); for (String permission : s) { setPermission(pep, moduleName, moduleDir, permission); } } } zip.close(); } catch (Exception e) { LOG.warn(new StringBuilder().append("Error while opening zip file ").append(file.getName()) .append(". Is this module built for the core version that you are using? Module ignored.") .toString(), e); } finally { zip.close(); } file.delete(); } } finally { pep.waitForAll(); pep.terminate(); } }
From source file:net.sourceforge.jweb.maven.mojo.InWarMinifyMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (disabled) return;//from w w w.j av a2 s . c o m processConfiguration(); String name = this.getBuilddir().getAbsolutePath() + File.separator + this.getFinalName() + "." + this.getPacking(); this.getLog().info(name); MinifyFileFilter fileFilter = new MinifyFileFilter(); int counter = 0; try { File finalWarFile = new File(name); File tempFile = File.createTempFile(finalWarFile.getName(), null); tempFile.delete();//check deletion boolean renameOk = finalWarFile.renameTo(tempFile); if (!renameOk) { getLog().error("Can not rename file, please check."); } ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile)); ZipFile zipFile = new ZipFile(tempFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); //no compress, just transfer to war if (!fileFilter.accept(entry)) { getLog().debug("nocompress entry: " + entry.getName()); out.putNextEntry(entry); InputStream inputStream = zipFile.getInputStream(entry); byte[] buf = new byte[512]; int len = -1; while ((len = inputStream.read(buf)) > 0) { out.write(buf, 0, len); } inputStream.close(); continue; } File sourceTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp" + File.separator + counter + ".tmp"); File destTmp = new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp" + File.separator + counter + ".min.tmp"); FileUtils.writeStringToFile(sourceTmp, ""); FileUtils.writeStringToFile(destTmp, ""); //assemble arguments String[] provied = getYuiArguments(); int length = (provied == null ? 0 : provied.length); length += 5; int i = 0; String[] ret = new String[length]; ret[i++] = "--type"; ret[i++] = (entry.getName().toLowerCase().endsWith(".css") ? "css" : "js"); if (provied != null) { for (String s : provied) { ret[i++] = s; } } ret[i++] = sourceTmp.getAbsolutePath(); ret[i++] = "-o"; ret[i++] = destTmp.getAbsolutePath(); try { InputStream in = zipFile.getInputStream(entry); FileUtils.copyInputStreamToFile(in, sourceTmp); in.close(); YUICompressorNoExit.main(ret); } catch (Exception e) { this.getLog().warn("compress error, this file will not be compressed:" + buildStack(e)); FileUtils.copyFile(sourceTmp, destTmp); } out.putNextEntry(new ZipEntry(entry.getName())); InputStream compressedIn = new FileInputStream(destTmp); byte[] buf = new byte[512]; int len = -1; while ((len = compressedIn.read(buf)) > 0) { out.write(buf, 0, len); } compressedIn.close(); String sourceSize = decimalFormat.format(sourceTmp.length() * 1.0d / 1024) + " KB"; String destSize = decimalFormat.format(destTmp.length() * 1.0d / 1024) + " KB"; getLog().info("compressed entry:" + entry.getName() + " [" + sourceSize + " ->" + destSize + "/" + numberFormat.format(1 - destTmp.length() * 1.0d / sourceTmp.length()) + "]"); counter++; } zipFile.close(); out.close(); FileUtils.cleanDirectory(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp")); FileUtils.forceDelete(new File(FileUtils.getUserDirectoryPath() + File.separator + ".mvntmp")); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.sweble.wikitext.engine.MassExpansionTest.java
private static NamedParametrizedSuite enumerateSuiteTestCasesFromZip(File zipFile) throws IOException { ZipFile zf = new ZipFile(zipFile); try {/*from w ww. ja v a 2s. com*/ Enumeration<? extends ZipEntry> entries = zf.entries(); String suiteName; { String zfname = zipFile.getName(); if (!zfname.toLowerCase().endsWith(".zip")) throw new InternalError(); suiteName = zfname.substring(0, zfname.length() - 4); } String testPrefix = suiteName + "/tests/"; String resourcesPrefix = suiteName + "/resources/"; Map<FileUrlKey, String> fileUrls = new HashMap<FileUrlKey, String>(); Map<String, ArticleDesc> articles = new HashMap<String, ArticleDesc>(); List<Object[]> testCases = new ArrayList<Object[]>(); while (entries.hasMoreElements()) { ZipEntry ze = (ZipEntry) entries.nextElement(); // Skip directories if (ze.getName().endsWith("/")) continue; long longSize = ze.getSize(); if (longSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Archives contains files too big to process!"); InputStream is = zf.getInputStream(ze); byte[] content = IOUtils.toByteArray(is); is.close(); String filename = ze.getName(); if (filename.startsWith(resourcesPrefix + "fileUrl-") && filename.endsWith(".txt")) { filename = filename.substring(resourcesPrefix.length()); Matcher m = FILE_URL_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Wrong 'fileUrl' pattern: " + ze.getName()); String encName = m.group(1); int width = Integer.parseInt(m.group(2)); int height = Integer.parseInt(m.group(3)); FileUrlKey key = new FileUrlKey(encName, width, height); fileUrls.put(key, new String(content, "UTF8")); } else if (filename.startsWith(resourcesPrefix + "retrieveWikitext-") && filename.endsWith(".wikitext")) { filename = filename.substring(resourcesPrefix.length()); Matcher m = ARTICLE_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Wrong 'retrieveWikitext' pattern: " + ze.getName()); String encName = m.group(1); long revision = Long.parseLong(m.group(2)); ArticleDesc article = new ArticleDesc(revision, new String(content, "UTF8")); articles.put(encName, article); } else if (filename.startsWith(testPrefix) && filename.endsWith(".txt")) { filename = filename.substring(testPrefix.length()); Matcher m = TEST_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Invalid test case filename: " + ze.getName()); String title = m.group(1); String test = new String(content, "UTF8"); testCases.add(new Object[] { title, fileUrls, articles, test }); } else { System.err.println("Ignored file in " + zipFile + ": " + ze.getName()); continue; } } Collections.sort(testCases, new Comparator<Object[]>() { @Override public int compare(Object[] o1, Object[] o2) { return ((String) o1[0]).compareTo((String) o2[0]); } }); return new NamedParametrizedSuite(zipFile.getName(), MassExpansionTest.class.getSimpleName(), testCases); } finally { zf.close(); } }
From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java
private File removeDuplicatesFromJar(File in, List<String> duplicates, Set<String> duplicatesAdded, ZipOutputStream duplicateZos, int num) { String target = targetDirectory.getAbsolutePath(); File tmp = new File(target, "unpacked-embedded-jars"); tmp.mkdirs();//from www . jav a2 s.co m String jarName = String.format("%s-%d.%s", Files.getNameWithoutExtension(in.getName()), num, Files.getFileExtension(in.getName())); File out = new File(tmp, jarName); if (out.exists()) { return out; } else { try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // Create a new Jar file final FileOutputStream fos; final ZipOutputStream jos; try { fos = new FileOutputStream(out); jos = new ZipOutputStream(fos); } catch (FileNotFoundException e1) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found"); return null; } final ZipFile inZip; try { inZip = new ZipFile(in); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if (!duplicates.contains(entry.getName())) { // copy the entry header to jos jos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, jos); currIn.close(); jos.closeEntry(); } //if it is duplicate, check the resource transformers else { boolean resourceTransformed = false; if (transformers != null) { for (ResourceTransformer transformer : transformers) { if (transformer.canTransformResource(entry.getName())) { getLog().info("Transforming " + entry.getName() + " using " + transformer.getClass().getName()); InputStream currIn = inZip.getInputStream(entry); transformer.processResource(entry.getName(), currIn, null); currIn.close(); resourceTransformed = true; break; } } } //if not handled by transformer, add (once) to duplicates jar if (!resourceTransformed) { if (!duplicatesAdded.contains(entry.getName())) { duplicatesAdded.add(entry.getName()); duplicateZos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, duplicateZos); currIn.close(); duplicateZos.closeEntry(); } } } } } catch (IOException e) { getLog().error("Cannot removing duplicates : " + e.getMessage()); return null; } try { inZip.close(); jos.close(); fos.close(); } catch (IOException e) { // ignore it. } getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath()); return out; }
From source file:com.app.server.WarDeployer.java
/** * This method deploys the war in exploded form and configures it. * /*from w w w . j a va 2s .c om*/ * @param file * @param customClassLoader * @param warDirectoryPath */ public void extractWar(File file, ClassLoader classLoader) { StringBuffer classPath = new StringBuffer(); int numBytes; WebClassLoader customClassLoader = null; CopyOnWriteArrayList<URL> jarUrls = new CopyOnWriteArrayList<URL>(); try { ConcurrentHashMap jspMap = new ConcurrentHashMap(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; // String fileName=file.getName(); String directoryName = file.getName(); directoryName = directoryName.substring(0, directoryName.indexOf('.')); try { /*ClassLoader classLoader = Thread.currentThread() .getContextClassLoader();*/ // log.info("file://"+warDirectoryPath+"/WEB-INF/classes/"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/")); // new WebServer().addURL(new // URL("file://"+warDirectoryPath+"/"),customClassLoader); } catch (Exception e) { log.error("syntax of the URL is incorrect", e); //e1.printStackTrace(); } String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jsp")) { jspMap.put(ze.getName(), filePath); } else if (ze.getName().endsWith(".jar")) { jarUrls.add(new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName())); classPath.append(filePath); classPath.append(";"); } } } zip.close(); Set jsps = jspMap.keySet(); Iterator jspIterator = jsps.iterator(); classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes;"); jarUrls.add(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/;")); ArrayList<String> jspFiles = new ArrayList(); // log.info(classPath.toString()); if (jspIterator.hasNext()) { jarUrls.add(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/")); customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); while (jspIterator.hasNext()) { String filepackageInternal = (String) jspIterator.next(); String filepackageInternalTmp = filepackageInternal; if (filepackageInternal.lastIndexOf('/') == -1) { filepackageInternal = ""; } else { filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/')) .replace("/", "."); filepackageInternal = "." + filepackageInternal; } createDirectory(scanDirectory + "/temp/" + directoryName); File jspFile = new File((String) jspMap.get(filepackageInternalTmp)); String fName = jspFile.getName(); String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp"; // String fileCreated=new JspCompiler().compileJsp((String) // jspMap.get(filepackageInternalTmp), // scanDirectory+"/temp/"+fileName, // "com.app.server"+filepackageInternal,classPath.toString()); synchronized (customClassLoader) { String fileNameInWar = filepackageInternalTmp; jspFiles.add(fileNameInWar.replace("/", "\\")); if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) { customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"), "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } else { customClassLoader.addURL("/" + fileNameInWar, "com.app.server" + filepackageInternal.replace("WEB-INF", "WEB_002dINF") + "." + fileNameWithoutExtension); } } } } else { customClassLoader = new WebClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), classLoader); } String filePath = file.getAbsolutePath(); // log.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".war")); urlClassLoaderMap.put(filePath.replace("\\", "/"), customClassLoader); if (jspFiles.size() > 0) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); //Thread.currentThread().setContextClassLoader(customClassLoader); String classPathBefore = ""; try { JspCompiler jspc = new JspCompiler(); jspc.setUriroot(scanDirectory + "/" + directoryName); jspc.setAddWebXmlMappings(false); jspc.setListErrors(false); jspc.setCompile(true); jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/"); jspc.setPackage("com.app.server"); StringBuffer buffer = new StringBuffer(); for (String jspFile : jspFiles) { buffer.append(","); buffer.append(jspFile); } String jsp = buffer.toString(); jsp = jsp.substring(1, jsp.length()); //log.info(jsp); classPathBefore = System.getProperty("java.class.path"); System.setProperty("java.class.path", System.getProperty("java.class.path") + ";" + classPath.toString().replace("/", "\\")); //jspc.setClassPath(System.getProperty("java.class.path")+";"+classPath.toString().replace("/", "\\")); jspc.setJspFiles(jsp); jspc.initCL(customClassLoader); jspc.execute(); //jspc.closeClassLoader(); //jspc.closeClassLoader(); } catch (Throwable je) { log.error("Error in compiling the jsp page", je); //je.printStackTrace(); } finally { System.setProperty("java.class.path", classPathBefore); //Thread.currentThread().setContextClassLoader(oldCL); } //Thread.currentThread().setContextClassLoader(customClassLoader); } try { File execxml = new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"); if (execxml.exists()) { new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap, execxml, customClassLoader); } } catch (Exception e) { log.error("error in getting executor services ", e); // e.printStackTrace(); } try { File messagingxml = new File( scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"); if (messagingxml.exists()) { new MessagingClassConstruct().getMessagingClass(messagedigester, messagingxml, customClassLoader, messagingClassMap); } } catch (Exception e) { log.error("Error in getting the messaging classes ", e); // e.printStackTrace(); } webxmldigester.setNamespaceAware(true); webxmldigester.setValidating(true); // digester.setRules(null); FileInputStream webxml = new FileInputStream( scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml"); InputSource is = new InputSource(webxml); try { //log.info("SCHEMA"); synchronized (webxmldigester) { // webxmldigester.set("config/web-app_2_4.xsd"); WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is); servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig); } webxml.close(); } catch (Exception e) { log.error("Error in pasrsing the web.xml", e); //e.printStackTrace(); } //customClassLoader.close(); // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { log.error("Error in Deploying war " + file.getAbsolutePath(), ex); } }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String Unzip(String zipFileName, String dstDirectory) { String sRet = ""; String fixedZipFileName = fixFileName(zipFileName); String fixedDstDirectory = fixFileName(dstDirectory); String dstFileName = ""; int nNumExtracted = 0; boolean bRet = false; try {/*from w ww . j a v a 2 s .c om*/ final int BUFFER = 2048; BufferedOutputStream dest = null; ZipFile zipFile = new ZipFile(fixedZipFileName); int nNumEntries = zipFile.size(); zipFile.close(); FileInputStream fis = new FileInputStream(fixedZipFileName); CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32()); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum)); ZipEntry entry; byte[] data = new byte[BUFFER]; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; if (fixedDstDirectory.length() > 0) dstFileName = fixedDstDirectory + entry.getName(); else dstFileName = entry.getName(); String tmpDir = dstFileName.substring(0, dstFileName.lastIndexOf('/')); File tmpFile = new File(tmpDir); if (!tmpFile.exists()) { bRet = tmpFile.mkdirs(); } else bRet = true; if (bRet) { // if we aren't just creating a directory if (dstFileName.lastIndexOf('/') != (dstFileName.length() - 1)) { // write out the file FileOutputStream fos = new FileOutputStream(dstFileName); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); dest = null; fos.close(); fos = null; } nNumExtracted++; } else sRet += " - failed" + lineSep; } data = null; zis.close(); System.out.println("Checksum: " + checksum.getChecksum().getValue()); sRet += "Checksum: " + checksum.getChecksum().getValue(); sRet += lineSep + nNumExtracted + " of " + nNumEntries + " successfully extracted"; } catch (Exception e) { e.printStackTrace(); } return (sRet); }