List of usage examples for java.util.zip ZipFile ZipFile
public ZipFile(File file) throws ZipException, IOException
From source file:com.serotonin.m2m2.Main.java
private static void openZipFiles() throws Exception { ProcessEPoll pep = new ProcessEPoll(); try {//from w ww. j a v a2s .c o m 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:com.predic8.membrane.examples.DistributionExtractingTestcase.java
public static final void unzip(File zip, File target) throws IOException { ZipFile zipFile = new ZipFile(zip); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { // Assume directories are stored parents first then children. // This is not robust, just for demonstration purposes. new File(target, entry.getName()).mkdir(); } else {//from ww w .j a va2s .c o m FileOutputStream fos = new FileOutputStream(new File(target, entry.getName())); try { copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(fos)); } finally { fos.close(); } } } zipFile.close(); }
From source file:dk.netarkivet.common.utils.ZipUtils.java
/** Unzip a zipFile into a directory. This will create subdirectories * as needed.//from w w w .j a v a 2 s . c o m * * @param zipFile The file to unzip * @param toDir The directory to create the files under. This directory * will be created if necessary. Files in it will be overwritten if the * filenames match. */ public static void unzip(File zipFile, File toDir) { ArgumentNotValid.checkNotNull(zipFile, "File zipFile"); ArgumentNotValid.checkNotNull(toDir, "File toDir"); ArgumentNotValid.checkTrue(toDir.getAbsoluteFile().getParentFile().canWrite(), "can't write to '" + toDir + "'"); ArgumentNotValid.checkTrue(zipFile.canRead(), "can't read '" + zipFile + "'"); InputStream inputStream = null; ZipFile unzipper = null; try { try { unzipper = new ZipFile(zipFile); Enumeration<? extends ZipEntry> entries = unzipper.entries(); while (entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); File target = new File(toDir, ze.getName()); // Ensure that its dir exists FileUtils.createDir(target.getCanonicalFile().getParentFile()); if (ze.isDirectory()) { target.mkdir(); } else { inputStream = unzipper.getInputStream(ze); FileUtils.writeStreamToFile(inputStream, target); inputStream.close(); } } } finally { if (unzipper != null) { unzipper.close(); } if (inputStream != null) { inputStream.close(); } } } catch (IOException e) { throw new IOFailure("Failed to unzip '" + zipFile + "'", e); } }
From source file:org.openmrs.module.sdmxhdintegration.web.controller.KeyFamilyAttributesDialogController.java
@RequestMapping("/module/sdmxhdintegration/keyFamilyAttributesDialog") public void showForm(ModelMap model, @RequestParam("messageId") Integer messageId, @RequestParam("attachmentLevel") String attachmentLevel, @RequestParam("keyFamilyId") String keyFamilyId, @RequestParam(value = "columnName", required = false) String columnName) throws IOException, XMLStreamException, ExternalRefrenceNotFoundException, ValidationException, SchemaValidationException { attachmentLevel = URLDecoder.decode(attachmentLevel); if (columnName != null) { columnName = URLDecoder.decode(columnName); }/*from w w w .j av a2 s. c om*/ SDMXHDService sdmxhdService = Context.getService(SDMXHDService.class); SDMXHDMessage sdmxhdMessage = sdmxhdService.getMessage(messageId); // get OMRS DSD DataSetDefinitionService dss = Context.getService(DataSetDefinitionService.class); SDMXHDCohortIndicatorDataSetDefinition omrsDSD = Utils.getOMRSDataSetDefinition(sdmxhdMessage, keyFamilyId); String path = Context.getAdministrationService().getGlobalProperty("sdmxhdintegration.messageUploadDir"); ZipFile zf = new ZipFile(path + File.separator + sdmxhdMessage.getZipFilename()); SDMXHDParser parser = new SDMXHDParser(); org.jembi.sdmxhd.SDMXHDMessage sdmxhdData = parser.parse(zf); DSD sdmxhdDSD = sdmxhdData.getDsd(); Map<String, List<SimpleCode>> codelistValues = new HashMap<String, List<SimpleCode>>(); // get mandatory attributes List<Attribute> mandAttributes = sdmxhdDSD.getAttributes(attachmentLevel, Attribute.MANDATORY); // set the mandatory attributes datatypes Map<String, String> mandAttrDataTypes = new HashMap<String, String>(); for (Attribute a : mandAttributes) { if (a.getCodelist() != null) { // Get codelist from DSD CodeList codeList = sdmxhdDSD.getCodeList(a.getCodelist()); // Extract code values List<SimpleCode> codeValues = new ArrayList<SimpleCode>(); for (Code c : codeList.getCodes()) { codeValues.add(new SimpleCode(c.getValue(), c.getDescription().getDefaultStr())); } // Add to master map codelistValues.put(a.getConceptRef(), codeValues); mandAttrDataTypes.put(a.getConceptRef(), "Coded"); } else if (a.getTextFormat().getTextType().equalsIgnoreCase("String")) { mandAttrDataTypes.put(a.getConceptRef(), "String"); } else if (a.getTextFormat().getTextType().equalsIgnoreCase("Date")) { mandAttrDataTypes.put(a.getConceptRef(), "Date"); } } // get conditional attributes List<Attribute> condAttributes = sdmxhdDSD.getAttributes(attachmentLevel, Attribute.CONDITIONAL); // set the conditional attributes datatypes Map<String, String> condAttrDataTypes = new HashMap<String, String>(); for (Attribute a : condAttributes) { if (a.getCodelist() != null) { // Get codelist from DSD CodeList codeList = sdmxhdDSD.getCodeList(a.getCodelist()); // Extract code values List<SimpleCode> codeValues = new ArrayList<SimpleCode>(); for (Code c : codeList.getCodes()) { codeValues.add(new SimpleCode(c.getValue(), c.getDescription().getDefaultStr())); } // Add to master map codelistValues.put(a.getConceptRef(), codeValues); condAttrDataTypes.put(a.getConceptRef(), "Coded"); } else if (a.getTextFormat().getTextType().equalsIgnoreCase("String")) { condAttrDataTypes.put(a.getConceptRef(), "String"); } else if (a.getTextFormat().getTextType().equalsIgnoreCase("Date")) { condAttrDataTypes.put(a.getConceptRef(), "Date"); } } // get attribute values for the attachment level Map<String, String> attributeValues = null; if (attachmentLevel.equals("Dataset")) { attributeValues = omrsDSD.getDataSetAttachedAttributes(); } else if (attachmentLevel.equals("Series")) { attributeValues = omrsDSD.getSeriesAttachedAttributes().get(columnName); } else if (attachmentLevel.equals("Observation")) { attributeValues = omrsDSD.getObsAttachedAttributes().get(columnName); } model.addAttribute("mandAttributes", mandAttributes); model.addAttribute("condAttributes", condAttributes); model.addAttribute("mandAttrDataTypes", mandAttrDataTypes); model.addAttribute("condAttrDataTypes", condAttrDataTypes); model.addAttribute("attributeValues", attributeValues); model.addAttribute("codelistValues", codelistValues); model.addAttribute("messageId", messageId); model.addAttribute("keyFamilyId", keyFamilyId); model.addAttribute("attachmentLevel", attachmentLevel); }
From source file:it.tidalwave.northernwind.importer.infoglue.ExportConverter.java
protected void addLibraries(final @Nonnull String zippedLibraryPath, final @Nonnull ZonedDateTime dateTime) throws IOException { final @Cleanup ZipFile zipFile = new ZipFile(zippedLibraryPath); final Enumeration enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { final ZipEntry zipEntry = (ZipEntry) enumeration.nextElement(); if (!zipEntry.isDirectory()) { // System.out.println("Unzipping: " + zipEntry.getName()); final @Cleanup InputStream is = new BufferedInputStream(zipFile.getInputStream(zipEntry)); ResourceManager.addCommand(new AddResourceCommand(dateTime, zipEntry.getName(), IOUtils.toByteArray(is), "Extracted from library")); }/* ww w . ja v a 2s . co m*/ } }
From source file:biz.c24.io.spring.batch.reader.source.ZipFileSource.java
public void initialise(StepExecution stepExecution) { try {/*from ww w .j a va 2 s . c o m*/ // Get an File and a name for where we're reading from // Use the Resource if supplied File source = null; if (resource != null) { name = resource.getDescription(); source = resource.getFile(); } else { // If no resource supplied, fallback to a Job parameter called input.file name = stepExecution.getJobParameters().getString("input.file"); // Remove any leading file:// if it exists if (name.startsWith("file://")) { name = name.substring("file://".length()); } source = new File(name); } zipFile = new ZipFile(source); zipEntries = zipFile.entries(); ZipEntry entry = getNextZipEntry(); if (entry != null) { // Prime the reader reader = getReader(entry); } // If we have a large number of ZipEntries and the first one looks relatively small, advise // callers to use a thread per reader if (entry != null && zipFile.size() > 20 && (entry.getSize() == -1 || entry.getSize() < 100000)) { useMultipleThreadsPerReader = false; } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.meltmedia.cadmium.deployer.JBossUtil.java
public static boolean isCadmiumWar(File file, Logger log) { if (file.isDirectory()) { return new File(file, "WEB-INF/cadmium.properties").exists(); } else if (file.exists()) { ZipFile zip = null;/*from w w w . j a v a2s . c om*/ try { zip = new ZipFile(file); ZipEntry cadmiumProps = zip.getEntry("WEB-INF/cadmium.properties"); return cadmiumProps != null; } catch (Exception e) { log.warn("Failed to read war file " + file, e); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { //Not much we can do about this. } } } } return false; }
From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java
public static void unzip2folder(File zipFile, File toFolder) throws FileExistsException { if (!toFolder.exists()) { toFolder.mkdirs();/* w w w . j a v a2 s . c o m*/ } else if (toFolder.isFile()) { throw new FileExistsException(toFolder.getName()); } try { ZipEntry entry; @SuppressWarnings("resource") ZipFile zipfile = new ZipFile(zipFile); Enumeration<? extends ZipEntry> e = zipfile.entries(); while (e.hasMoreElements()) { entry = e.nextElement(); // String newDir; // if (entry.getName().indexOf("/") == -1) { // newDir = zipFile.getName().substring(0, zipFile.getName().indexOf(".")); // } else { // newDir = entry.getName().substring(0, entry.getName().indexOf("/")); // } // String folder = toFolder + (File.separatorChar+"") + newDir; // System.out.println(folder); // if ((new File(folder).mkdir())) { // System.out.println("Done."); // } System.out.println("Extracting: " + entry); if (entry.isDirectory()) { new File(toFolder + (File.separatorChar + "") + entry.getName()).mkdir(); } else { BufferedInputStream is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[2048]; String fileName = toFolder + (File.separatorChar + "") + entry.getName(); FileOutputStream fos = new FileOutputStream(fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, 2048); while ((count = is.read(data, 0, 2048)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); System.out.println("extracted to: " + fileName); } } } catch (ZipException e1) { zipFile.delete(); e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * <p>This method updates a template war with the following settings.</p> * @param templateWar The name of the template war to pull from the classpath. * @param war The path of an external war to update (optional). * @param newWarNames The name to give the new war. (note: only the first element of this list is used.) * @param repoUri The uri to a github repo to pull content from. * @param branch The branch of the github repo to pull content from. * @param configRepoUri The uri to a github repo to pull config from. * @param configBranch The branch of the github repo to pull config from. * @param domain The domain to bind a vHost to. * @param context The context root that this war will deploy to. * @param secure A flag to set if this war needs to have its contents password protected. * @throws Exception/*from ww w . j a v a2 s . c o m*/ */ public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri, String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure, Logger log) throws Exception { ZipFile inZip = null; ZipOutputStream outZip = null; InputStream in = null; OutputStream out = null; try { if (war != null) { if (war.equals(newWarNames.get(0))) { File tmpZip = File.createTempFile(war, null); tmpZip.delete(); tmpZip.deleteOnExit(); new File(war).renameTo(tmpZip); war = tmpZip.getAbsolutePath(); } inZip = new ZipFile(war); } else { File tmpZip = File.createTempFile("cadmium-war", "war"); tmpZip.delete(); tmpZip.deleteOnExit(); in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar); out = new FileOutputStream(tmpZip); FileSystemManager.streamCopy(in, out); inZip = new ZipFile(tmpZip); } outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0))); ZipEntry cadmiumPropertiesEntry = null; cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties"); Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch, configRepoUri, configBranch); ZipEntry jbossWeb = null; jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml"); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().equals(cadmiumPropertiesEntry.getName())) { storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames); } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0)) && e.getName().equals(jbossWeb.getName())) { updateDomain(inZip, outZip, jbossWeb, domain, context); } else if (secure && e.getName().equals("WEB-INF/web.xml")) { addSecurity(inZip, outZip, e); } else { outZip.putNextEntry(e); if (!e.isDirectory()) { FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true); } outZip.closeEntry(); } } } finally { if (FileSystemManager.exists("tmp_cadmium-war.war")) { new File("tmp_cadmium-war.war").delete(); } try { if (inZip != null) { inZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + war); } } try { if (outZip != null) { outZip.close(); } } catch (Exception e) { if (log != null) { log.error("Failed to close " + newWarNames.get(0)); } } try { if (out != null) { out.close(); } } catch (Exception e) { } try { if (in != null) { in.close(); } } catch (Exception e) { } } }
From source file:fi.mikuz.boarder.gui.ZipImporter.java
@SuppressWarnings("rawtypes") public void unzipArchive(final File archive, final File outputDir) { Thread t = new Thread() { public void run() { Looper.prepare();//from w ww . java 2 s . com String archiveName = archive.getName(); String boardName = archiveName.substring(0, archiveName.indexOf(".zip")); String boardDirectory = SoundboardMenu.mSbDir.getAbsolutePath() + "/" + boardName; try { File boardDirectoryFile = new File(boardDirectory); if (boardDirectoryFile.exists()) { postMessage(boardDirectoryFile.getName() + " already exists."); } else { ZipFile zipfile = new ZipFile(archive); boolean normalStructure = true; log = "Checking if zip structure is legal\n" + log; for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); File outputFile = new File(outputDir, entry.getName()); if (!Pattern.matches(boardDirectory + ".*", outputFile.getAbsolutePath())) { normalStructure = false; log = entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory + "\n\n" + log; Log.e(TAG, entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory); } } if (normalStructure) { log = "\nGoing to extract\n" + log; outputDir.mkdirs(); for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); log = "Extracting " + entry.getName() + "\n" + log; postMessage("Please wait\n\n" + log); unzipEntry(zipfile, entry, outputDir); } log = "Success\n\n" + log; postMessage(log); } else { postMessage("Zip was not extracted because it doesn't follow the normal structure.\n\n" + "Please use another application to check the content of this zip file and extract it if you want to.\n\n" + log); } } } catch (Exception e) { log = "Couldn't extract " + archive + "\n\nError: \n" + e.getMessage() + "\n\n" + log; postMessage(log); Log.e(TAG, "Error while extracting file " + archive, e); } mHandler.post(showContinueButton); } }; t.start(); }