List of usage examples for java.util.zip ZipInputStream ZipInputStream
public ZipInputStream(InputStream in)
From source file:edu.monash.merc.system.remote.HttpHpaFileGetter.java
public boolean importHPAXML(String remoteFile, String localFile) { //use httpclient to get the remote file HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(remoteFile); ZipInputStream zis = null;//from www .j a va2 s . c o m FileOutputStream fos = null; try { HttpResponse response = httpClient.execute(httpGet); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream in = entity.getContent(); zis = new ZipInputStream(in); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); if (StringUtils.contains(fileName, HPA_FILE_NAME)) { System.out.println("======= found file."); File aFile = new File(localFile); fos = new FileOutputStream(aFile); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); break; } } } } else { throw new DMRemoteException("can't get the file from " + remoteFile); } } catch (Exception ex) { throw new DMRemoteException(ex); } finally { try { if (fos != null) { fos.close(); } if (zis != null) { zis.closeEntry(); zis.close(); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { //ignore whatever caught } } return true; }
From source file:com.oprisnik.semdroid.Semdroid.java
protected void extract(InputStream source, File targetDir) { if (!targetDir.exists()) { targetDir.mkdirs();//from w w w . j a va 2s . co m } if (BuildConfig.DEBUG) { Log.d(TAG, "Extracting to " + targetDir); } try { ZipInputStream zip = new ZipInputStream(source); ZipEntry entry = null; while ((entry = zip.getNextEntry()) != null) { if (entry.isDirectory()) { File dir = new File(targetDir, entry.getName()); if (!dir.exists()) { dir.mkdirs(); } } else { File newFile = new File(targetDir, entry.getName()); FileOutputStream fout = new FileOutputStream(newFile); if (BuildConfig.DEBUG) { Log.d(TAG, "Extracting " + entry.getName() + " to " + newFile); } byte[] data = new byte[BUFFER]; int count; while ((count = zip.read(data, 0, BUFFER)) != -1) { fout.write(data, 0, count); } zip.closeEntry(); fout.close(); } } } catch (Exception e) { Log.e(TAG, e.getMessage()); } finally { IOUtils.closeQuietly(source); } }
From source file:com.receipts.backingbeans.StoreView.java
public void importStores(FileUploadEvent event) { int userId = (int) event.getComponent().getAttributes().get("userId"); UploadedFile zipFile = event.getFile(); String insertStoresSql = "insert into stores (store_id, store_date, user_id) values (?, ?, ?)"; String selectStoresSql = "select id from stores where store_id = ? and store_date = ?"; String insertReceiptsSql = "insert into receipts (store_fk, user_id, img_name) values (?, ?, ?)"; try (Connection conn = DbUtils.getDbConnection()) { try (ZipInputStream zin = new ZipInputStream(new BufferedInputStream(zipFile.getInputstream())); PreparedStatement insertStoresPs = conn.prepareStatement(insertStoresSql); PreparedStatement selectStoresPs = conn.prepareStatement(selectStoresSql); PreparedStatement insertReceiptsPs = conn.prepareStatement(insertReceiptsSql)) { ZipEntry entry;/* w w w.j a v a 2 s .c o m*/ conn.setAutoCommit(false); while ((entry = zin.getNextEntry()) != null) { String entryName = entry.getName(); boolean isDirectory = entry.isDirectory(); if (isDirectory) { String storeId = entryName.split("_")[0]; String storeDay = entryName.split("_")[1]; String storeMonth = entryName.split("_")[2]; String storeYear = entryName.split("_")[3].substring(0, entryName.split("_")[3].length() - 1); LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear), Integer.parseInt(storeMonth), Integer.parseInt(storeDay)); insertStoresPs.setString(1, storeId); insertStoresPs.setDate(2, new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis())); insertStoresPs.setInt(3, userId); insertStoresPs.executeUpdate(); } else { String storeData = entryName.split("/")[0]; String fileName = entryName.split("/")[1]; if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg") || fileName.toLowerCase().endsWith(".png") || fileName.toLowerCase().endsWith(".gif") || fileName.endsWith(".tiff")) { String storeId = storeData.split("_")[0]; String storeDay = storeData.split("_")[1]; String storeMonth = storeData.split("_")[2]; String storeYear = storeData.split("_")[3]; LocalDate storeDate = new LocalDate(Integer.parseInt(storeYear), Integer.parseInt(storeMonth), Integer.parseInt(storeDay)); selectStoresPs.setInt(1, Integer.parseInt(storeId)); selectStoresPs.setDate(2, new java.sql.Date(storeDate.toDateTimeAtStartOfDay().getMillis())); int storePK = -1; try (ResultSet rs = selectStoresPs.executeQuery()) { while (rs.next()) { storePK = rs.getInt("id"); } } // insertReceiptsPs.setBlob(1, zin, entry.getSize()); insertReceiptsPs.setInt(1, storePK); insertReceiptsPs.setInt(2, userId); insertReceiptsPs.setString(3, fileName); insertReceiptsPs.executeUpdate(); } } } conn.commit(); allStores = storesService.loadAllStores(); conn.setAutoCommit(true); } catch (Exception ex) { conn.rollback(); conn.setAutoCommit(true); ex.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } }
From source file:com.nuvolect.securesuite.util.OmniZip.java
/** * Unzip the file into the target directory. * The added structure is updated to reflect any new files and directories created. * Overwrite files when requested./* ww w .j ava 2 s . c om*/ * @param zipOmni * @param targetDir * @param added * @param httpIpPort * @return */ public static boolean unzipFile(OmniFile zipOmni, OmniFile targetDir, JsonArray added, String httpIpPort) { String volumeId = zipOmni.getVolumeId(); String rootFolderPath = targetDir.getPath(); boolean DEBUG = true; /** * Keep a list of all directories created. * Defer creating the directory object files until the zip is extracted. * This way the dir=1/0 settings can be set accurately. */ ArrayList<OmniFile> directories = new ArrayList<>(); ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream()); ZipEntry entry = null; try { while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { OmniFile dir = new OmniFile(volumeId, entry.getName()); if (dir.mkdir()) { directories.add(dir); if (DEBUG) LogUtil.log(LogUtil.LogType.OMNI_ZIP, "dir created: " + dir.getPath()); } } else { String path = rootFolderPath + "/" + entry.getName(); OmniFile file = new OmniFile(volumeId, path); // Create any necessary directories file.getParentFile().mkdirs(); if (file.exists()) { file = OmniUtil.makeUniqueName(file); } OutputStream out = file.getOutputStream(); OmniFiles.copyFileLeaveInOpen(zis, out); if (DEBUG) LogUtil.log(LogUtil.LogType.OMNI_ZIP, "file created: " + file.getPath()); if (added != null) added.add(file.getFileObject(httpIpPort)); } } zis.close(); if (added != null) { /** * Iterate over the list of directories created and * create object files for each. * The full tree is now expanded such that the dir=1/0 * can be set accurately. */ for (OmniFile dir : directories) added.add(dir.getFileObject(httpIpPort)); } } catch (IOException e) { LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e); return false; } return true; }
From source file:net.osten.watermap.batch.FetchPCTWaypointsJob.java
private void unZipIt(File zipFile, File outputFolder) { byte[] buffer = new byte[1024]; try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { // get the zipped file list entry ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputFolder.getAbsolutePath() + File.separator + fileName); log.log(Level.FINER, "file unzip : {0}", new Object[] { newFile.getAbsoluteFile() }); // create all non existing folders else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); }//from w w w. ja v a 2 s . c o m } ze = zis.getNextEntry(); // move newFile to data directory try { // have to delete first since FileUtils does not overwrite File destinationFile = new File(outputFolder + File.separator + newFile.getName()); if (destinationFile.exists()) { destinationFile.delete(); } FileUtils.moveFileToDirectory(newFile, outputFolder, false); } catch (FileExistsException ioe) { log.warning(ioe.getLocalizedMessage()); } catch (IOException ioe) { log.warning(ioe.getLocalizedMessage()); } } // close the last entry zis.closeEntry(); } catch (IOException e) { log.warning(e.getLocalizedMessage()); } }
From source file:de.forsthaus.backend.service.impl.IpToCountryServiceImpl.java
@Override public int importIP2CountryCSV() { try {/*from w w w . ja v a2s. com*/ // first, delete all records in the ip2Country table getIpToCountryDAO().deleteAll(); final URL url = new URL(this.updateUrl); final URLConnection conn = url.openConnection(); final InputStream istream = conn.getInputStream(); final ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(istream)); zipInputStream.getNextEntry(); final BufferedReader in = new BufferedReader(new InputStreamReader(zipInputStream)); final CsvBeanReader csvb = new CsvBeanReader(in, CsvPreference.STANDARD_PREFERENCE); // List<IpToCountry> list = new ArrayList<IpToCountry>(); IpToCountry tmp = null; int id = 1; while (null != (tmp = csvb.read(IpToCountry.class, this.stringNameMapping))) { tmp.setId(id++); getIpToCountryDAO().saveOrUpdate(tmp); } // close the stream !!! in.close(); return getIpToCountryDAO().getCountAllIpToCountries(); } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:msearch.filmlisten.MSFilmlisteLesen.java
private InputStream selectDecompressor(String source, InputStream in) throws Exception { if (source.endsWith(MSConst.FORMAT_XZ)) { in = new XZInputStream(in); } else if (source.endsWith(MSConst.FORMAT_BZ2)) { in = new BZip2CompressorInputStream(in); } else if (source.endsWith(MSConst.FORMAT_ZIP)) { ZipInputStream zipInputStream = new ZipInputStream(in); zipInputStream.getNextEntry();//from w w w . j ava 2s. co m in = zipInputStream; } return in; }
From source file:com.aurel.track.exchange.track.importer.TrackImportAction.java
/** * Render the import page/*from w w w . ja v a 2 s . c om*/ */ @Override /** * Save the zip file and import the data * @return */ public String execute() { LOGGER.info("Import started"); InputStream inputStream; try { inputStream = new FileInputStream(uploadFile); } catch (FileNotFoundException e) { LOGGER.error("Getting the input stream for the zip failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed"))); return null; } /** * delete the old temporary attachment directory if exists from previous imports */ String tempAttachmentDirectory = AttachBL.getAttachDirBase() + File.separator + AttachBL.tmpAttachments; AttachBL.deleteDirectory(new File(tempAttachmentDirectory)); /** * extract the zip to a temporary directory */ ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); final int BUFFER = 2048; File unzipTempDirectory = new File(tempAttachmentDirectory); if (!unzipTempDirectory.exists()) { unzipTempDirectory.mkdirs(); } BufferedOutputStream dest = null; ZipEntry zipEntry; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(unzipTempDirectory, zipEntry.getName()); // grab file's parent directory structure int count; byte data[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zipInputStream.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zipInputStream.close(); } catch (Exception e) { LOGGER.error("Extracting the zip to the temporary directory failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * get the data file (the only file from the zip which is not an attachment) */ File importDataFile = new File(tempAttachmentDirectory, ExchangeFieldNames.EXCHANGE_ZIP_ENTRY); if (!importDataFile.exists()) { LOGGER.error("The file " + ExchangeFieldNames.EXCHANGE_ZIP_ENTRY + " not found in the zip"); JSONUtility.encodeJSON(servletResponse, JSONUtility.encodeJSONFailure(getText("admin.actions.importTp.err.failed")), false); return null; } /** * field parser */ LOGGER.debug("Parsing the fields"); List<ISerializableLabelBean> customFieldsBeans = new ImporterFieldParser().parse(importDataFile); Map<Integer, Integer> fieldsMatcherMap = null; try { fieldsMatcherMap = TrackImportBL.getFieldMatchMap(customFieldsBeans); } catch (ImportExceptionList importExceptionList) { LOGGER.error("Getting the field match map failed "); JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true)); return null; } /** * dropdown parser */ LOGGER.debug("Parsing the external dropdowns"); SortedMap<String, List<ISerializableLabelBean>> externalDropdowns = new ImporterDropdownParser() .parse(importDataFile, fieldsMatcherMap); /** * data parser */ LOGGER.debug("Parsing the items"); List<ExchangeWorkItem> externalReportBeansList = new ImporterDataParser().parse(importDataFile, fieldsMatcherMap); try { LOGGER.debug("Importing the items"); ImportCounts importCounts = TrackImportBL.importWorkItems(externalReportBeansList, externalDropdowns, fieldsMatcherMap, personID, locale); LOGGER.debug("Imported " + importCounts.getNoOfCreatedIssues() + " new issues " + " modified " + importCounts.getNoOfUpdatedIssues()); JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(true, getText("admin.actions.importTp.lbl.result", new String[] { Integer.valueOf(importCounts.getNoOfCreatedIssues()).toString(), Integer.valueOf(importCounts.getNoOfUpdatedIssues()).toString() }), true, locale), false); } catch (ImportExceptionList importExceptionList) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importErrorMessageListJSON( ErrorHandlerJSONAdapter.handleErrorList(importExceptionList.getErrorDataList(), locale), null, true), false); return null; } catch (ImportException importException) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText(importException.getMessage()), true, locale), false); return null; } catch (Exception e) { JSONUtility.encodeJSON(servletResponse, ImportJSON.importMessageJSON(false, getText("admin.actions.importTp.err.failed"), true, locale), false); return null; } LOGGER.info("Import done"); return null; }
From source file:edu.ku.brc.helpers.ZipFileHelper.java
/** * Unzips a a zip file cntaining just one file. * @param zipFile the backup file// w w w .j av a 2s. c om * @return the file of the new uncompressed back up file. */ public File unzipToSingleFile(final File zipFile) { final int bufSize = 102400; File outFile = null; try { ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); if (entry == null) { return null; } if (zin.available() == 0) { return null; } outFile = File.createTempFile("zip_", "sql"); FileOutputStream fos = new FileOutputStream(outFile); byte[] bytes = new byte[bufSize]; // 10K int bytesRead = zin.read(bytes, 0, bufSize); while (bytesRead > 0) { fos.write(bytes, 0, bytesRead); bytesRead = zin.read(bytes, 0, 100); } } catch (ZipException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ZipFileHelper.class, ex); return null; //I think this means it is not a zip file. } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ZipFileHelper.class, ex); return null; } return outFile; }
From source file:net.geoprism.data.importer.ShapefileImporter.java
@Request public void run(InputStream iStream) throws InvocationTargetException { // create a buffer to improve copy performance later. byte[] buffer = new byte[2048]; File directory = null;/* w ww.j a v a 2 s .c o m*/ File first = null; try { directory = new File(FileUtils.getTempDirectory(), new Long(configuration.getGenerator().next()).toString()); directory.mkdirs(); ZipInputStream zstream = new ZipInputStream(iStream); ZipEntry entry; while ((entry = zstream.getNextEntry()) != null) { File file = new File(directory, entry.getName()); if (first == null && file.getName().endsWith("dbf")) { first = file; } FileOutputStream output = null; try { output = new FileOutputStream(file); int len = 0; while ((len = zstream.read(buffer)) > 0) { output.write(buffer, 0, len); } } finally { if (output != null) { output.close(); } } } if (first != null) { this.createFeatures(first.toURI().toURL()); } else { // TODO Change exception type throw new RuntimeException("Empty zip file"); } } catch (IOException e1) { throw new RuntimeException(e1); } finally { if (directory != null) { try { FileUtils.deleteDirectory(directory); } catch (IOException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } } }