List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:com.knowgate.dfs.FileSystem.java
/** * Download an HTML page and all its referenced files into a ZIP * @param sBasePath String Base path for page and its referenced files * @param sFilePath String File path from sBasePath * @param oOutStrm OutputStream where ZIP is written * @param sDefaultEncoding Character encoding of file to be downloaded * @throws IOException//from w w w.j a va 2s .c o m * @since 7.0 */ public void downloadhtmlpage(String sBasePath, String sFilePath, OutputStream oOutStrm, String sDefaultEncoding) throws IOException { if (DebugFile.trace) { DebugFile.writeln("Begin FileSystem.downloadhtmlpage(" + sBasePath + "," + sFilePath + ",[OutputStream]," + sDefaultEncoding + ")"); DebugFile.incIdent(); } String sEncoding = sDefaultEncoding; String sBaseHref = ""; boolean bAutoDetectEncoding = (sDefaultEncoding == null); TreeSet<String> oFiles = new TreeSet<String>(); TreeSet<String> oEntries = new TreeSet<String>(); Perl5Matcher oMatcher = new Perl5Matcher(); Perl5Matcher oReplacer = new Perl5Matcher(); Perl5Compiler oCompiler = new Perl5Compiler(); if (sDefaultEncoding == null) sDefaultEncoding = "ASCII"; try { String sHtml = readfilestr(sBasePath + sFilePath, sDefaultEncoding); if (null == sHtml) { if (DebugFile.trace) { DebugFile.writeln("Could not read file " + sBasePath + sFilePath); DebugFile.decIdent(); throw new IOException("Could not read file " + sBasePath + sFilePath); } } if (DebugFile.trace) { DebugFile.writeln( String.valueOf(sHtml.length()) + " characters readed from file " + sBasePath + sFilePath); } if (bAutoDetectEncoding) { if (oMatcher.contains(sHtml, oCompiler.compile( "<meta\\x20+http-equiv=(\"|')?Content-Type(\"|')?\\x20+content=(\"|')?text/html;\\x20+charset=(\\w|-){3,32}(\"|')?>", Perl5Compiler.CASE_INSENSITIVE_MASK))) { if (DebugFile.trace) DebugFile.writeln("<meta http-equiv> tag found"); String sHttpEquiv = oMatcher.getMatch().toString(); int iCharset = Gadgets.indexOfIgnoreCase(sHttpEquiv, "charset="); if (iCharset > 0) { int iQuoute = sHttpEquiv.indexOf('"', iCharset); if (iQuoute < 0) iQuoute = sHttpEquiv.indexOf((char) 39, iCharset); if (iQuoute < 0) { bAutoDetectEncoding = true; } else { sEncoding = sHttpEquiv.substring(iCharset + 8, iQuoute); if (DebugFile.trace) DebugFile.writeln("setting charset encoding to " + sEncoding); bAutoDetectEncoding = false; try { byte[] aTest = new String("Test").getBytes(sEncoding); } catch (UnsupportedEncodingException uex) { bAutoDetectEncoding = true; } } } else { bAutoDetectEncoding = true; } } else { bAutoDetectEncoding = true; } } if (bAutoDetectEncoding) { if (DebugFile.trace) DebugFile.writeln("Autodetecting encoding"); ByteArrayInputStream oHtmlStrm = new ByteArrayInputStream(sHtml.getBytes(sDefaultEncoding)); sEncoding = new CharacterSetDetector().detect(oHtmlStrm, sDefaultEncoding); oHtmlStrm.close(); if (DebugFile.trace) DebugFile.writeln("Encoding set to " + sEncoding); } Pattern oPattern = oCompiler.compile("<base(\\x20)+href=(\"|')?([^'\"\\r\\n]+)(\"|')?(\\x20)*/?>", Perl5Compiler.CASE_INSENSITIVE_MASK); if (oMatcher.contains(sHtml, oPattern)) { sBaseHref = Gadgets.chomp(oMatcher.getMatch().group(3), "/"); if (DebugFile.trace) DebugFile.writeln("<base href=" + sBaseHref + ">"); } PatternMatcherInput oMatchInput = new PatternMatcherInput(sHtml); oPattern = oCompiler.compile( "\\x20(src=|background=|background-image:url\\x28)(\"|')?([^'\"\\r\\n]+)(\"|')?(\\x20|\\x29|/|>)", Perl5Compiler.CASE_INSENSITIVE_MASK); StringSubstitution oSrcSubs = new StringSubstitution(); int nMatches = 0; while (oMatcher.contains(oMatchInput, oPattern)) { nMatches++; String sMatch = oMatcher.getMatch().toString(); String sAttr = oMatcher.getMatch().group(1); String sQuo = oMatcher.getMatch().group(2); if (sQuo == null) sQuo = ""; String sSrc = oMatcher.getMatch().group(3); if (DebugFile.trace) DebugFile.writeln("Source file found at " + sSrc); String sEnd = oMatcher.getMatch().group(5); if (!oFiles.contains(sSrc)) oFiles.add(sSrc); String sFilename = sSrc.substring(sSrc.replace('\\', '/').lastIndexOf('/') + 1); if (DebugFile.trace) DebugFile.writeln("StringSubstitution.setSubstitution(" + sMatch + " replace with " + sMatch.substring(0, sAttr.length() + 1) + sQuo + sFilename + sQuo + sEnd + ")"); oSrcSubs.setSubstitution(sMatch.substring(0, sAttr.length() + 1) + sQuo + sFilename + sQuo + sEnd); sHtml = Util.substitute(oReplacer, oCompiler.compile(sMatch), oSrcSubs, sHtml, Util.SUBSTITUTE_ALL); } //wend oMatchInput = new PatternMatcherInput(sHtml); oPattern = oCompiler.compile( "<link\\x20+(rel=(\"|')?stylesheet(\"|')?\\x20+)?(type=(\"|')?text/css(\"|')?\\x20+)?href=(\"|')?([^'\"\\r\\n]+)(\"|')?"); while (oMatcher.contains(oMatchInput, oPattern)) { nMatches++; String sMatch = oMatcher.getMatch().toString(); String sSrc = oMatcher.getMatch().group(8); String sFilename = sSrc.substring(sSrc.replace('\\', '/').lastIndexOf('/') + 1); if (!oFiles.contains(sSrc)) oFiles.add(sSrc); if (DebugFile.trace) DebugFile.writeln("StringSubstitution.setSubstitution(" + sMatch + " replace with " + Gadgets.replace(sMatch, sSrc, sFilename) + ")"); oSrcSubs.setSubstitution(Gadgets.replace(sMatch, sSrc, sFilename)); sHtml = Util.substitute(oReplacer, oCompiler.compile(sMatch), oSrcSubs, sHtml); } // wend if (DebugFile.trace) { DebugFile.writeln(String.valueOf(nMatches) + " matches found"); DebugFile.write("\n" + sHtml + "\n"); } ZipOutputStream oZOut = new ZipOutputStream(oOutStrm); String sLocalName = sFilePath.substring(sFilePath.replace('\\', '/').lastIndexOf('/') + 1); int iDot = sLocalName.lastIndexOf('.'); if (iDot > 0) sLocalName = Gadgets.ASCIIEncode(sLocalName.substring(0, iDot)).toLowerCase() + ".html"; else sLocalName = Gadgets.ASCIIEncode(sLocalName).toLowerCase(); oEntries.add(sLocalName); if (DebugFile.trace) DebugFile.writeln("Putting entry " + sLocalName + " into ZIP"); oZOut.putNextEntry(new ZipEntry(sLocalName)); StringBufferInputStream oHtml = new StringBufferInputStream(sHtml); new StreamPipe().between(oHtml, oZOut); oHtml.close(); oZOut.closeEntry(); for (String sName : oFiles) { String sZipEntryName = sName.substring(sName.replace('\\', '/').lastIndexOf('/') + 1); if (!oEntries.contains(sZipEntryName)) { oEntries.add(sZipEntryName); if (DebugFile.trace) DebugFile.writeln("Putting entry " + sZipEntryName + " into ZIP"); oZOut.putNextEntry(new ZipEntry(sZipEntryName)); if (sName.startsWith("http://") || sName.startsWith("https://") || sName.startsWith("file://") || sBaseHref.length() > 0) { try { new StreamPipe().between(new ByteArrayInputStream(readfilebin(sBaseHref + sName)), oZOut); } catch (IOException ioe) { if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("Could not download file " + sName); } } } else { try { byte[] aFile = readfilebin( sBasePath + (sName.startsWith("/") ? sName.substring(1) : sName)); if (null != aFile) { if (aFile.length > 0) new StreamPipe().between(new ByteArrayInputStream(aFile), oZOut); } else { DebugFile.writeln("Could not find file " + sBasePath + (sName.startsWith("/") ? sName.substring(1) : sName)); } } catch (IOException ioe) { if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("Could not download file " + sBasePath + (sName.startsWith("/") ? sName.substring(1) : sName)); } } } oZOut.closeEntry(); } // fi (sName!=sLocalName) } // next oZOut.close(); } catch (MalformedPatternException mpe) { } catch (FTPException ftpe) { } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End FileSystem.downloadhtmlpage()"); } }
From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java
public File getZipFileExport() { File zipOutputFile;// www . j ava 2s . co m ZipOutputStream zout; String exportTimestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date()); try { zipOutputFile = File.createTempFile("dataDownload", "zip"); zout = new ZipOutputStream((OutputStream) new FileOutputStream(zipOutputFile)); if (includeCSV) { File csvFile = File.createTempFile("dataDownload_", "csv"); //writeFile(csvFile, csvString.toString().toCharArray(), csvString.length()); writeFile(csvFile, csvString, csvString.length()); addZipEntry(zout, csvFile.getAbsolutePath(), "csvData_" + exportTimestamp + ".txt"); if (csvFile != null && csvFile.exists()) { if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) { csvFile.delete(); } } } if (includeImage || includePdf) { File imageUrlFile = includeImage ? File.createTempFile("dataDownload", "png") : null; File imagePdfFile = includePdf ? File.createTempFile("dataDownload", "pdf") : null; writeImageFile(imageUrlFile, imagePdfFile); if (includeImage) { addZipEntry(zout, imageUrlFile.getAbsolutePath(), "imageGraph_" + exportTimestamp + ".png"); } if (includePdf) { addZipEntry(zout, imagePdfFile.getAbsolutePath(), "imagePdf_" + exportTimestamp + ".pdf"); } if (imageUrlFile != null && imageUrlFile.exists()) { if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) { imageUrlFile.delete(); } } if (imagePdfFile != null && imagePdfFile.exists()) { if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) { imagePdfFile.delete(); } } } if (includeExcel) { File excelDataFile = File.createTempFile("dataDownload", "xls"); writeExcelFile(excelDataFile); addZipEntry(zout, excelDataFile.getAbsolutePath(), "excelData_" + exportTimestamp + ".xls"); if (excelDataFile != null && excelDataFile.exists()) { if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) { excelDataFile.delete(); } } } zout.close(); } catch (IOException e) { throw new EJBException(e); } catch (Exception ie) { zipOutputFile = null; } // TODO: make sure the zip file itself gets deleted as well. // - L.A. return zipOutputFile; }
From source file:com.topsec.tsm.sim.event.web.EventQueryController.java
/** * // w ww . j a va2 s . c o m * @author zhaojun 2014-2-25?4:05:38 * @param resultMap * @param condition * @param header * @return * @throws LogSearchException */ private String exportProcess(Map<String, Object> resultMap, Condition condition, String header, String fields) throws LogSearchException { List<Map<String, Object>> list = (List<Map<String, Object>>) resultMap.get("rows"); String filePath = ""; String zipFile = System.currentTimeMillis() + ".zip"; zipFile = System.getProperty("java.io.tmpdir") + File.separator + zipFile; File uploadFile = new File(zipFile); ZipOutputStream zipOut = null; WritableWorkbook book = null; try { zipOut = new ZipOutputStream(new FileOutputStream(uploadFile)); ZipEntry ze = new ZipEntry( zipFile.replaceFirst(".zip", ".xls").substring(zipFile.lastIndexOf(File.separator) + 1)); zipOut.putNextEntry(ze); String[] strTitle = {}; String[] strHeader = {}; if (fields != "" && header != "") { strTitle = fields.split(","); strHeader = header.split(","); } //java excel api //open file book = Workbook.createWorkbook(zipOut); WritableSheet front = book.createSheet("??", 0); WritableFont font = new WritableFont(WritableFont.createFont("")); font.setPointSize(36); font.setBoldStyle(WritableFont.BOLD); font.setColour(Colour.RED); WritableCellFormat cellFormat = new WritableCellFormat(font); cellFormat.setAlignment(Alignment.CENTRE); cellFormat.setBackground(Colour.GRAY_25); cellFormat.setWrap(true); cellFormat.setBorder(Border.ALL, BorderLineStyle.MEDIUM); cellFormat.setLocked(true); cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE); Label title = new Label(0, 0, "", cellFormat); front.addCell(title); front.mergeCells(0, 0, 10, 20); front.getSettings().setHidden(false); front.getSettings().setSelected(true); //create Sheet with name "" WritableSheet sheet = book.createSheet("1", 1); sheet.getSettings().setHidden(false); sheet.getSettings().setDefaultColumnWidth(20); title.setString("\012" + list.size() + "?"); WritableFont fontHeader = new WritableFont(WritableFont.createFont("")); fontHeader.setBoldStyle(WritableFont.BOLD); fontHeader.setColour(Colour.RED); WritableCellFormat cellFormatHeader = new WritableCellFormat(fontHeader); cellFormatHeader.setAlignment(Alignment.CENTRE); cellFormatHeader.setBackground(Colour.BLUE2); cellFormatHeader.setBorder(Border.ALL, BorderLineStyle.MEDIUM); cellFormatHeader.setLocked(true); cellFormatHeader.setVerticalAlignment(VerticalAlignment.CENTRE); int i = 0; for (String head : strHeader) { Label label = new Label(i++, 0, head, cellFormatHeader); sheet.addCell(label); } int m = 1; int page = 1; for (Map<String, Object> elem : list) { if (page == 1) { if (m % 1001 == 0) { page++; sheet = book.createSheet("" + page, page); sheet.setColumnView(0, 20); sheet.getSettings().setHidden(false); sheet.getSettings().setDefaultColumnWidth(20); m = 0; } } else { if (m % 1000 == 0) { page++; sheet = book.createSheet("" + page, page); sheet.setColumnView(0, 20); sheet.getSettings().setHidden(false); sheet.getSettings().setDefaultColumnWidth(20); m = 0; } } Map<String, Object> record = (Map<String, Object>) elem; int n = 0; for (String tit : strTitle) { Object value = record.get(tit); if (tit.equalsIgnoreCase("PRIORITY")) { value = CommonUtils.getLevel(value); } if (value != null) { Label label = new Label(n++, m, value.toString()); sheet.addCell(label); } else { Label label = new Label(n++, m, "null"); sheet.addCell(label); } } m++; } } catch (Exception e) { throw new LogSearchException(e); } finally { if (book != null) { try { book.write(); book.setProtected(true); book.close(); } catch (Exception e) { e.printStackTrace(); } } if (zipOut != null) try { zipOut.close(); } catch (IOException e) { e.printStackTrace(); } } try { //FTP ? Map<String, Object> ftpmap = FtpConfigUtil.getInstance().getFTPConfigByKey("log"); String uploadName = uploadFile.getName(); boolean result = FtpUploadUtil.uploadFile((String) ftpmap.get("host"), Integer.parseInt((String) ftpmap.get("port")), (String) ftpmap.get("user"), (String) ftpmap.get("password"), (String) ftpmap.get("encoding"), ".", uploadName, new FileInputStream(uploadFile)); FileUtils.deleteQuietly(uploadFile); if (result) { filePath = uploadName; } } catch (Exception e) { e.printStackTrace(); } return filePath; }
From source file:com.smartbear.collaborator.issue.IssueRest.java
/** * Downloads raw files from Fisheye, calculates checksum for each file and * puts them to zip file//from www. j a v a2 s .co m * * @param changesetList * @return * @throws Exception */ private java.io.File downloadRawFilesFromFisheye(List<Changeset> changesetList) throws Exception { // Create temp zip file where versions will be put java.io.File targetZipFile = java.io.File.createTempFile("store-", ".zip"); String urlGetRawFileContent = null; byte[] fileBytes = null; try { FileOutputStream fileOutputStream = new FileOutputStream(targetZipFile); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); HashSet<String> zipEntryNames = new HashSet<String>(); Client client; WebResource service; ClientResponse response; InputStream fileInputStream; ZipEntry zipEntry; Action action; // Go through repositories->commits->files to put versions in temp // zip file for (Changeset changeset : changesetList) { for (File file : changeset.getFiles()) { // Get raw file content from Fisheye server // Example // http://nb-kpl:8060/browse/~raw,r=HEAD/svn_test/test/log.txt action = Util.getVersionAction(file.getChangeType()); if (action == null) { continue; } if (action == Action.DELETED) { fileBytes = new byte[0]; } else { urlGetRawFileContent = Util.encodeURL(configModel.getFisheyeUrl() + file.getContentLink()); response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false); fileInputStream = response.getEntity(InputStream.class); fileBytes = IOUtils.toByteArray(fileInputStream); LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent); LOGGER.debug("Response from Fisheye" + new String(fileBytes)); //Check that we really received file content checkRawFileResponse(response); } // Set calculated md5 for raw version file.setMd5(calculateMd5(fileBytes)); if (!zipEntryNames.contains(file.getMd5())) { zipEntry = new ZipEntry(file.getMd5()); zipOutputStream.putNextEntry(zipEntry); // write version to temp zip file zipOutputStream.write(fileBytes); zipEntryNames.add(file.getMd5()); } // Check if file was modified/deleted then download also // previous version if (action == Action.MODIFIED || action == Action.DELETED) { if (!Util.isEmpty(file.getAncestor())) { ClientResponse ancestorChangesetResp = getFisheyeClientResponse( Util.encodeURL(configModel.getFisheyeUrl() + FISHEYE_CHANGESET_API + changeset.getRepositoryName() + "/" + file.getAncestor()), configModel, true); String ancestorChangesetRespString = ancestorChangesetResp.getEntity(String.class); ObjectNode ancestorChangesetNode = (ObjectNode) mapper .readTree(ancestorChangesetRespString); file.setPreviousCommitAuthor(ancestorChangesetNode.get("author").asText()); file.setPreviousCommitDate(new Date(ancestorChangesetNode.get("date").asLong())); file.setPreviousCommitComment(ancestorChangesetNode.get("comment").asText()); urlGetRawFileContent = Util .encodeURL(configModel.getFisheyeUrl() + "/browse/~raw,r=" + file.getAncestor() + "/" + changeset.getRepositoryName() + "/" + file.getPath()); response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false); fileInputStream = response.getEntity(InputStream.class); fileBytes = IOUtils.toByteArray(fileInputStream); LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent); LOGGER.debug("Response from Fisheye" + new String(fileBytes)); //Check that we really received file content checkRawFileResponse(response); // Set calculated md5 for raw version file.setPreviousMd5(calculateMd5(fileBytes)); if (!zipEntryNames.contains(file.getPreviousMd5())) { zipEntry = new ZipEntry(file.getPreviousMd5()); zipOutputStream.putNextEntry(zipEntry); // write version to temp zip file zipOutputStream.write(fileBytes); zipEntryNames.add(file.getPreviousMd5()); } } else { String errorMsg = "Please, try to \"Create/Update Review\" a little bit later. FishEye server hasn't been refreshed commit info yet."; LOGGER.error(errorMsg); throw new Exception(errorMsg); } } } } // close ZipEntry to store the stream to the file zipOutputStream.closeEntry(); zipOutputStream.close(); fileOutputStream.close(); return targetZipFile; } catch (Exception e) { LOGGER.error("Request URL to Fisheye: " + urlGetRawFileContent, e); LOGGER.error("Response from Fisheye: " + (fileBytes != null ? new String(fileBytes) : ""), e); throw new Exception( "Can't download raw versions from FishEye server. Check that FishEye server is running. \n " + "Request URL to Fisheye: " + urlGetRawFileContent + "\n" + e.getMessage()); } }
From source file:lu.fisch.unimozer.Diagram.java
private void createBackup() { File fDir = new File(directoryName + System.getProperty("file.separator") + "src"); if (classes.size() > 0) { // check the versions directory String versionDir = directoryName + System.getProperty("file.separator") + "versions"; File versionFile = new File(versionDir); if (!versionFile.exists()) versionFile.mkdir();//w w w.j a va 2s. c o m // get the new filename SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); String now = dateFormater.format(new Date()); String zipFilename = now + ".zip"; zipFilename = directoryName + System.getProperty("file.separator") + "versions" + System.getProperty("file.separator") + zipFilename; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(zipFilename))); addToZip(out, now + System.getProperty("file.separator"), fDir); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
private void setAttachedFilesList(Object[] r, LogWriter log) throws Exception { String realSourceFileFoldername = null; String realSourceWildcard = null; FileObject sourcefile = null; FileObject file = null;/*from w ww. ja v a2s .c om*/ ZipOutputStream zipOutputStream = null; File masterZipfile = null; if (meta.isZipFilenameDynamic()) data.ZipFilename = data.previousRowMeta.getString(r, data.indexOfDynamicZipFilename); try { if (meta.isDynamicFilename()) { // dynamic attached filenames if (data.indexOfSourceFilename > -1) realSourceFileFoldername = data.previousRowMeta.getString(r, data.indexOfSourceFilename); if (data.indexOfSourceWildcard > -1) realSourceWildcard = data.previousRowMeta.getString(r, data.indexOfSourceWildcard); } else { // static attached filenames realSourceFileFoldername = data.realSourceFileFoldername; realSourceWildcard = data.realSourceWildcard; } if (!Const.isEmpty(realSourceFileFoldername)) { sourcefile = KettleVFS.getFileObject(realSourceFileFoldername); if (sourcefile.exists()) { long FileSize = 0; FileObject list[] = null; if (sourcefile.getType() == FileType.FILE) { list = new FileObject[1]; list[0] = sourcefile; } else list = sourcefile .findFiles(new TextFileSelector(sourcefile.toString(), realSourceWildcard)); if (list.length > 0) { boolean zipFiles = meta.isZipFiles(); if (zipFiles && data.zipFileLimit == 0) { masterZipfile = new File( System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename); zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); } for (int i = 0; i < list.length; i++) { file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i])); if (zipFiles) { if (data.zipFileLimit == 0) { ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); } else FileSize += file.getContent().getSize(); } else { addAttachedFilePart(file); } } // end for if (zipFiles) { if (log.isDebug()) log.logDebug(toString(), Messages.getString("Mail.Log.FileSize", "" + FileSize)); if (log.isDebug()) log.logDebug(toString(), Messages.getString("Mail.Log.LimitSize", "" + data.zipFileLimit)); if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit) { masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename); zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (int i = 0; i < list.length; i++) { file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i])); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); } } if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit || data.zipFileLimit == 0) { file = KettleVFS.getFileObject(masterZipfile.getAbsolutePath()); addAttachedFilePart(file); } } } } else { log.logError(toString(), Messages.getString("Mail.Error.SourceFileFolderNotExists", realSourceFileFoldername)); } } } catch (Exception e) { log.logError(toString(), e.getMessage()); } finally { if (sourcefile != null) { try { sourcefile.close(); } catch (Exception e) { } } if (file != null) { try { file.close(); } catch (Exception e) { } } if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); } } } }
From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java
/** * Generate an "archive" of the data package by parsing and retrieving * components of the data package resource map * /*from w w w . j a v a 2 s. c om*/ * @param scope * The scope value of the data package * @param identifier * The identifier value of the data package * @param revision * The revision value of the data package * @param map * The resource map of the data package * @param authToken * The authentication token of the user requesting the archive * @param transaction * The transaction id of the request * @return The file name of the data package archive * @throws Exception */ public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId, AuthToken authToken, String transaction) throws Exception { String zipName = transaction + ".zip"; String zipPath = tmpDir + "/"; EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision); StringBuffer manifest = new StringBuffer(); Date now = new Date(); manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n"); DataPackageManager dpm = null; /* * It is necessary to create a temporary file while building the ZIP archive * to prevent the client from accessing an incomplete product. */ String tmpName = DigestUtils.md5Hex(transaction); File zFile = new File(zipPath + tmpName); if (zFile.exists()) { String gripe = "The resource " + zipName + "already exists!"; throw new ResourceExistsException(gripe); } try { dpm = new DataPackageManager(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); throw e; } FileOutputStream fOut = null; try { fOut = new FileOutputStream(zFile); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } if (dpm != null && fOut != null) { String map = null; try { map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); throw e; } Scanner mapScanner = new Scanner(map); ZipOutputStream zOut = new ZipOutputStream(fOut); while (mapScanner.hasNextLine()) { FileInputStream fIn = null; String objectName = null; File file = null; String line = mapScanner.nextLine(); if (line.contains(URI_MIDDLE_METADATA)) { try { file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken); objectName = emlPackageId.toString() + ".xml"; } catch (ClassNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } if (file != null) { try { fIn = new FileInputStream(file); Long size = FileUtils.sizeOf(file); manifest.append(objectName + " (" + size.toString() + " bytes)\n"); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } } } else if (line.contains(URI_MIDDLE_REPORT)) { try { file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId, authToken, userId); objectName = emlPackageId.toString() + ".report.xml"; } catch (ClassNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } if (file != null) { try { fIn = new FileInputStream(file); Long size = FileUtils.sizeOf(file); manifest.append(objectName + " (" + size.toString() + " bytes)\n"); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } } } else if (line.contains(URI_MIDDLE_DATA)) { String[] lineParts = line.split("/"); String entityId = lineParts[lineParts.length - 1]; String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage, scope, identifier, revision, null); String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope, identifier, revision, entityId); String entityName = null; String xml = null; try { entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken); xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken); objectName = dpm.findObjectName(xml, entityName); file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken, userId); } catch (UnauthorizedException e) { logger.error(e.getMessage()); e.printStackTrace(); manifest.append(objectName + " (access denied)\n"); } catch (ResourceNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } if (file != null) { try { fIn = new FileInputStream(file); Long size = FileUtils.sizeOf(file); manifest.append(objectName + " (" + size.toString() + " bytes)\n"); } catch (FileNotFoundException e) { logger.error(e.getMessage()); e.printStackTrace(); } } } if (objectName != null && fIn != null) { ZipEntry zipEntry = new ZipEntry(objectName); try { zOut.putNextEntry(zipEntry); int length; byte[] buffer = new byte[1024]; while ((length = fIn.read(buffer)) > 0) { zOut.write(buffer, 0, length); } zOut.closeEntry(); fIn.close(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } } // Create ZIP archive manifest File mFile = new File(zipPath + transaction + ".txt"); FileUtils.writeStringToFile(mFile, manifest.toString()); ZipEntry zipEntry = new ZipEntry("manifest.txt"); try { FileInputStream fIn = new FileInputStream(mFile); zOut.putNextEntry(zipEntry); int length; byte[] buffer = new byte[1024]; while ((length = fIn.read(buffer)) > 0) { zOut.write(buffer, 0, length); } zOut.closeEntry(); fIn.close(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } // Close ZIP archive zOut.close(); FileUtils.forceDelete(mFile); } File tmpFile = new File(zipPath + tmpName); File zipFile = new File(zipPath + zipName); // Copy hidden ZIP archive to visible ZIP archive, thus making available if (!tmpFile.renameTo(zipFile)) { String gripe = "Error renaming " + tmpName + " to " + zipName + "!"; throw new IOException(); } return zipName; }
From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.java
@Override public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]"; Printer printer = null;//from www . j a va2 s . c o m try { int numeroZipEntries = 0; this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita); boolean eseguiRicerca = !setDomini.isEmpty(); VersamentiBD versamentiBD = new VersamentiBD(bd); EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd); VersamentoFilter filter = versamentiBD.newFilter(); List<Long> ids = new ArrayList<Long>(); ids.add(idToExport); if (!setDomini.contains(-1L)) { List<Long> lstCodDomini = new ArrayList<Long>(); lstCodDomini.addAll(setDomini); filter.setIdDomini(lstCodDomini); // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi. if (eseguiRicerca) { filter.setIdVersamento(ids); eseguiRicerca = eseguiRicerca && versamentiBD.count(filter) > 0; } } Versamento versamento = eseguiRicerca ? versamentiBD.getVersamento(idToExport) : null; String fileName = "Export.zip"; if (versamento != null) { // Prelevo il dominio UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Estratto conto per iban e codiceversamento. List<Long> idVersamentiDominio = new ArrayList<Long>(); idVersamentiDominio.add(idToExport); it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoVersamentiPDF(dominio, idVersamentiDominio); List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); listInputEstrattoConto.add(input); String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD .getEstrattoContoVersamenti(listInputEstrattoConto, pathLoghi); for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) { Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput(); for (String nomeEntry : estrattoContoVersamenti.keySet()) { numeroZipEntries++; ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry); ZipEntry estrattoContoEntry = new ZipEntry( estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry); zout.putNextEntry(estrattoContoEntry); zout.write(baos.toByteArray()); zout.closeEntry(); } } //Estratto conto in formato CSV EstrattoContoFilter ecFilter = estrattiContoBD.newFilter(true); ecFilter.setIdVersamento(ids); List<EstrattoConto> findAll = estrattiContoBD.estrattoContoFromIdVersamenti(ecFilter); if (findAll != null && findAll.size() > 0) { //ordinamento record Collections.sort(findAll, new EstrattoContoComparator()); numeroZipEntries++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ZipEntry pagamentoCsv = new ZipEntry("estrattoConto.csv"); zout.putNextEntry(pagamentoCsv); printer = new Printer(this.getFormat(), baos); printer.printRecord(CSVUtils.getEstrattoContoCsvHeader()); for (EstrattoConto pagamento : findAll) { printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf)); } } finally { try { if (printer != null) { printer.close(); } } catch (Exception e) { throw new Exception("Errore durante la chiusura dello stream ", e); } } zout.write(baos.toByteArray()); zout.closeEntry(); } } // se non ho inserito nessuna entry if (numeroZipEntries == 0) { String noEntriesTxt = "/README"; ZipEntry entryTxt = new ZipEntry(noEntriesTxt); zout.putNextEntry(entryTxt); zout.write("Non sono state trovate informazioni sui versamenti selezionati.".getBytes()); zout.closeEntry(); } zout.flush(); zout.close(); this.log.info("Esecuzione " + methodName + " completata."); return fileName; } catch (WebApplicationException e) { throw e; } catch (ExportException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:it.govpay.web.rs.dars.reportistica.pagamenti.PagamentiHandler.java
@Override public String esporta(Long idToExport, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException { String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]"; Printer printer = null;/*from ww w . jav a 2s . co m*/ int numeroZipEntries = 0; try { String fileName = "Pagamenti.zip"; this.log.info("Esecuzione " + methodName + " in corso..."); Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); ProfiloOperatore profilo = operatore.getProfilo(); boolean isAdmin = profilo.equals(ProfiloOperatore.ADMIN); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd); EstrattiContoBD pagamentiBD = new EstrattiContoBD(bd); EstrattoContoFilter filter = pagamentiBD.newFilter(); boolean eseguiRicerca = true; List<Long> ids = new ArrayList<Long>(); ids.add(idToExport); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); if (!isAdmin) { AclBD aclBD = new AclBD(bd); List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId()); boolean vediTuttiDomini = false; List<Long> idDomini = new ArrayList<Long>(); for (Acl acl : aclOperatore) { if (Tipo.DOMINIO.equals(acl.getTipo())) { if (acl.getIdDominio() == null) { vediTuttiDomini = true; break; } else { idDomini.add(acl.getIdDominio()); } } } if (!vediTuttiDomini) { if (idDomini.isEmpty()) { eseguiRicerca = false; } else { filter.setIdDomini(toListCodDomini(idDomini, bd)); } } // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi. if (eseguiRicerca) { filter.setIdSingoloVersamento(ids); eseguiRicerca = eseguiRicerca && pagamentiBD.count(filter) > 0; } } if (eseguiRicerca) { // recupero oggetto filter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? pagamentiBD.estrattoContoFromIdSingoliVersamenti(filter) : new ArrayList<EstrattoConto>(); if (findAll != null && findAll.size() > 0) { numeroZipEntries++; //ordinamento record Collections.sort(findAll, new EstrattoContoComparator()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv"); zout.putNextEntry(pagamentoCsv); printer = new Printer(this.getFormat(), baos); printer.printRecord(CSVUtils.getEstrattoContoCsvHeader()); for (EstrattoConto pagamento : findAll) { printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf)); } } finally { try { if (printer != null) { printer.close(); } } catch (Exception e) { throw new Exception("Errore durante la chiusura dello stream ", e); } } zout.write(baos.toByteArray()); zout.closeEntry(); } SingoloVersamento singoloVersamento = singoliVersamentiBD.getSingoloVersamento(idToExport); Versamento versamento = singoloVersamento.getVersamento(bd); UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Estratto conto per iban e codiceversamento. List<Long> idSingoliVersamentiDominio = new ArrayList<Long>(); idSingoliVersamentiDominio.add(idToExport); it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoPagamentiPDF(dominio, idSingoliVersamentiDominio); List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); listInputEstrattoConto.add(input); String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi); for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) { Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput(); for (String nomeEntry : estrattoContoVersamenti.keySet()) { numeroZipEntries++; ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry); // ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry); ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry); zout.putNextEntry(estrattoContoEntry); zout.write(baos.toByteArray()); zout.closeEntry(); } } } // se non ho inserito nessuna entry if (numeroZipEntries == 0) { String noEntriesTxt = "/README"; ZipEntry entryTxt = new ZipEntry(noEntriesTxt); zout.putNextEntry(entryTxt); zout.write("Non sono state trovate informazioni sui pagamenti selezionati.".getBytes()); zout.closeEntry(); } zout.flush(); zout.close(); this.log.info("Esecuzione " + methodName + " completata."); return fileName; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:it.govpay.web.rs.dars.monitoraggio.pagamenti.ReportisticaPagamentiHandler.java
@Override public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]"; Printer printer = null;// w w w . java 2s .c om int numeroZipEntries = 0; try { String fileName = "Pagamenti.zip"; this.log.info("Esecuzione " + methodName + " in corso..."); // Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd); EstrattiContoBD pagamentiBD = new EstrattiContoBD(bd); EstrattoContoFilter filter = pagamentiBD.newFilter(); boolean eseguiRicerca = true; List<Long> ids = new ArrayList<Long>(); ids.add(idToExport); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); // if(!isAdmin){ // // AclBD aclBD = new AclBD(bd); // List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId()); // // boolean vediTuttiDomini = false; // List<Long> idDomini = new ArrayList<Long>(); // for(Acl acl: aclOperatore) { // if(Tipo.DOMINIO.equals(acl.getTipo())) { // if(acl.getIdDominio() == null) { // vediTuttiDomini = true; // break; // } else { // idDomini.add(acl.getIdDominio()); // } // } // } // if(!vediTuttiDomini) { // if(idDomini.isEmpty()) { // eseguiRicerca = false; // } else { // filter.setIdDomini(toListCodDomini(idDomini, bd)); // } // } // // // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi. // if(eseguiRicerca){ // filter.setIdSingoloVersamento(ids); // eseguiRicerca = eseguiRicerca && pagamentiBD.count(filter) > 0; // } // } if (eseguiRicerca) { // recupero oggetto filter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? pagamentiBD.estrattoContoFromIdSingoliVersamenti(filter) : new ArrayList<EstrattoConto>(); if (findAll != null && findAll.size() > 0) { numeroZipEntries++; //ordinamento record Collections.sort(findAll, new EstrattoContoComparator()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv"); zout.putNextEntry(pagamentoCsv); printer = new Printer(this.getFormat(), baos); printer.printRecord(CSVUtils.getEstrattoContoCsvHeader()); for (EstrattoConto pagamento : findAll) { printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf)); } } finally { try { if (printer != null) { printer.close(); } } catch (Exception e) { throw new Exception("Errore durante la chiusura dello stream ", e); } } zout.write(baos.toByteArray()); zout.closeEntry(); } SingoloVersamento singoloVersamento = singoliVersamentiBD.getSingoloVersamento(idToExport); Versamento versamento = singoloVersamento.getVersamento(bd); UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Estratto conto per iban e codiceversamento. List<Long> idSingoliVersamentiDominio = new ArrayList<Long>(); idSingoliVersamentiDominio.add(idToExport); it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoPagamentiPDF(dominio, idSingoliVersamentiDominio); List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); listInputEstrattoConto.add(input); String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi); for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) { Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput(); for (String nomeEntry : estrattoContoVersamenti.keySet()) { numeroZipEntries++; ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry); // ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry); ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry); zout.putNextEntry(estrattoContoEntry); zout.write(baos.toByteArray()); zout.closeEntry(); } } } // se non ho inserito nessuna entry if (numeroZipEntries == 0) { String noEntriesTxt = "/README"; ZipEntry entryTxt = new ZipEntry(noEntriesTxt); zout.putNextEntry(entryTxt); zout.write("Non sono state trovate informazioni sui pagamenti selezionati.".getBytes()); zout.closeEntry(); } zout.flush(); zout.close(); this.log.info("Esecuzione " + methodName + " completata."); return fileName; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }