List of usage examples for java.util.zip ZipOutputStream write
public void write(int b) throws IOException
From source file:com.portfolio.rest.RestServicePortfolio.java
@Path("/portfolios/portfolio/{portfolio-id}") @GET/* ww w . j av a2 s . co m*/ @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip", MediaType.APPLICATION_OCTET_STREAM }) public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token, @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId, @QueryParam("group") Integer group, @QueryParam("resources") String resource, @QueryParam("files") String files, @QueryParam("export") String export, @QueryParam("lang") String lang) { UserInfo ui = checkCredential(httpServletRequest, user, token, null); Response response = null; try { String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0, this.label, resource, "", ui.subId).toString(); if ("faux".equals(portfolio)) { response = Response.status(403).build(); } if (response == null) { Date time = new Date(); Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer()); NodeList codes = doc.getDocumentElement().getElementsByTagName("code"); // Le premier c'est celui du root Node codenode = codes.item(0); String code = ""; if (codenode != null) code = codenode.getTextContent(); if (export != null) { response = Response.ok(portfolio).header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".xml\"").build(); } else if (resource != null && files != null) { //// Cas du renvoi d'un ZIP /// Temp file in temp directory File tempDir = new File(System.getProperty("java.io.tmpdir", null)); File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir); FileOutputStream fos = new FileOutputStream(tempZip); ZipOutputStream zos = new ZipOutputStream(fos); // BufferedOutputStream bos = new BufferedOutputStream(zos); /// zos.setComment("Some comment"); /// Write xml file to zip ZipEntry ze = new ZipEntry(portfolioUuid + ".xml"); zos.putNextEntry(ze); byte[] bytes = portfolio.getBytes("UTF-8"); zos.write(bytes); zos.closeEntry(); /// Find all fileid/filename XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource/fileid"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); /// Direct link to data // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs"; /* String langatt = ""; if( lang != null ) langatt = "?lang="+lang; else langatt = "?lang=fr"; //*/ /// Fetch all files for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node p = res.getParentNode(); // resource -> container Node gp = p.getParentNode(); // container -> context Node uuidNode = gp.getAttributes().getNamedItem("id"); String uuid = uuidNode.getTextContent(); String filterName = "./filename[@lang and text()]"; NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p, XPathConstants.NODESET); String filename = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); filename = fileNode.getTextContent(); lang = fileNode.getAttribute("lang"); if ("".equals(lang)) lang = "fr"; } String servlet = httpServletRequest.getRequestURI(); servlet = servlet.substring(0, servlet.indexOf("/", 7)); String server = httpServletRequest.getServerName(); int port = httpServletRequest.getServerPort(); // "http://"+ server + /resources/resource/file/ uuid ? lang= size= // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs"; String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid + "?lang=" + lang; HttpGet get = new HttpGet(url); // Transfer sessionid so that local request still get security checked HttpSession session = httpServletRequest.getSession(true); get.addHeader("Cookie", "JSESSIONID=" + session.getId()); // Send request CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse ret = client.execute(get); HttpEntity entity = ret.getEntity(); // Put specific name for later recovery if ("".equals(filename)) continue; int lastDot = filename.lastIndexOf("."); if (lastDot < 0) lastDot = 0; String filenameext = filename.substring(0); /// find extension int extindex = filenameext.lastIndexOf("."); filenameext = uuid + "_" + lang + filenameext.substring(extindex); // Save it to zip file // int length = (int) entity.getContentLength(); InputStream content = entity.getContent(); // BufferedInputStream bis = new BufferedInputStream(entity.getContent()); ze = new ZipEntry(filenameext); try { int totalread = 0; zos.putNextEntry(ze); int inByte; byte[] buf = new byte[4096]; // zos.write(bytes,0,inByte); while ((inByte = content.read(buf)) != -1) { totalread += inByte; zos.write(buf, 0, inByte); } System.out.println("FILE: " + filenameext + " -> " + totalread); content.close(); // bis.close(); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } EntityUtils.consume(entity); ret.close(); client.close(); } zos.close(); fos.close(); /// Return zip file RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r"); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip") .build(); // Temp file cleanup tempZip.delete(); } else { //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; }; // String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString(); if (portfolio.equals("faux")) { throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires"); } if (accept.equals(MediaType.APPLICATION_JSON)) { portfolio = XML.toJSONObject(portfolio).toString(); response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build(); } else response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build(); logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode()); } } } catch (RestWebApplicationException ex) { throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString()); } catch (SQLException ex) { logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found", Status.NOT_FOUND.getStatusCode()); throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found"); } catch (Exception ex) { ex.printStackTrace(); logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(), Status.INTERNAL_SERVER_ERROR.getStatusCode()); throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { if (dataProvider != null) dataProvider.disconnect(); } return response; }
From source file:it.govpay.web.rs.dars.reportistica.pagamenti.PagamentiHandler.java
@Override public String esporta(List<Long> idsToExport, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException { StringBuffer sb = new StringBuffer(); if (idsToExport != null && idsToExport.size() > 0) { for (Long long1 : idsToExport) { if (sb.length() > 0) { sb.append(", "); }// w w w . jav a 2 s.c o m sb.append(long1); } } Printer printer = null; String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]"; int numeroZipEntries = 0; if (idsToExport.size() == 1) { return this.esporta(idsToExport.get(0), uriInfo, bd, zout); } String fileName = "Pagamenti.zip"; try { this.log.info("Esecuzione " + methodName + " in corso..."); Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); ProfiloOperatore profilo = operatore.getProfilo(); boolean isAdmin = profilo.equals(ProfiloOperatore.ADMIN); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); EstrattoContoFilter filter = estrattiContoBD.newFilter(); boolean eseguiRicerca = true; List<Long> ids = idsToExport; 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 && estrattiContoBD.count(filter) > 0; } } if (eseguiRicerca) { Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>(); Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>(); // recupero oggetto filter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? estrattiContoBD.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(); } for (Long idSingoloVersamento : idsToExport) { SingoloVersamento singoloVersamento = singoliVersamentiBD .getSingoloVersamento(idSingoloVersamento); Versamento versamento = singoloVersamento.getVersamento(bd); // Prelevo il dominio UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Aggrego i versamenti per dominio per generare gli estratti conto List<Long> idSingoliVersamentiDominio = null; if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) { idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio()); } else { idSingoliVersamentiDominio = new ArrayList<Long>(); mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio); mappaInputDomini.put(dominio.getCodDominio(), dominio); } idSingoliVersamentiDominio.add(idSingoloVersamento); } List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); for (String codDominio : mappaInputEstrattoConto.keySet()) { it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio), mappaInputEstrattoConto.get(codDominio)); listInputEstrattoConto.add(input); } String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto( bd); 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(nomeEntry); // ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + 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(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 . ja va 2 s . co m sb.append(long1); } } Printer printer = null; String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]"; if (idsToExport == null || idsToExport.size() == 0) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.erroreSelezioneVuota")); throw new ExportException(msg, EsitoOperazione.ERRORE); } int numeroZipEntries = 0; if (idsToExport.size() == 1) { return this.esporta(idsToExport.get(0), rawValues, uriInfo, bd, zout); } String fileName = "Pagamenti.zip"; try { this.log.info("Esecuzione " + methodName + " in corso..."); // Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); EstrattoContoFilter filter = estrattiContoBD.newFilter(); boolean eseguiRicerca = true; List<Long> ids = idsToExport; // 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 && estrattiContoBD.count(filter) > 0; // } // } if (eseguiRicerca) { Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>(); Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>(); // recupero oggetto filter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? estrattiContoBD.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(); } for (Long idSingoloVersamento : idsToExport) { SingoloVersamento singoloVersamento = singoliVersamentiBD .getSingoloVersamento(idSingoloVersamento); Versamento versamento = singoloVersamento.getVersamento(bd); // Prelevo il dominio UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Aggrego i versamenti per dominio per generare gli estratti conto List<Long> idSingoliVersamentiDominio = null; if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) { idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio()); } else { idSingoliVersamentiDominio = new ArrayList<Long>(); mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio); mappaInputDomini.put(dominio.getCodDominio(), dominio); } idSingoliVersamentiDominio.add(idSingoloVersamento); } List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); for (String codDominio : mappaInputEstrattoConto.keySet()) { it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio), mappaInputEstrattoConto.get(codDominio)); listInputEstrattoConto.add(input); } String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto( bd); 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(nomeEntry); // ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + 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:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java
private void zipMultipleFiles(HttpServletRequest req, HttpServletResponse res, VDCUser user, VDC vdc, UserGroup ipUserGroup) {//from www . j a v a 2 s.com // a request for a zip-packaged multiple file archive. String fileId = req.getParameter("fileId"); String studyId = req.getParameter("studyId"); String versionNumber = req.getParameter("versionNumber"); System.out.print("zip multiple files version number" + versionNumber); Study study = null; Collection files = new ArrayList(); boolean createDirectoriesForCategories = false; String fileManifest = ""; String sessionId = null; javax.servlet.http.Cookie cookies[] = req.getCookies(); for (int i = 0; i < cookies.length; i++) { if ("JSESSIONID".equals(cookies[i].getName())) { sessionId = cookies[i].getValue(); } } if (sessionId == null || "".equals(sessionId)) { // if there's no JSESSIONID, we'll use the vdcSession id, for // logging the download counts: String[] stringArray = vdcSession.toString().toString().split("@"); sessionId = stringArray[1]; } if (fileId != null) { String[] idTokens = fileId.split(","); for (String tok : idTokens) { StudyFile sf; try { sf = studyFileService.getStudyFile(new Long(tok)); files.add(sf); } catch (Exception ex) { fileManifest = fileManifest + tok + " DOES NOT APPEAR TO BE A VALID FILE ID;\r\n"; } } } else if (studyId != null) { try { study = studyService.getStudy(new Long(studyId)); files = study.getStudyFiles(); createDirectoriesForCategories = true; } catch (Exception ex) { if (ex.getCause() instanceof IllegalArgumentException) { createErrorResponse404(res); return; } } } else { createErrorResponse404(res); return; } // check for restricted files Iterator iter = files.iterator(); while (iter.hasNext()) { StudyFile file = (StudyFile) iter.next(); if (file.isFileRestrictedForUser(user, ipUserGroup)) { fileManifest = fileManifest + file.getFileName() + " IS RESTRICTED AND CANNOT BE DOWNLOADED\r\n"; iter.remove(); } } if (files.size() == 0) { createErrorResponse403(res); return; } Long sizeLimit = Long.valueOf(104857600); // that's the default of 100 MB. Long sizeTotal = Long.valueOf(0); // this is the total limit of the size of all the files we // are packaging. if exceeded, we stop packaging files and add // a note to the manifest explaining what happened. // the value above is the default. a different value can // be set with a JVM option. String sizeLimitOption = System.getProperty("dvn.batchdownload.limit"); if (sizeLimitOption != null) { Long sizeOptionValue = new Long(sizeLimitOption); if (sizeOptionValue > 0) { sizeLimit = sizeOptionValue; } } FileDownloadObject remoteDownload = null; // now create zip stream try { // set content type: res.setContentType("application/zip"); // create zipped output stream: OutputStream out = res.getOutputStream(); ZipOutputStream zout = new ZipOutputStream(out); List nameList = new ArrayList(); // used to check for duplicates List successList = new ArrayList(); iter = files.iterator(); while (iter.hasNext()) { int fileSize = 0; StudyFile file = (StudyFile) iter.next(); if (sizeTotal < sizeLimit) { InputStream in = null; String varHeaderLine = null; String dbContentType = file.getFileType(); if (dbContentType != null && dbContentType.equals("text/tab-separated-values") && file.isSubsettable()) { List datavariables = ((TabularDataFile) file).getDataTable().getDataVariables(); varHeaderLine = generateVariableHeader(datavariables); } if (dbContentType == null) { dbContentType = "unknown filetype;"; } Boolean Success = true; if (file.isRemote()) { // do the http magic; // remote files may be subject to complex authentication and // authorization. // And for that we have a special method... remoteDownload = initiateRemoteDownload(file, req); if (remoteDownload.getStatus() != 200) { fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") COULD NOT be downloaded because an I/O error has occured. \r\n"; if (remoteDownload.getInputStream() != null) { remoteDownload.getInputStream().close(); } remoteDownload.releaseConnection(); Success = false; } else { in = remoteDownload.getInputStream(); } } else { in = getLocalFileAsStream(file); if (in == null) { fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") COULD NOT be downloaded because an I/O error has occured. \r\n"; Success = false; } } if (Success) { // String zipEntryName = file.getFileName(); // get file name and category according to study version number chosen by user Long versionNum = null; if (versionNumber != null) versionNum = Long.valueOf(versionNumber).longValue(); String zipEntryName = file.getFileName(versionNum); zipEntryName = checkZipEntryName(zipEntryName, nameList); // ZipEntry e = new ZipEntry(zipEntryName); String zipEntryDirectoryName = file.getCategory(versionNum); ZipEntry e = new ZipEntry(zipEntryDirectoryName + "/" + zipEntryName); zout.putNextEntry(e); if (varHeaderLine != null) { byte[] headerBuffer = varHeaderLine.getBytes(); zout.write(headerBuffer); fileSize += (headerBuffer.length); } byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = in.read(dataBuffer)) > 0) { zout.write(dataBuffer, 0, i); fileSize += i; out.flush(); } in.close(); zout.closeEntry(); if (dbContentType == null) { dbContentType = "unknown filetype;"; } fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") " + fileSize + " bytes.\r\n"; if (fileSize > 0) { successList.add(file.getId()); sizeTotal += Long.valueOf(fileSize); } // if this was a remote stream, let's close // the connection properly: if (remoteDownload != null) { remoteDownload.releaseConnection(); } } } else { fileManifest = fileManifest + file.getFileName() + " skipped because the total size of the download bundle exceeded the limit of " + sizeLimit + " bytes.\r\n"; } } // finally, let's create the manifest entry: ZipEntry e = new ZipEntry("MANIFEST.TXT"); zout.putNextEntry(e); zout.write(fileManifest.getBytes()); zout.closeEntry(); zout.close(); // and finally finally, we can now increment the download // counts on all the files successfully zipped: Iterator it = successList.iterator(); while (it.hasNext()) { Long fid = (Long) it.next(); StudyFile file = studyFileService.getStudyFile(new Long(fid)); Long versionNum = null; if (versionNumber != null) versionNum = Long.valueOf(versionNumber).longValue(); System.out.print("versionNumber " + versionNumber); StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNum); GuestBookResponse guestbookResponse = (GuestBookResponse) vdcSession.getGuestbookResponseMap() .get("guestBookResponse_" + file.getStudy().getId()); if (guestbookResponse == null) { //need to set up dummy network response guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(file.getStudy(), file, vdcSession.getLoginBean()); } guestbookResponse.setStudyVersion(sv); guestbookResponse.setSessionId(sessionId); String friendlyFormatType = FileUtil.getUserFriendlyTypeForMime(file.getFileType()); guestbookResponse.setDownloadtype("File Download (as Zip archive) - " + friendlyFormatType); if (vdc != null) { studyService.incrementNumberOfDownloads(fid, vdc.getId(), (GuestBookResponse) guestbookResponse); } else { studyService.incrementNumberOfDownloads(fid, (Long) null, (GuestBookResponse) guestbookResponse); } } } catch (IOException ex) { // if we caught an exception *here*, it means something // catastrophic has happened while packaging the zip archive // itself (I/O errors on individual files would be caught // above); so there's not much we can do except print a // generic error message: String errorMessage = "An unknown I/O error has occured while generating a Zip archive of multiple data files. Unfortunately, no further diagnostic information on the nature of the problem is avaiable to the Application at this point. It is possible that the problem was caused by a temporary network error. Please try again later and if the problem persists, report it to your DVN technical support contact."; createErrorResponse403(res); if (remoteDownload != null) { remoteDownload.releaseConnection(); } } }
From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.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 va 2 s .c om*/ sb.append(long1); } } Printer printer = null; String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]"; int numeroZipEntries = 0; String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); // if(idsToExport.size() == 1) { // return this.esporta(idsToExport.get(0), uriInfo, bd, zout); // } String fileName = "Export.zip"; try { this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport(); boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID); VersamentiBD versamentiBD = new VersamentiBD(bd); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd); Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>(); Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>(); VersamentoFilter filter = versamentiBD.newFilter(simpleSearch); // se ho ricevuto anche gli id li utilizzo per fare il check della count if (idsToExport != null && idsToExport.size() > 0) filter.setIdVersamento(idsToExport); boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, bd, 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 = versamentiBD.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 (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.Versamento.model().DATA_ORA_ULTIMO_AGGIORNAMENTO); fsw.setSortOrder(SortOrder.DESC); filter.getFilterSortList().add(fsw); List<Versamento> findAll = versamentiBD.findAll(filter); for (Versamento versamento : findAll) { // Prelevo il dominio UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Aggrego i versamenti per dominio per generare gli estratti conto List<Long> idVersamentiDominio = null; if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) { idVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio()); } else { idVersamentiDominio = new ArrayList<Long>(); mappaInputEstrattoConto.put(dominio.getCodDominio(), idVersamentiDominio); mappaInputDomini.put(dominio.getCodDominio(), dominio); } idVersamentiDominio.add(versamento.getId()); } List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); for (String codDominio : mappaInputEstrattoConto.keySet()) { it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoVersamentiPDF(mappaInputDomini.get(codDominio), mappaInputEstrattoConto.get(codDominio)); listInputEstrattoConto.add(input); } 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 EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); EstrattoContoFilter ecFilter = estrattiContoBD.newFilter(); ecFilter.setIdVersamento(idsToExport); List<EstrattoConto> findAllEstrattoConto = estrattiContoBD.estrattoContoFromIdVersamenti(ecFilter); if (findAllEstrattoConto != null && findAllEstrattoConto.size() > 0) { //ordinamento record Collections.sort(findAllEstrattoConto, 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 : findAllEstrattoConto) { 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.monitoraggio.pagamenti.PagamentiHandler.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 w ww. j a va2 s. c om*/ int numeroZipEntries = 0; boolean esportaCsv = false, esportaPdf = false, esportaRtPdf = false, esportaRtBase64 = false; try { String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); String fileName = "Pagamenti.zip"; this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); String esportaCsvId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaCsv.id"); String esportaCsvS = Utils.getValue(rawValues, esportaCsvId); if (StringUtils.isNotEmpty(esportaCsvS)) { esportaCsv = Boolean.parseBoolean(esportaCsvS); } String esportaPdfId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaPdf.id"); String esportaPdfS = Utils.getValue(rawValues, esportaPdfId); if (StringUtils.isNotEmpty(esportaPdfS)) { esportaPdf = Boolean.parseBoolean(esportaPdfS); } String esportaRtPdfId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtPdf.id"); String esportaRtPdfS = Utils.getValue(rawValues, esportaRtPdfId); if (StringUtils.isNotEmpty(esportaRtPdfS)) { esportaRtPdf = Boolean.parseBoolean(esportaRtPdfS); } String esportaRtBase64Id = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtBase64.id"); String esportaRtBase64S = Utils.getValue(rawValues, esportaRtBase64Id); if (StringUtils.isNotEmpty(esportaRtBase64S)) { esportaRtBase64 = Boolean.parseBoolean(esportaRtBase64S); } // almeno una voce deve essere selezionata if (!(esportaCsv || esportaPdf || esportaRtPdf || esportaRtBase64)) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.tipiExportObbligatori")); throw new ExportException(msg, EsitoOperazione.ERRORE); } Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita); boolean eseguiRicerca = !setDomini.isEmpty(); it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd); PagamentiBD pagamentiBD = new PagamentiBD(bd); PagamentoFilter filter = pagamentiBD.newFilter(); filter.setSogliaRitardo(ConsoleProperties.getInstance().getSogliaGiorniRitardoPagamenti()); List<String> idDomini = new ArrayList<String>(); List<Long> idsToExport = new ArrayList<Long>(); idsToExport.add(idToExport); if (!setDomini.contains(-1L)) { List<Long> lstCodDomini = new ArrayList<Long>(); lstCodDomini.addAll(setDomini); idDomini.addAll(this.toListCodDomini(lstCodDomini, bd)); filter.setIdDomini(idDomini); // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi. if (eseguiRicerca) { filter.setIdPagamenti(idsToExport); eseguiRicerca = eseguiRicerca && pagamentiBD.count(filter) > 0; } } if (eseguiRicerca) { Pagamento pagamento = pagamentiBD.getPagamento(idToExport); if (esportaRtPdf || esportaRtBase64) { // ricevuta pagamento try { Rpt rpt = pagamento.getRpt(bd); Dominio dominio = pagamento.getDominio(bd); if (rpt.getXmlRt() != null) { String ricevutaFileName = dominio.getCodDominio() + "_" + pagamento.getIuv() + "_" + pagamento.getIur(); if (esportaRtPdf) { Versamento versamento = rpt.getVersamento(bd); // RT in formato pdf String tipoFirma = rpt.getFirmaRichiesta().getCodifica(); byte[] rtByteValidato = RtUtils.validaFirma(tipoFirma, rpt.getXmlRt(), dominio.getCodDominio()); CtRicevutaTelematica rt = JaxbUtils.toRT(rtByteValidato); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String auxDigit = dominio.getAuxDigit() + ""; String applicationCode = String.format("%02d", dominio.getStazione(bd).getApplicationCode()); RicevutaPagamentoUtils.getPdfRicevutaPagamento(dominio.getLogo(), versamento.getCausaleVersamento(), rt, pagamento, auxDigit, applicationCode, baos, this.log); String rtPdfEntryName = ricevutaFileName + ".pdf"; numeroZipEntries++; ZipEntry rtPdf = new ZipEntry(rtPdfEntryName); zout.putNextEntry(rtPdf); zout.write(baos.toByteArray()); zout.closeEntry(); } if (esportaRtBase64) { // RT in formato Base 64 String rtBase64EntryName = ricevutaFileName + ".txt"; numeroZipEntries++; ZipEntry rtPdf = new ZipEntry(rtBase64EntryName); zout.putNextEntry(rtPdf); zout.write(rpt.getXmlRt()); zout.closeEntry(); } } } catch (Exception e) { } } List<Long> ids = new ArrayList<Long>(); if (pagamento.getIdSingoloVersamento() != null) ids.add(pagamento.getIdSingoloVersamento()); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); EstrattoContoFilter ecFilter = estrattiContoBD.newFilter(); if (esportaCsv) { // recupero oggetto ecFilter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(ecFilter) : 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 eConto : findAll) { printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(eConto, 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(); } } if (esportaPdf) { SingoloVersamento singoloVersamento = singoliVersamentiBD .getSingoloVersamento(pagamento.getIdSingoloVersamento()); 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); 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.PagamentiHandler.java
@Override public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { Printer printer = null;//from w w w . j a va 2 s . c om String methodName = "exportMassivo " + this.titoloServizio; int numeroZipEntries = 0; boolean esportaCsv = false, esportaPdf = false, esportaRtPdf = false, esportaRtBase64 = false; String fileName = "Pagamenti.zip"; try { String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi(); this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport(); boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID); PagamentiBD pagamentiBD = new PagamentiBD(bd); PagamentoFilter filter = pagamentiBD.newFilter(simpleSearch); Map<String, String> params = new HashMap<String, String>(); String esportaCsvId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaCsv.id"); String esportaCsvS = Utils.getValue(rawValues, esportaCsvId); if (StringUtils.isNotEmpty(esportaCsvS)) { esportaCsv = Boolean.parseBoolean(esportaCsvS); } String esportaPdfId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaPdf.id"); String esportaPdfS = Utils.getValue(rawValues, esportaPdfId); if (StringUtils.isNotEmpty(esportaPdfS)) { esportaPdf = Boolean.parseBoolean(esportaPdfS); } String esportaRtPdfId = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtPdf.id"); String esportaRtPdfS = Utils.getValue(rawValues, esportaRtPdfId); if (StringUtils.isNotEmpty(esportaRtPdfS)) { esportaRtPdf = Boolean.parseBoolean(esportaRtPdfS); } String esportaRtBase64Id = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtBase64.id"); String esportaRtBase64S = Utils.getValue(rawValues, esportaRtBase64Id); if (StringUtils.isNotEmpty(esportaRtBase64S)) { esportaRtBase64 = Boolean.parseBoolean(esportaRtBase64S); } // almeno una voce deve essere selezionata if (!(esportaCsv || esportaPdf || esportaRtPdf || esportaRtBase64)) { List<String> msg = new ArrayList<String>(); msg.add(Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esporta.tipiExportObbligatori")); throw new ExportException(msg, EsitoOperazione.ERRORE); } // se ho ricevuto anche gli id li utilizzo per fare il check della count if (idsToExport != null && idsToExport.size() > 0) filter.setIdPagamenti(idsToExport); //1. eseguo una count per verificare che il numero dei risultati da esportare sia <= sogliamassimaexport massivo boolean eseguiRicerca = this.popolaFiltroPagamenti(rawValues, uriInfo, pagamentiBD, params, 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 = pagamentiBD.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 (esportaRtPdf && 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); } FilterSortWrapper fsw = new FilterSortWrapper(); fsw.setField(it.govpay.orm.Pagamento.model().DATA_PAGAMENTO); fsw.setSortOrder(SortOrder.DESC); filter.getFilterSortList().add(fsw); List<Pagamento> findAllPag = new ArrayList<Pagamento>(); int countIterazione = -1; int offset = 0; // esecuzione della ricerca di tutti i pagamenti paginata per problemi di performance, nel caso di esporta rt pdf c'e' il limit impostato e si fa solo un ciclo do { filter.setOffset(offset); filter.setLimit(limit); List<Pagamento> findAllPagTmp = pagamentiBD.findAll(filter); countIterazione = findAllPagTmp != null ? findAllPagTmp.size() : 0; offset += countIterazione; if (findAllPagTmp != null && findAllPagTmp.size() > 0) findAllPag.addAll(findAllPagTmp); } while (countIterazione > 0 && !esportaRtPdf); List<Long> ids = new ArrayList<Long>(); for (Pagamento pagamento : findAllPag) { if (pagamento.getIdSingoloVersamento() != null) ids.add(pagamento.getIdSingoloVersamento()); if (esportaRtPdf || esportaRtBase64) { // ricevuta pagamento try { Rpt rpt = pagamento.getRpt(bd); Dominio dominio = pagamento.getDominio(bd); if (rpt.getXmlRt() != null) { numeroZipEntries++; String ricevutaFileName = dominio.getCodDominio() + "_" + pagamento.getIuv() + "_" + pagamento.getIur(); if (esportaRtPdf) { Versamento versamento = rpt.getVersamento(bd); // RT in formato pdf String tipoFirma = rpt.getFirmaRichiesta().getCodifica(); byte[] rtByteValidato = RtUtils.validaFirma(tipoFirma, rpt.getXmlRt(), dominio.getCodDominio()); CtRicevutaTelematica rt = JaxbUtils.toRT(rtByteValidato); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String auxDigit = dominio.getAuxDigit() + ""; String applicationCode = String.format("%02d", dominio.getStazione(bd).getApplicationCode()); RicevutaPagamentoUtils.getPdfRicevutaPagamento(dominio.getLogo(), versamento.getCausaleVersamento(), rt, pagamento, auxDigit, applicationCode, baos, this.log); String rtPdfEntryName = ricevutaFileName + ".pdf"; numeroZipEntries++; ZipEntry rtPdf = new ZipEntry(rtPdfEntryName); zout.putNextEntry(rtPdf); zout.write(baos.toByteArray()); zout.closeEntry(); } if (esportaRtBase64) { // RT in formato Base 64 String rtBase64EntryName = ricevutaFileName + ".txt"; numeroZipEntries++; ZipEntry rtPdf = new ZipEntry(rtBase64EntryName); zout.putNextEntry(rtPdf); zout.write(rpt.getXmlRt()); zout.closeEntry(); } } } catch (Exception e) { } } } if (esportaCsv) { EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd); EstrattoContoFilter ecFilter = estrattiContoBD.newFilter(); // recupero oggetto ecFilter.setIdSingoloVersamento(ids); List<EstrattoConto> findAll = eseguiRicerca ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(ecFilter) : 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(); } } if (esportaPdf) { Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>(); Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>(); SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd); for (Long idSingoloVersamento : ids) { SingoloVersamento singoloVersamento = singoliVersamentiBD .getSingoloVersamento(idSingoloVersamento); Versamento versamento = singoloVersamento.getVersamento(bd); // Prelevo il dominio UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo()); Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio()); // Aggrego i versamenti per dominio per generare gli estratti conto List<Long> idSingoliVersamentiDominio = null; if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) { idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio()); } else { idSingoliVersamentiDominio = new ArrayList<Long>(); mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio); mappaInputDomini.put(dominio.getCodDominio(), dominio); } idSingoliVersamentiDominio.add(idSingoloVersamento); } List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>(); for (String codDominio : mappaInputEstrattoConto.keySet()) { it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio), mappaInputEstrattoConto.get(codDominio)); listInputEstrattoConto.add(input); } it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto( bd); 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(nomeEntry); // ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + 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 (ExportException e) { throw e; } catch (Exception e) { this.log.error(e.getMessage(), e); throw new ConsoleException(e); } }
From source file:com.portfolio.data.provider.MysqlAdminProvider.java
@Override public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label, String resource, String files) throws Exception { String rootNodeUuid = getPortfolioRootNode(portfolioUuid); String header = ""; String footer = ""; NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ); if (!nodeRight.read) return "faux"; if (outMimeType.getSubType().equals("xml")) { // header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>"; // footer = "</portfolio>"; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; Document document = null; try {// w w w. j a va 2 s. c o m documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); document.setXmlStandalone(true); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root = document.createElement("portfolio"); root.setAttribute("id", portfolioUuid); root.setAttribute("code", "0"); //// Noeuds supplmentaire pour WAD // Version Element verNode = document.createElement("version"); Text version = document.createTextNode("3"); verNode.appendChild(version); root.appendChild(verNode); // metadata-wad Element metawad = document.createElement("metadata-wad"); metawad.setAttribute("prog", "main.jsp"); metawad.setAttribute("owner", "N"); root.appendChild(metawad); // root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); // root.setAttribute("schemaVersion", "1.0"); document.appendChild(root); getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId); StringWriter stw = new StringWriter(); Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.transform(new DOMSource(document), new StreamResult(stw)); if (resource != null && files != null) { if (resource.equals("true") && files.equals("true")) { String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date() + ".xml"; String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date() + ".zip"; File file = null; PrintWriter ecrire; PrintWriter ecri; try { file = new File(adressedufichier); ecrire = new PrintWriter(new FileOutputStream(adressedufichier)); ecrire.println(stw.toString()); ecrire.flush(); ecrire.close(); System.out.print("fichier cree "); } catch (IOException ioe) { System.out.print("Erreur : "); ioe.printStackTrace(); } try { String fileName = portfolioUuid + ".zip"; ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip)); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(Deflater.BEST_COMPRESSION); File dataDirectories = new File(file.getName()); FileInputStream fis = new FileInputStream(dataDirectories); byte[] bytes = new byte[fis.available()]; fis.read(bytes); ZipEntry entry = new ZipEntry(file.getName()); entry.setTime(dataDirectories.lastModified()); zip.putNextEntry(entry); zip.write(bytes); zip.closeEntry(); fis.close(); //zipDirectory(dataDirectories, zip); zip.close(); file.delete(); return adresseduzip; } catch (FileNotFoundException fileNotFound) { fileNotFound.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } } } return stw.toString(); } else if (outMimeType.getSubType().equals("json")) { header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\","; footer = "}}"; } return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer; }
From source file:com.portfolio.data.provider.MysqlDataProvider.java
@Override public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label, String resource, String files, int substid) throws Exception { String rootNodeUuid = getPortfolioRootNode(portfolioUuid); String header = ""; String footer = ""; NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ); if (!nodeRight.read) { userId = credential.getPublicUid(); // NodeRight nodeRight = new NodeRight(false,false,false,false,false,false); /// Vrifie les droits avec le compte publique (dernire chance) nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy"); if (!nodeRight.read) return "faux"; }//from w w w . j a v a 2 s. c o m if (outMimeType.getSubType().equals("xml")) { // header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>"; // footer = "</portfolio>"; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; Document document = null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); document.setXmlStandalone(true); } catch (ParserConfigurationException e) { e.printStackTrace(); } Element root = document.createElement("portfolio"); root.setAttribute("id", portfolioUuid); root.setAttribute("code", "0"); //// Noeuds supplmentaire pour WAD // Version Element verNode = document.createElement("version"); Text version = document.createTextNode("4"); verNode.appendChild(version); root.appendChild(verNode); // metadata-wad // Element metawad = document.createElement("metadata-wad"); // metawad.setAttribute("prog", "main.jsp"); // metawad.setAttribute("owner", "N"); // root.appendChild(metawad); int owner = credential.getOwner(userId, portfolioUuid); String isOwner = "N"; if (owner == userId) isOwner = "Y"; root.setAttribute("owner", isOwner); // root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); // root.setAttribute("schemaVersion", "1.0"); document.appendChild(root); getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId, nodeRight.groupLabel); StringWriter stw = new StringWriter(); Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.transform(new DOMSource(document), new StreamResult(stw)); if (resource != null && files != null) { if (resource.equals("true") && files.equals("true")) { String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date() + ".xml"; String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date() + ".zip"; File file = null; PrintWriter ecrire; try { file = new File(adressedufichier); ecrire = new PrintWriter(new FileOutputStream(adressedufichier)); ecrire.println(stw.toString()); ecrire.flush(); ecrire.close(); System.out.print("fichier cree "); } catch (IOException ioe) { System.out.print("Erreur : "); ioe.printStackTrace(); } try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip)); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(Deflater.BEST_COMPRESSION); File dataDirectories = new File(file.getName()); FileInputStream fis = new FileInputStream(dataDirectories); byte[] bytes = new byte[fis.available()]; fis.read(bytes); ZipEntry entry = new ZipEntry(file.getName()); entry.setTime(dataDirectories.lastModified()); zip.putNextEntry(entry); zip.write(bytes); zip.closeEntry(); fis.close(); //zipDirectory(dataDirectories, zip); zip.close(); file.delete(); return adresseduzip; } catch (FileNotFoundException fileNotFound) { fileNotFound.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } } } return stw.toString(); } else if (outMimeType.getSubType().equals("json")) { header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\","; footer = "}}"; } return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer; }
From source file:com.globalsight.webservices.Ambassador.java
private void compressionXml(String zipFileName, File inputFile) { try {/*from w ww . j a va 2s .c o m*/ ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.putNextEntry(new ZipEntry(inputFile.getName())); FileInputStream inputStream = new FileInputStream(inputFile); int b; while ((b = inputStream.read()) != -1) { out.write(b); } inputStream.close(); inputFile.delete(); out.close(); } catch (Exception e) { e.printStackTrace(); } }