List of usage examples for java.util.zip ZipOutputStream close
public void close() throws IOException
From source file:org.syncope.core.scheduling.ReportJob.java
@Override public void execute(final JobExecutionContext context) throws JobExecutionException { Report report = reportDAO.find(reportId); if (report == null) { throw new JobExecutionException("Report " + reportId + " not found"); }//from ww w .ja v a2 s . c om // 1. create execution ReportExec execution = new ReportExec(); execution.setStatus(ReportExecStatus.STARTED); execution.setStartDate(new Date()); execution.setReport(report); execution = reportExecDAO.save(execution); // 2. define a SAX handler for generating result as XML TransformerHandler handler; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); zos.setLevel(Deflater.BEST_COMPRESSION); try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); handler = transformerFactory.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); // a single ZipEntry in the ZipOutputStream zos.putNextEntry(new ZipEntry(report.getName())); // streaming SAX handler in a compressed byte array stream handler.setResult(new StreamResult(zos)); } catch (Exception e) { throw new JobExecutionException("While configuring for SAX generation", e, true); } execution.setStatus(ReportExecStatus.RUNNING); execution = reportExecDAO.save(execution); ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext() .getBeanFactory(); // 3. actual report execution StringBuilder reportExecutionMessage = new StringBuilder(); StringWriter exceptionWriter = new StringWriter(); try { // report header handler.startDocument(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName()); handler.startElement("", "", ELEMENT_REPORT, atts); // iterate over reportlet instances defined for this report for (ReportletConf reportletConf : report.getReportletConfs()) { Class reportletClass = null; try { reportletClass = Class.forName(reportletConf.getReportletClassName()); } catch (ClassNotFoundException e) { LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e); } if (reportletClass != null) { Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false); autowired.setConf(reportletConf); // invoke reportlet try { autowired.extract(handler); } catch (Exception e) { execution.setStatus(ReportExecStatus.FAILURE); Throwable t = e instanceof ReportException ? e.getCause() : e; exceptionWriter.write(t.getMessage() + "\n\n"); t.printStackTrace(new PrintWriter(exceptionWriter)); reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n"); } } } // report footer handler.endElement("", "", ELEMENT_REPORT); handler.endDocument(); if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) { execution.setStatus(ReportExecStatus.SUCCESS); } } catch (Exception e) { execution.setStatus(ReportExecStatus.FAILURE); exceptionWriter.write(e.getMessage() + "\n\n"); e.printStackTrace(new PrintWriter(exceptionWriter)); reportExecutionMessage.append(exceptionWriter.toString()); throw new JobExecutionException(e, true); } finally { try { zos.closeEntry(); zos.close(); baos.close(); } catch (IOException e) { LOG.error("While closing StreamResult's backend", e); } execution.setExecResult(baos.toByteArray()); execution.setMessage(reportExecutionMessage.toString()); execution.setEndDate(new Date()); reportExecDAO.save(execution); } }
From source file:it.govpay.web.rs.dars.monitoraggio.eventi.EventiHandler.java
@Override public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { StringBuffer sb = new StringBuffer(); if (idsToExport != null && idsToExport.size() > 0) { for (Long long1 : idsToExport) { if (sb.length() > 0) { sb.append(", "); }//from w ww .j a v a 2s . c o m sb.append(long1); } } String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]"; String fileName = "Eventi.zip"; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Map<String, String> params = new HashMap<String, String>(); this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID); EventiBD eventiBD = new EventiBD(bd); EventiFilter filter = eventiBD.newFilter(simpleSearch); // se ho ricevuto anche gli id li utilizzo per fare il check della count if (idsToExport != null && idsToExport.size() > 0) filter.setIdEventi(idsToExport); boolean checkCount = this.popolaFiltroRicerca(rawValues, uriInfo, params, simpleSearch, filter); long count = eventiBD.count(filter); if (count < 1) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare")); throw new ExportException(msg, EsitoOperazione.ERRORE); } if (checkCount && count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima")); throw new ExportException(msg, EsitoOperazione.ERRORE); } filter.setOffset(0); if (checkCount) filter.setLimit(ConsoleProperties.getInstance().getNumeroMassimoElementiExport()); List<Evento> list = eventiBD.findAll(filter); if (list != null && list.size() > 0) { this.scriviCSVEventi(baos, list); ZipEntry datiEvento = new ZipEntry("eventi.csv"); zout.putNextEntry(datiEvento); zout.write(baos.toByteArray()); zout.closeEntry(); } else { String noEntriesTxt = "/README"; ZipEntry entryTxt = new ZipEntry(noEntriesTxt); zout.putNextEntry(entryTxt); zout.write("Non sono state trovate informazioni sugli eventi 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:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = new Result(nr); result.setResult(false);// w w w .jav a 2 s .c o m boolean Fileexists = false; String realZipfilename = StringUtil.environmentSubstitute(zipFilename); String realWildcard = StringUtil.environmentSubstitute(wildcard); String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude); String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory); String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory); if (realZipfilename != null) { FileObject fileObject = null; try { fileObject = KettleVFS.getFileObject(realZipfilename); // Check if Zip File exists if (fileObject.exists()) { Fileexists = true; log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label")); } else { Fileexists = false; } // Let's start the process now if (ifzipfileexists == 3 && Fileexists) { // the zip file exists and user want to Fail result.setResult(false); result.setNrErrors(1); } else if (ifzipfileexists == 2 && Fileexists) { // the zip file exists and user want to do nothing result.setResult(true); } else if (afterzip == 2 && realMovetodirectory == null) { // After Zip, Move files..User must give a destination Folder result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label")); } else // After Zip, Move files..User must give a destination Folder { if (ifzipfileexists == 0 && Fileexists) { // the zip file exists and user want to create new one with unique name //Format Date DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy"); realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip"; log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")); } else if (ifzipfileexists == 1 && Fileexists) { log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label") + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label")); } // Get all the files in the directory... File f = new File(realTargetdirectory); String[] filelist = f.list(); log.logDetailed(toString(), Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory + Messages.getString("JobZipFiles.Files_Found3.Label")); Pattern pattern = null; if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } Pattern patternexclude = null; if (!Const.isEmpty(realWildcardExclude)) { patternexclude = Pattern.compile(realWildcardExclude); } // Prepare Zip File byte[] buffer = new byte[18024]; FileOutputStream dest = new FileOutputStream(realZipfilename); BufferedOutputStream buff = new BufferedOutputStream(dest); ZipOutputStream out = new ZipOutputStream(buff); // Set the method out.setMethod(ZipOutputStream.DEFLATED); // Set the compression level if (compressionrate == 0) { out.setLevel(Deflater.NO_COMPRESSION); } else if (compressionrate == 1) { out.setLevel(Deflater.DEFAULT_COMPRESSION); } if (compressionrate == 2) { out.setLevel(Deflater.BEST_COMPRESSION); } if (compressionrate == 3) { out.setLevel(Deflater.BEST_SPEED); } // Specify Zipped files (After that we will move,delete them...) String[] ZippedFiles = new String[filelist.length]; int FileNum = 0; // Get the files in the list... for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) { boolean getIt = true; boolean getItexclude = false; // First see if the file matches the regular expression! if (pattern != null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (patternexclude != null) { Matcher matcherexclude = patternexclude.matcher(filelist[i]); getItexclude = matcherexclude.matches(); } // Get processing File String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i]; File file = new File(targetFilename); if (getIt && !getItexclude && !file.isDirectory()) { // We can add the file to the Zip Archive log.logDebug(toString(), Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i] + Messages.getString("JobZipFiles.Add_FilesToZip2.Label") + realTargetdirectory + Messages.getString("JobZipFiles.Add_FilesToZip3.Label")); // Associate a file input stream for the current file FileInputStream in = new FileInputStream(targetFilename); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(filelist[i])); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); // Close the current file input stream in.close(); // Get Zipped File ZippedFiles[FileNum] = filelist[i]; FileNum = FileNum + 1; } } // Close the ZipOutPutStream out.close(); //-----Get the list of Zipped Files and Move or Delete Them if (afterzip == 1 || afterzip == 2) { // iterate through the array of Zipped files for (int i = 0; i < ZippedFiles.length; i++) { if (ZippedFiles[i] != null) { // Delete File FileObject fileObjectd = KettleVFS .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]); // Here we can move, delete files if (afterzip == 1) { // Delete File boolean deleted = fileObjectd.delete(); if (!deleted) { result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.Cant_Delete_File1.Label") + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i] + Messages .getString("JobZipFiles.Cant_Delete_File2.Label")); } // File deleted log.logDebug(toString(), Messages.getString("JobZipFiles.File_Deleted1.Label") + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Deleted2.Label")); } else if (afterzip == 2) { // Move File try { FileObject fileObjectm = KettleVFS.getFileObject( realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]); fileObjectd.moveTo(fileObjectm); } catch (IOException e) { log.logError(toString(), Messages.getString("JobZipFiles.Cant_Move_File1.Label") + ZippedFiles[i] + Messages.getString("JobZipFiles.Cant_Move_File2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } // File moved log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label") + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label")); } } } } result.setResult(true); } } catch (IOException e) { log.logError(toString(), Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage()); result.setResult(false); result.setNrErrors(1); } finally { if (fileObject != null) { try { fileObject.close(); } catch (IOException ex) { } ; } } } else { result.setResult(false); result.setNrErrors(1); log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label")); } return result; }
From source file:com.esd.ps.WorkerController.java
/** * (wav?)/*from ww w . ja v a2 s . c o m*/ * @param response * @param downTaskCount * @param session * @param request * @param packType * @return */ @RequestMapping(value = "/downTask", method = RequestMethod.GET) @ResponseBody public Map<String, Object> downTask(final HttpServletResponse response, int downTaskCount, HttpSession session, HttpServletRequest request, int packType) { Map<String, Object> map = new HashMap<String, Object>(); //session?user_id int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()); //int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString())); //workeruser_idworker worker w = workerService.getWorkerByUserId(userId); if (w == null) { map.put("replay", 1); return map; } //worker_id int workerId = w.getWorkerId(); //workerdowningworker? //downing = 1 if (w.getDowning() == 1) { map.put("replay", 1); return map; } else { //worker_recordworker_idworker?? int doingtaskcount = workerRecordService.getDoingTaskCountByWorkerId(workerId); if (doingtaskcount > 0) { map.put("replay", 1); return map; } } //sessiondowning?1 session.setAttribute("downing", 1); logger.debug("downTaskCount:{}", downTaskCount); //taskpack_type?? int countTaskDoing = taskService.getCountTaskDoing(packType); // ???? if (countTaskDoing < downTaskCount) { // String nowCountTaskDoing=countTaskDoing + ""; map.put(Constants.MESSAGE, MSG_TASK_NOT_ENOUGH); session.setAttribute("downing", 0); return map; } //String realName = workerService.getWorkerRealNameByWorkerId(workerId); //?worker?? String realName = w.getWorkerRealName(); // int packId = packService.getPackIdOrderByPackLvl(); // ? worker worker = new worker(); worker.setWorkerId(workerId); worker.setDowning(1); //workerdowning workerService.updateByPrimaryKeySelective(worker); //? String url = WorkerController.url(request); logger.debug("url:{}", url); // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); //??? String downPackName = sdf.format(new Date()) + Constants.UNDERLINE + downTaskCount + Constants.UNDERLINE + userId + Constants.POINT + Constants.ZIP; String wrongPath = Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + downPackName; //?list String downPackName,String wrongPath,String realName,String userName List<taskWithBLOBs> list = taskService.updateWorkerIdDowningTask(downTaskCount, 0, userId, workerId, packType, downPackName, wrongPath, realName, session.getAttribute(Constants.USER_NAME).toString()); if (list == null) { session.setAttribute("downing", 0); return null; } File f = new File(url); if (f.exists() == false) { f.mkdir(); } //? File zipFile = new File(url + Constants.SLASH + downPackName); if (zipFile.exists()) { zipFile.delete(); } // ??? // String serverAndProjectPath = request.getLocalAddr() + // Constants.COLON + request.getLocalPort() + request.getContextPath(); // ? // String wrongPath = Constants.HTTP + serverAndProjectPath + // Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + // downPackName; //?? logger.debug("wrongPath:{}", wrongPath); try { zipFile.createNewFile(); FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)); byte[] bufs = new byte[1024 * 10]; for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) { taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next(); //?? String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName(); // ZIP, ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); //task?? byte[] data = taskWithBLOBs.getTaskWav(); //?? InputStream is = new ByteArrayInputStream(data); // ? BufferedInputStream bis = new BufferedInputStream(is, 1024); int read; while ((read = bis.read(bufs)) > 0) {// , 0, 2048 zos.write(bufs, 0, read);// } // zos.closeEntry(); bis.close(); is.close(); // task // worker_record // workerRecord workerRecord = new workerRecord(); // workerRecord.setCreateTime(new Date()); // workerRecord.setTaskOverTime(new Date()); // workerRecord.setDownPackName(downPackName); // workerRecord.setDownUrl(wrongPath); // workerRecord.setPackId(taskWithBLOBs.getPackId()); // workerRecord.setPackName(packService.getPackNameByPackId(taskWithBLOBs.getPackId())); // workerRecord.setTaskDownTime(new Date()); // workerRecord.setTaskId(taskWithBLOBs.getTaskId()); // int packLockTime = packService.getPackLockTime(taskWithBLOBs.getPackId()); // if (packLockTime > 0) { // workerRecord.setTaskLockTime(packLockTime); // } // workerRecord.setTaskName(taskWithBLOBs.getTaskName()); // //?? // workerRecord.setRealName(realName); // workerRecord.setTaskStatu(0); // workerRecord.setWorkerId(workerId); // workerRecord.setUserName(session.getAttribute(Constants.USER_NAME).toString()); // StackTraceElement[] items1 = Thread.currentThread().getStackTrace(); // workerRecord.setCreateMethod(items1[1].toString()); // workerRecordService.insertSelective(workerRecord); } session.setAttribute(Constants.WORKERMARK, 1); zos.close();// ,??0kb fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } /** * ,packStatus */ // if (taskService.getUndoTaskCountByPackId(packId) == 0) { // packWithBLOBs pack = new packWithBLOBs(); // pack.setPackId(packId); // pack.setPackStatus(2); // packService.updateByPrimaryKeySelective(pack); // } logger.debug("wrongPath:{}", wrongPath); map.put(Constants.WRONGPATH, wrongPath); map.put("replay", 0); session.setAttribute("downing", 0); // ? worker.setDowning(0); workerService.updateByPrimaryKeySelective(worker); return map; }
From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/splitMultipageFile", method = RequestMethod.POST) @ResponseBody/* www. j a v a2s. c om*/ public void splitMultipageFile(final HttpServletRequest req, final HttpServletResponse resp) { String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; try { if (req instanceof DefaultMultipartHttpServletRequest) { logger.info("Start spliting multipage file"); final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final BatchInstanceThread threadList = new BatchInstanceThread( new File(workingDir).getName() + Math.random()); String inputParams = WebServiceUtil.EMPTY_STRING, outputParams = WebServiceUtil.EMPTY_STRING; boolean isGSTool = false; for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("isGhostscript")) { isGSTool = Boolean.parseBoolean(multiPartRequest.getParameter(paramName)); logger.info("Value for isGhostscript parameter is " + isGSTool); continue; } if (paramName.equalsIgnoreCase("inputParams")) { inputParams = multiPartRequest.getParameter(paramName); logger.info("Value for inputParams parameter is " + inputParams); continue; } if (paramName.equalsIgnoreCase("outputParams")) { outputParams = multiPartRequest.getParameter(paramName); logger.info("Value for outputParams parameter is " + outputParams); continue; } } final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); // perform validation on input fields String results = WebServiceUtil.validateSplitAPI(fileMap, isGSTool, outputParams, inputParams); if (!results.isEmpty()) { respStr = results; } else { for (final String fileName : fileMap.keySet()) { if (fileName.toLowerCase().indexOf(FileType.PDF.getExtension()) > -1 || fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1 || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1) { // only tiffs and RSP file is expected if (isGSTool && (fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1 || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1)) { respStr = "Only PDF files expected with GhostScript tool."; break; } final MultipartFile multipartFile = multiPartRequest.getFile(fileName); instream = multipartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } else { respStr = "Files other than tiff, tif and pdf formats are provided."; break; } } if (respStr.isEmpty()) { for (final String fileName : fileMap.keySet()) { final File file = new File(workingDir + File.separator + fileName); if (isGSTool) { logger.info( "Start spliting multipage file using ghost script for file :" + fileName); imService.convertPdfToSinglePageTiffsUsingGSAPI(inputParams, file, outputParams, new File(outputDir + File.separator + fileName), threadList); } else { logger.info( "Start spliting multipage file using image magick for file :" + fileName); imService.convertPdfOrMultiPageTiffToTiffUsingIM(inputParams, file, outputParams, new File(outputDir + File.separator + fileName), threadList); } } try { logger.info("Executing batch instance thread using thread pool"); threadList.execute(); } catch (final DCMAApplicationException e) { threadList.remove(); FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); throw new Exception(e.getMessage(), e); } ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Unable to process web service request.Please check you ghostscipt or imagemagick configuration."; } finally { if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } } catch (Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/createMultiPageFile", method = RequestMethod.POST) @ResponseBody/*from w w w. java 2s . c o m*/ public void createMultiPageFile(final HttpServletRequest req, final HttpServletResponse resp) { logger.info("Start processing web service for createMultiPageFile."); String respStr = WebServiceUtil.EMPTY_STRING; String workingDir = WebServiceUtil.EMPTY_STRING; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); String xmlFileName = WebServiceUtil.EMPTY_STRING; List<File> fileList = new ArrayList<File>(); for (final String fileName : fileMap.keySet()) { if (fileName.endsWith(FileType.XML.getExtensionWithDot()) || fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) { final File file = new File(workingDir + File.separator + fileName); if (fileName.endsWith(FileType.XML.getExtensionWithDot())) { xmlFileName = fileName; } else { fileList.add(file); } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } else { respStr = "Expected only tif, tiff files."; } } if (respStr.isEmpty()) { final File xmlFile = new File(workingDir + File.separator + xmlFileName); final FileInputStream inputStream = new FileInputStream(xmlFile); Source source = XMLUtil.createSourceFromStream(inputStream); final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template() .getJaxb2Marshaller().unmarshal(source); if (webServiceParams.getParams() == null || webServiceParams.getParams().getParam() == null || webServiceParams.getParams().getParam().isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results."; } else { List<Param> paramList = webServiceParams.getParams().getParam(); String imageProcessingAPI = WebServiceUtil.EMPTY_STRING; String pdfOptimizationParams = WebServiceUtil.EMPTY_STRING; String multipageTifSwitch = WebServiceUtil.EMPTY_STRING; String pdfOptimizationSwitch = WebServiceUtil.EMPTY_STRING, ghostscriptPdfParameters = WebServiceUtil.EMPTY_STRING; for (final Param param : paramList) { if (param.getName().equalsIgnoreCase("imageProcessingAPI")) { imageProcessingAPI = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("pdfOptimizationParams")) { pdfOptimizationParams = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("multipageTifSwitch")) { multipageTifSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("pdfOptimizationSwitch")) { pdfOptimizationSwitch = param.getValue(); continue; } if (param.getName().equalsIgnoreCase("ghostscriptPdfParameters")) { ghostscriptPdfParameters = param.getValue(); continue; } } String results = WebServiceUtil.validateCreateMultiPageFile(ghostscriptPdfParameters, imageProcessingAPI, pdfOptimizationSwitch, multipageTifSwitch, pdfOptimizationParams); if (!results.isEmpty()) { respStr = results; } else { imService.createMultiPageFilesAPI(ghostscriptPdfParameters, pdfOptimizationParams, multipageTifSwitch, imageProcessingAPI, pdfOptimizationSwitch, workingDir, outputDir, fileList, new File(workingDir).getName() + Math.random()); ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { respStr = "Unable to process web service request.Please try again." + e; } finally { if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } } } catch (final XmlMappingException xmle) { respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is " + xmle; } catch (final DCMAException dcmae) { respStr = "Error in processing request. Detailed exception is " + dcmae; } catch (final Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } if (!respStr.isEmpty()) { try { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/extractFuzzyDB", method = RequestMethod.POST) @ResponseBody//from w ww. j a v a2s.c o m public void extractFuzzyDB(final HttpServletRequest req, final HttpServletResponse resp) { logger.info("Start processing web service for extract fuzzy DB for given HOCR file"); String respStr = ""; String workingDir = ""; Documents documents = null; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); String htmlFile = WebServiceUtil.EMPTY_STRING; if (fileMap.size() == 1) { for (final String fileName : fileMap.keySet()) { if (fileName.endsWith(FileType.HTML.getExtensionWithDot())) { htmlFile = fileName; } else { respStr = "Invalid file. Please passed the valid html file"; break; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } } else { respStr = "Invalid number of files. We are supposed only one file"; } String batchClassIdentifier = WebServiceUtil.EMPTY_STRING; String documentType = WebServiceUtil.EMPTY_STRING; String hocrFileName = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("documentType")) { documentType = multiPartRequest.getParameter(paramName); logger.info("Value for documentType parameter is " + documentType); continue; } if (paramName.equalsIgnoreCase("batchClassIdentifier")) { batchClassIdentifier = multiPartRequest.getParameter(paramName); logger.info("Value for batchClassIdentifier parameter is " + batchClassIdentifier); continue; } if (paramName.equalsIgnoreCase("hocrFile")) { hocrFileName = multiPartRequest.getParameter(paramName); logger.info("Value for hocrFile parameter is " + hocrFileName); continue; } } if (!hocrFileName.equalsIgnoreCase(htmlFile)) { respStr = "Please passed the valid hocr File"; } String results = WebServiceUtil.validateExtractFuzzyDBAPI(workingDir, hocrFileName, batchClassIdentifier, documentType); BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier); if (batchClass == null) { respStr = "Please enter valid batch class identifier"; } else { BatchPlugin fuzzyDBPlugin = batchClassPPService.getPluginProperties(batchClassIdentifier, "FUZZYDB"); if (fuzzyDBPlugin == null) { respStr = "Fuzzy DB plugin is not configured for batch class : " + batchClassIdentifier + " . Please select proper batch class"; } else if (fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_STOP_WORDS) == null || fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MIN_TERM_FREQ) == null || fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MIN_WORD_LENGTH) == null || fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_MAX_QUERY_TERMS) == null || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_NO_OF_PAGES) == null || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_DRIVER) == null || fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_CONNECTION_URL) == null || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_USER_NAME) == null || fuzzyDBPlugin.getPluginConfigurations(FuzzyDBProperties.FUZZYDB_DB_PASSWORD) == null || fuzzyDBPlugin .getPluginConfigurations(FuzzyDBProperties.FUZZYDB_THRESHOLD_VALUE) == null) { respStr = "Incomplete properties of the Fuzzy DB plugin for the specified batch class id."; } } List<com.ephesoft.dcma.da.domain.FieldType> allFdTypes = fieldTypeService .getFdTypeByDocTypeNameForBatchClass(documentType, batchClassIdentifier); if (allFdTypes == null) { respStr = "Please enter valid document type"; } if (!results.isEmpty()) { respStr = results; } else { try { HocrPages hocrPages = new HocrPages(); List<HocrPage> hocrPageList = hocrPages.getHocrPage(); HocrPage hocrPage = new HocrPage(); String pageID = "PG0"; hocrPage.setPageID(pageID); hocrPageList.add(hocrPage); bsService.hocrGenerationAPI(workingDir, pageID, workingDir + File.separator + hocrFileName, hocrPage); documents = fuzzyDBSearchService.extractDataBaseFields(batchClassIdentifier, documentType, hocrPages); } catch (final DCMAException e) { respStr = "Exception while extracting field using fuzzy db" + e; } } if (documents != null) { File outputxmlFile = new File(outputDir + File.separator + "OutputXML.xml"); FileOutputStream stream = new FileOutputStream(outputxmlFile); StreamResult result = new StreamResult(stream); batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(documents, result); ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error in creating output zip file.Please try again." + e.getMessage()); } finally { if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } catch (final XmlMappingException xmle) { respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is " + xmle; } catch (final DCMAException dcmae) { respStr = "Error in processing request. Detailed exception is " + dcmae; } catch (final Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } if (!respStr.isEmpty()) { try { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java
@RequestMapping(value = "/convertTiffToPdf", method = RequestMethod.POST) @ResponseBody/*w w w .java2s. c o m*/ public void convertTiffToPdf(final HttpServletRequest req, final HttpServletResponse resp) { logger.info("Start processing web service for extract fuzzy DB for given HOCR file"); String respStr = ""; String workingDir = ""; if (req instanceof DefaultMultipartHttpServletRequest) { try { final String webServiceFolderPath = bsService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); InputStream instream = null; OutputStream outStream = null; final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req; final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap(); if (!fileMap.keySet().isEmpty()) { for (final String fileName : fileMap.keySet()) { if (fileName.endsWith(FileType.TIF.getExtensionWithDot()) || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) { } else { respStr = "Invalid file. Please passed the valid tif/tiff file"; break; } final MultipartFile multiPartFile = multiPartRequest.getFile(fileName); instream = multiPartFile.getInputStream(); final File file = new File(workingDir + File.separator + fileName); outStream = new FileOutputStream(file); final byte[] buf = new byte[WebServiceUtil.bufferSize]; int len; while ((len = instream.read(buf)) > 0) { outStream.write(buf, 0, len); } if (instream != null) { instream.close(); } if (outStream != null) { outStream.close(); } } } else { respStr = "Please passed the input files for processing"; } if (respStr.isEmpty()) { String inputParams = WebServiceUtil.EMPTY_STRING; String outputParams = WebServiceUtil.EMPTY_STRING; String pdfGeneratorEngine = WebServiceUtil.EMPTY_STRING; for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params .hasMoreElements();) { final String paramName = params.nextElement(); if (paramName.equalsIgnoreCase("inputParams")) { inputParams = multiPartRequest.getParameter(paramName); logger.info("Value for batchClassIdentifier parameter is " + inputParams); continue; } if (paramName.equalsIgnoreCase("outputParams")) { outputParams = multiPartRequest.getParameter(paramName); logger.info("Value for hocrFile parameter is " + outputParams); continue; } if (paramName.equalsIgnoreCase("pdfGeneratorEngine")) { pdfGeneratorEngine = multiPartRequest.getParameter(paramName); logger.info("Value for hocrFile parameter is " + pdfGeneratorEngine); continue; } } respStr = WebServiceUtil.validateConvertTiffToPdfAPI(pdfGeneratorEngine, inputParams, outputParams); if (respStr.isEmpty()) { Set<String> outputFileList = new HashSet<String>(); File file = new File(workingDir); String[] fileList = file.list(new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot())); BatchInstanceThread batchInstanceThread = new BatchInstanceThread(workingDir); for (String inputFile : fileList) { String[] fileArray = new String[2]; String outputFile = inputFile.substring(0, inputFile.lastIndexOf(WebServiceUtil.DOT)) + FileType.PDF.getExtensionWithDot(); fileArray[0] = workingDir + File.separator + inputFile; fileArray[1] = workingDir + File.separator + outputFile; outputFileList.add(outputFile); imService.createTifToPDF(pdfGeneratorEngine, fileArray, batchInstanceThread, inputParams, outputParams); } batchInstanceThread.execute(); for (String outputFile : outputFileList) { FileUtils.copyFile(new File(workingDir + File.separator + outputFile), new File(outputDir + File.separator + outputFile)); } ServletOutputStream out = null; ZipOutputStream zout = null; final String zipFileName = WebServiceUtil.serverOutputFolderName; resp.setContentType("application/x-zip\r\n"); resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n"); try { out = resp.getOutputStream(); zout = new ZipOutputStream(out); FileUtils.zipDirectory(outputDir, zout, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error in creating output zip file.Please try again." + e.getMessage()); } finally { if (zout != null) { zout.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } } catch (final XmlMappingException xmle) { respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is " + xmle; } catch (final DCMAException dcmae) { respStr = "Error in processing request. Detailed exception is " + dcmae; } catch (final Exception e) { respStr = "Internal Server error.Please check logs for further details." + e; if (!workingDir.isEmpty()) { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); } } } else { respStr = "Improper input to server. Expected multipart request. Returning without processing the results."; } if (!respStr.isEmpty()) { try { FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr); } catch (final IOException ioe) { } } }
From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.java
@Override public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { StringBuffer sb = new StringBuffer(); if (idsToExport != null && idsToExport.size() > 0) { for (Long long1 : idsToExport) { if (sb.length() > 0) { sb.append(", "); }//from ww w. ja v a 2 s . c o m sb.append(long1); } } String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]"; String fileName = "Rendicontazioni.zip"; try { this.log.info("Esecuzione " + methodName + " in corso..."); int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport(); FrBD frBD = new FrBD(bd); boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID); FrFilter filter = frBD.newFilter(simpleSearch); // se ho ricevuto anche gli id li utilizzo per fare il check della count if (idsToExport != null && idsToExport.size() > 0) filter.setIdFr(idsToExport); //1. eseguo una count per verificare che il numero dei risultati da esportare sia <= sogliamassimaexport massivo boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, frBD, simpleSearch, filter); if (!eseguiRicerca) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.operazioneNonPermessa")); throw new ExportException(msg, EsitoOperazione.ERRORE); } long count = frBD.countExt(filter); if (count < 1) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare")); throw new ExportException(msg, EsitoOperazione.ERRORE); } if (count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima")); throw new ExportException(msg, EsitoOperazione.ERRORE); } filter.setOffset(0); filter.setLimit(limit); FilterSortWrapper fsw = new FilterSortWrapper(); fsw.setField(it.govpay.orm.FR.model().DATA_ORA_FLUSSO); fsw.setSortOrder(SortOrder.DESC); filter.getFilterSortList().add(fsw); List<Fr> findAllExt = frBD.findAllExt(filter); for (Fr fr : findAllExt) { String folderName = "Rendicontazione_" + fr.getIur(); ZipEntry frXml = new ZipEntry(folderName + "/fr.xml"); zout.putNextEntry(frXml); zout.write(fr.getXml()); 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); } }