List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:org.wso2.security.tools.product.manager.handler.FileHandler.java
/** * Extract a zip file and returns name of the extracted folder * * @param zipFilePath ZIP file path// www.j a va 2 s . c o m * @return Extracted folder name * @throws IOException If an error occurs while I/O operations */ public static String extractZipFile(String zipFilePath) throws IOException { int BUFFER = 2048; File file = new File(zipFilePath); ZipFile zip = new ZipFile(file); String newPath = file.getParent(); String fileName = file.getName(); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } if (currentEntry.endsWith(".zip")) { // found a zip file, try to open extractZipFile(destFile.getAbsolutePath()); } } zip.close(); return fileName.substring(0, fileName.length() - 4); }
From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java
protected void performDeployInternal(String hostName, WebApplication appInfo, String warUrl, AbstractWebContainer.WebDescriptorParser webAppParser) throws Exception { WebMetaData metaData = appInfo.getMetaData(); String ctxPath = metaData.getContextRoot(); if (ctxPath.equals("/") || ctxPath.equals("/ROOT") || ctxPath.equals("")) { log.debug("deploy root context=" + ctxPath); ctxPath = "/"; metaData.setContextRoot(ctxPath); }//w w w. j ava 2 s . c o m log.info("deploy, ctxPath=" + ctxPath + ", warUrl=" + shortWarUrlFromServerHome(warUrl)); URL url = new URL(warUrl); ClassLoader loader = Thread.currentThread().getContextClassLoader(); /* If we are using the jboss class loader we need to augment its path to include the WEB-INF/{lib,classes} dirs or else scoped class loading does not see the war level overrides. The call to setWarURL adds these paths to the deployment UCL. */ Loader webLoader = null; if (config.isUseJBossWebLoader()) { WebCtxLoader jbossLoader = new WebCtxLoader(loader); jbossLoader.setWarURL(url); webLoader = jbossLoader; } else { String[] pkgs = config.getFilteredPackages(); WebAppLoader jbossLoader = new WebAppLoader(loader, pkgs); jbossLoader.setDelegate(getJava2ClassLoadingCompliance()); webLoader = jbossLoader; } // We need to establish the JNDI ENC prior to the start // of the web container so that init on startup servlets are able // to interact with their ENC. We hook into the context lifecycle // events to be notified of the start of the // context as this occurs before the servlets are started. if (appInfo.getAppData() == null) webAppParser.parseWebAppDescriptors(loader, appInfo.getMetaData()); appInfo.setName(url.getPath()); appInfo.setClassLoader(loader); appInfo.setURL(url); String objectNameS = config.getCatalinaDomain() + ":j2eeType=WebModule,name=//" + ((hostName == null) ? "localhost" : hostName) + ctxPath + ",J2EEApplication=none,J2EEServer=none"; ObjectName objectName = new ObjectName(objectNameS); if (server.isRegistered(objectName)) { log.debug("Already exists, destroying " + objectName); server.invoke(objectName, "destroy", new Object[] {}, new String[] {}); } server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName, new Object[] { config.getContextClassName() }, new String[] { "java.lang.String" }); // Find and set config file on the context // If WAR is packed, expand config file to temp folder String ctxConfig = null; try { ctxConfig = findConfig(url); } catch (IOException e) { log.debug("No " + CONTEXT_CONFIG_FILE + " in " + url, e); } server.setAttribute(objectName, new Attribute("docBase", url.getFile())); server.setAttribute(objectName, new Attribute("configFile", ctxConfig)); server.setAttribute(objectName, new Attribute("defaultContextXml", "context.xml")); server.setAttribute(objectName, new Attribute("defaultWebXml", "conf/web.xml")); server.setAttribute(objectName, new Attribute("javaVMs", javaVMs)); server.setAttribute(objectName, new Attribute("server", serverName)); server.setAttribute(objectName, new Attribute("saveConfig", Boolean.FALSE)); if (webLoader != null) { server.setAttribute(objectName, new Attribute("loader", webLoader)); } else { server.setAttribute(objectName, new Attribute("parentClassLoader", loader)); } server.setAttribute(objectName, new Attribute("delegate", new Boolean(getJava2ClassLoadingCompliance()))); String[] jspCP = getCompileClasspath(loader); StringBuffer classpath = new StringBuffer(); for (int u = 0; u < jspCP.length; u++) { String repository = jspCP[u]; if (repository == null) continue; if (repository.startsWith("file://")) repository = repository.substring(7); else if (repository.startsWith("file:")) repository = repository.substring(5); else continue; if (repository == null) continue; // ok it is a file. Make sure that is is a directory or jar file File fp = new File(repository); if (!fp.isDirectory()) { // if it is not a directory, try to open it as a zipfile. try { // avoid opening .xml files if (fp.getName().toLowerCase().endsWith(".xml")) continue; ZipFile zip = new ZipFile(fp); zip.close(); } catch (IOException e) { continue; } } if (u > 0) classpath.append(File.pathSeparator); classpath.append(repository); } server.setAttribute(objectName, new Attribute("compilerClasspath", classpath.toString())); // Set the session cookies flag according to metadata switch (metaData.getSessionCookies()) { case WebMetaData.SESSION_COOKIES_ENABLED: server.setAttribute(objectName, new Attribute("cookies", new Boolean(true))); log.debug("Enabling session cookies"); break; case WebMetaData.SESSION_COOKIES_DISABLED: server.setAttribute(objectName, new Attribute("cookies", new Boolean(false))); log.debug("Disabling session cookies"); break; default: log.debug("Using session cookies default setting"); } // Add a valve to estalish the JACC context before authorization valves Certificate[] certs = null; CodeSource cs = new CodeSource(url, certs); JaccContextValve jaccValve = new JaccContextValve(metaData.getJaccContextID(), cs); server.invoke(objectName, "addValve", new Object[] { jaccValve }, new String[] { "org.apache.catalina.Valve" }); // Pass the metadata to the RunAsListener via a thread local RunAsListener.metaDataLocal.set(metaData); try { // Init the container; this will also start it server.invoke(objectName, "init", new Object[] {}, new String[] {}); } finally { RunAsListener.metaDataLocal.set(null); } // make the context class loader known to the WebMetaData, ws4ee needs it // to instanciate service endpoint pojos that live in this webapp Loader ctxLoader = (Loader) server.getAttribute(objectName, "loader"); metaData.setContextLoader(ctxLoader.getClassLoader()); // Clustering if (metaData.getDistributable()) { // Try to initate clustering, fallback to standard if no clustering is available try { AbstractJBossManager manager = null; String managerClassName = config.getManagerClass(); Class managerClass = Thread.currentThread().getContextClassLoader().loadClass(managerClassName); manager = (AbstractJBossManager) managerClass.newInstance(); if (manager instanceof JBossCacheManager) { // TODO either deprecate snapshot mode or move its config // into jboss-web.xml. String snapshotMode = config.getSnapshotMode(); int snapshotInterval = config.getSnapshotInterval(); JBossCacheManager jbcm = (JBossCacheManager) manager; jbcm.setSnapshotMode(snapshotMode); jbcm.setSnapshotInterval(snapshotInterval); } String name = "//" + ((hostName == null) ? "localhost" : hostName) + ctxPath; manager.init(name, metaData, config.isUseJK(), config.isUseLocalCache()); // Don't assign the manager to the context until all config // is done, or else the manager will be started without the config server.setAttribute(objectName, new Attribute("manager", manager)); log.debug("Enabled clustering support for ctxPath=" + ctxPath); } catch (ClusteringNotSupportedException e) { // JBAS-3513 Just log a WARN, not an ERROR log.warn("Failed to setup clustering, clustering disabled. ClusteringNotSupportedException: " + e.getMessage()); } catch (NoClassDefFoundError ncdf) { // JBAS-3513 Just log a WARN, not an ERROR log.debug("Classes needed for clustered webapp unavailable", ncdf); log.warn("Failed to setup clustering, clustering disabled. NoClassDefFoundError: " + ncdf.getMessage()); } catch (Throwable t) { // TODO consider letting this through and fail the deployment log.error("Failed to setup clustering, clustering disabled. Exception: ", t); } } /* Add security association valve after the authorization valves so that the authenticated user may be associated with the request thread/session. */ SecurityAssociationValve valve = new SecurityAssociationValve(metaData, config.getSecurityManagerService()); valve.setSubjectAttributeName(config.getSubjectAttributeName()); server.invoke(objectName, "addValve", new Object[] { valve }, new String[] { "org.apache.catalina.Valve" }); // Retrieve the state, and throw an exception in case of a failure Integer state = (Integer) server.getAttribute(objectName, "state"); if (state.intValue() != 1) { throw new DeploymentException("URL " + warUrl + " deployment failed"); } appInfo.setAppData(objectName); // Create mbeans for the servlets DeploymentInfo di = webAppParser.getDeploymentInfo(); di.deployedObject = objectName; ObjectName servletQuery = new ObjectName(config.getCatalinaDomain() + ":j2eeType=Servlet,WebModule=" + objectName.getKeyProperty("name") + ",*"); Iterator iterator = server.queryMBeans(servletQuery, null).iterator(); while (iterator.hasNext()) { di.mbeans.add(((ObjectInstance) iterator.next()).getObjectName()); } log.debug("Initialized: " + appInfo + " " + objectName); }
From source file:net.sf.zekr.engine.translation.TranslationData.java
/** * Verify the zip archive and close the zip file handle finally. * /*from w w w . ja va 2s .c om*/ * @return <code>true</code> if translation verified, <code>false</code> otherwise. * @throws IOException */ public boolean verify() throws IOException { ZipFile zf = new ZipFile(archiveFile); ZipEntry ze = zf.getEntry(file); if (ze == null) { logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\"."); return false; } byte[] textBuf = new byte[(int) ze.getSize()]; boolean result; result = verify(zf.getInputStream(ze), textBuf); zf.close(); return result; }
From source file:org.mule.appkit.it.AbstractMavenIT.java
protected void assertZipDoesNotContain(File file, String... filenames) throws IOException { ZipFile zipFile = null; try {//from w w w. ja va2 s . c o m zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); for (String name : filenames) { if (entry.getName().equals(name)) { fail(file.getAbsolutePath() + " contains invalid entry " + name); } } } } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java
public void testNotZipFileUpload() throws Exception { File file = getResourceFile("validModel.zip"); ZipFile zipFile = new ZipFile(file); ZipEntry zipEntry = zipFile.entries().nextElement(); File unzippedModelFile = TempFileProvider.createTempFile(zipFile.getInputStream(zipEntry), "validModel", ".xml"); tempFiles.add(unzippedModelFile);//w w w .j a v a 2 s. c o m zipFile.close(); PostRequest postRequest = buildMultipartPostRequest(unzippedModelFile); sendRequest(postRequest, 400); // CMM upload supports only zip file. }
From source file:com.github.swt_release_fetcher.Artifact.java
public void deploy() throws IOException { File jarFile = null;// w ww . jav a2 s. c o m File sourcesFile = null; File pomFile = null; ZipFile zipFile = null; try { jarFile = File.createTempFile("deploy", ".jar"); sourcesFile = File.createTempFile("deploy", "-sources.jar"); pomFile = File.createTempFile("pom", ".xml"); zipFile = new ZipFile(file); extractFromZip(zipFile, "swt.jar", jarFile); extractFromZip(zipFile, "src.zip", sourcesFile); generatePom(pomFile); runMavenDeploy(pomFile, jarFile, sourcesFile); } finally { if (zipFile != null) { zipFile.close(); } FileUtils.deleteQuietly(jarFile); FileUtils.deleteQuietly(sourcesFile); FileUtils.deleteQuietly(pomFile); } }
From source file:pdl.utils.ZipHandler.java
public boolean unZip(String filePath, String parentPath) throws Exception { boolean rtnVal = false; try {/* www .j ava2s .c om*/ ZipFile zipFile = new ZipFile(filePath); Enumeration files = zipFile.entries(); while (files.hasMoreElements()) { ZipEntry entry = (ZipEntry) files.nextElement(); InputStream eis = zipFile.getInputStream(entry); File f = new File(parentPath + entry.getName()); if (entry.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); f.createNewFile(); } FileUtils.copyInputStreamToFile(eis, f); eis.close(); } zipFile.close(); rtnVal = true; } catch (Exception ex) { ex.printStackTrace(); throw new Exception("unzip process failed."); } return rtnVal; }
From source file:com.thruzero.common.core.utils.FileUtilsExt.java
public static final boolean unzipArchive(final File fromFile, final File toDir) throws IOException { boolean result = false; // assumes error logHelper.logBeginUnzip(fromFile, toDir); ZipFile zipFile = new ZipFile(fromFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); if (!toDir.exists()) { toDir.mkdirs();//from w w w. j a v a2 s . com logHelper.logProgressCreatedToDir(toDir); } logHelper.logProgressToDirIsWritable(toDir); if (toDir.canWrite()) { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { File dir = new File( toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName()); if (!dir.exists()) { dir.mkdirs(); logHelper.logProgressFilePathCreated(dir); } } else { File fosz = new File( toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName()); logHelper.logProgressCopyEntry(fosz); File parent = fosz.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fosz)); IOUtils.copy(zipFile.getInputStream(entry), bos); bos.flush(); } } zipFile.close(); result = true; // success } else { logHelper.logFileWriteError(fromFile, null); zipFile.close(); } return result; }
From source file:de.uni_koeln.spinfo.maalr.services.admin.shared.DataLoader.java
public void createFromSQLDump(File file, int maxEntries) throws IOException, NoDatabaseAvailableException, InvalidEntryException, IndexException { if (!file.exists()) { logger.info("No data to import - file " + file + " does not exist."); return;// w w w . jav a2 s . c o m } BufferedReader br; ZipFile zipFile = null; if (file.getName().endsWith(".zip")) { logger.info("Trying to read data from zip file=" + file.getName()); zipFile = new ZipFile(file); String entryName = file.getName().replaceAll(".zip", ""); // ZipEntry entry = zipFile.getEntry(entryName+".tsv"); ZipEntry entry = zipFile.getEntry(entryName); if (entry == null) { logger.info("No file named " + entryName + " found in zip file - skipping import"); zipFile.close(); return; } br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry), "UTF-8")); } else { logger.info("Trying to read data from file " + file); br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); } String line = br.readLine(); String[] keys = line.split("\t", -1); Database db = Database.getInstance(); List<DBObject> entries = new ArrayList<DBObject>(); int counter = 0; String userId = loginManager.getCurrentUserId(); while ((line = br.readLine()) != null) { String[] values = line.split("\t", -1); if (values.length != keys.length) { logger.warn("Ignoring entry: Attribute mismatch (" + values.length + " entries found, " + keys.length + " entries expected) in line " + line); continue; } LemmaVersion version = new LemmaVersion(); for (int i = 0; i < keys.length; i++) { String value = values[i].trim(); String key = keys[i].trim(); if (value.length() == 0) continue; if (key.length() == 0) continue; version.setValue(key, value); } LexEntry entry = new LexEntry(version); entry.setCurrent(version); entry.getCurrent().setStatus(Status.NEW_ENTRY); entry.getCurrent().setVerification(Verification.ACCEPTED); long timestamp = System.currentTimeMillis(); String embeddedTimeStamp = version.getEntryValue(LemmaVersion.TIMESTAMP); if (embeddedTimeStamp != null) { timestamp = Long.parseLong(embeddedTimeStamp); version.removeEntryValue(LemmaVersion.TIMESTAMP); } entry.getCurrent().setUserId(userId); entry.getCurrent().setTimestamp(timestamp); entry.getCurrent().setCreatorRole(Role.ADMIN_5); entries.add(Converter.convertLexEntry(entry)); if (entries.size() == 10000) { db.insertBatch(entries); entries.clear(); } counter++; if (counter == maxEntries) { logger.warn("Skipping db creation, as max entries is " + maxEntries); break; } } db.insertBatch(entries); entries.clear(); //loginManager.login("admin", "admin"); Iterator<LexEntry> iterator = db.getEntries(); index.dropIndex(); index.addToIndex(iterator); logger.info("Index has been created, swapping to RAM..."); index.reloadIndex(); logger.info("RAM-Index updated."); br.close(); if (zipFile != null) { zipFile.close(); } //loginManager.logout(); logger.info("Dataloader initialized."); }
From source file:org.fao.geonet.api.mapservers.GeoFile.java
/** * Returns the names of the vector layers (Shapefiles) in the geographic file. * * @param onlyOneFileAllowed Return exception if more than one shapefile found * @return a collection of layer names// w w w .ja va2 s . c om * @throws IllegalArgumentException If more than on shapefile is found and onlyOneFileAllowed is * true or if Shapefile name is not equal to zip file base * name */ public Collection<String> getVectorLayers(final boolean onlyOneFileAllowed) throws IOException { final LinkedList<String> layers = new LinkedList<String>(); if (zipFile != null) { for (Path path : zipFile.getRootDirectories()) { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); if (fileIsShp(fileName)) { String base = getBase(fileName); if (onlyOneFileAllowed) { if (layers.size() > 1) throw new IllegalArgumentException("Only one shapefile per zip is allowed. " + layers.size() + " shapefiles found."); if (base.equals(getBase(fileName))) { layers.add(base); } else throw new IllegalArgumentException("Shapefile name (" + base + ") is not equal to ZIP file name (" + file.getFileName() + ")."); } else { layers.add(base); } } if (fileIsSld(fileName)) { _containsSld = true; _sldBody = fileName; } return FileVisitResult.CONTINUE; } }); } if (_containsSld) { ZipFile zf = new ZipFile(new File(this.file.toString())); InputStream is = zf.getInputStream(zf.getEntry(_sldBody)); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String line; _sldBody = ""; while ((line = br.readLine()) != null) { _sldBody += line; } br.close(); is.close(); zf.close(); } } return layers; }