List of usage examples for java.util.zip ZipOutputStream flush
public void flush() throws IOException
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 www . j a va 2 s .c o m 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.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(", "); }/* w w w .j ava2 s . c om*/ 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: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 ww w . j av a 2s.c o m 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:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java
protected void zipGroupSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, Assignment.SubmissionType typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, String gradeFileFormat, boolean includeNotSubmitted) { ZipOutputStream out = null; try {/*from w w w . j a v a2s. c o m*/ out = new ZipOutputStream(outputStream); // create the folder structure - named after the assignment's title final String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR; final SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase()); final SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeTypeString, getCsvSeparator()); if (!submissions.hasNext()) { exceptionMessage.append("There is no submission yet. "); } // Write the header sheet.addHeader(resourceLoader.getString("group"), resourceLoader.getString("grades.eid"), resourceLoader.getString("grades.members"), resourceLoader.getString("grades.grade"), resourceLoader.getString("grades.submissionTime"), resourceLoader.getString("grades.late")); // allow add assignment members allowAddSubmissionUsers(assignmentReference); // Create the ZIP file String caughtException = null; String caughtStackTrace = null; while (submissions.hasNext()) { final AssignmentSubmission s = (AssignmentSubmission) submissions.next(); log.debug(this + " ZIPGROUP " + (s == null ? "null" : s.getId())); //SAK-29314 added a new value where it's by default submitted but is marked when the user submits if ((s.getSubmitted() && s.getUserSubmission()) || includeNotSubmitted) { try { final StringBuilder submittersName = new StringBuilder(root); final User[] submitters = s.getSubmitters().stream().map(p -> { try { return userDirectoryService.getUser(p.getSubmitter()); } catch (UserNotDefinedException e) { log.warn("User not found {}", p.getSubmitter()); return null; } }).filter(Objects::nonNull).toArray(User[]::new); final String groupTitle = siteService.getSite(s.getAssignment().getContext()) .getGroup(s.getGroupId()).getTitle(); final StringBuilder submittersString = new StringBuilder(); final StringBuilder submitters2String = new StringBuilder(); for (int i = 0; i < submitters.length; i++) { if (i > 0) { submittersString.append("; "); submitters2String.append("; "); } String fullName = submitters[i].getSortName(); // in case the user doesn't have first name or last name if (fullName.indexOf(",") == -1) { fullName = fullName.concat(","); } submittersString.append(fullName); submitters2String.append(submitters[i].getDisplayName()); // add the eid to the end of it to guarantee folder name uniqness submittersString.append("(" + submitters[i].getEid() + ")"); } final String latenessStatus = whenSubmissionMade(s); final String gradeDisplay = getGradeDisplay(s.getGrade(), s.getAssignment().getTypeOfGrade(), s.getAssignment().getScaleFactor()); //Adding the row sheet.addRow(groupTitle, s.getGroupId(), submitters2String.toString(), gradeDisplay, s.getDateSubmitted() != null ? s.getDateSubmitted().toString() : StringUtils.EMPTY, latenessStatus); if (StringUtils.trimToNull(groupTitle) != null) { submittersName.append(StringUtils.trimToNull(groupTitle)).append(" (") .append(s.getGroupId()).append(")"); final String submittedText = s.getSubmittedText(); submittersName.append("/"); // record submission timestamp if (s.getSubmitted() && s.getDateSubmitted() != null) { createTextZipEntry(out, submittersName + "timestamp.txt", s.getDateSubmitted().toString()); } // create the folder structure - named after the submitter's name if (typeOfSubmission != Assignment.SubmissionType.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission text if (withStudentSubmissionText) { // create the text file only when a text submission is allowed final String zipEntryName = submittersName + groupTitle + "_submissionText" + AssignmentConstants.ZIP_SUBMITTED_TEXT_FILE_TYPE; createTextZipEntry(out, zipEntryName, submittedText); } // include student submission feedback text if (withFeedbackText) { // create a feedbackText file into zip createTextZipEntry(out, submittersName + "feedbackText.html", s.getFeedbackText()); } } if (typeOfSubmission != Assignment.SubmissionType.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION && withStudentSubmissionAttachment) { // include student submission attachment // create a attachment folder for the submission attachments final String sSubAttachmentFolder = submittersName + resourceLoader.getString("stuviewsubm.submissatt") + "/"; final ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder); out.putNextEntry(sSubAttachmentFolderEntry); // add all submission attachment into the submission attachment folder zipAttachments(out, submittersName.toString(), sSubAttachmentFolder, s.getAttachments()); out.closeEntry(); } if (withFeedbackComment) { // the comments.txt file to show instructor's comments final String zipEntryName = submittersName + "comments" + AssignmentConstants.ZIP_COMMENT_FILE_TYPE; final String textEntryString = formattedText.encodeUnicode(s.getFeedbackComment()); createTextZipEntry(out, zipEntryName, textEntryString); } if (withFeedbackAttachment) { // create an attachment folder for the feedback attachments final String feedbackSubAttachmentFolder = submittersName + resourceLoader.getString("download.feedback.attachment") + "/"; final ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry( feedbackSubAttachmentFolder); out.putNextEntry(feedbackSubAttachmentFolderEntry); // add all feedback attachment folder zipAttachments(out, submittersName.toString(), feedbackSubAttachmentFolder, s.getFeedbackAttachments()); out.closeEntry(); } if (!submittersString.toString().trim().isEmpty()) { // the comments.txt file to show instructor's comments final String zipEntryName = submittersName + "members" + AssignmentConstants.ZIP_COMMENT_FILE_TYPE; final String textEntryString = formattedText .encodeUnicode(submittersString.toString()); createTextZipEntry(out, zipEntryName, textEntryString); } } // if } catch (Exception e) { caughtException = e.toString(); if (log.isDebugEnabled()) { caughtStackTrace = ExceptionUtils.getStackTrace(e); } break; } } // if the user is still in site } // while -- there is submission if (caughtException == null) { // continue if (withGradeFile) { final ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension()); out.putNextEntry(gradesCSVEntry); sheet.write(out); out.closeEntry(); } } else { // log the error exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n"); if (log.isDebugEnabled()) { exceptionMessage.append(caughtStackTrace); } } } catch (IOException e) { exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n"); } finally { // Complete the ZIP file if (out != null) { try { out.finish(); out.flush(); } catch (IOException e) { // tried } try { out.close(); } catch (IOException e) { // tried } } } }
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 ww w. j ava 2 s. co m 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:org.pentaho.di.job.entries.zipfile.JobEntryZipFile.java
public boolean processRowFile(Job parentJob, Result result, String realZipfilename, String realWildcard, String realWildcardExclude, String realSourceDirectoryOrFile, String realMovetodirectory, boolean createparentfolder) { boolean Fileexists = false; File tempFile = null;//from w w w .jav a 2s.com File fileZip = null; boolean resultat = false; boolean renameOk = false; boolean orginExist = false; // Check if target file/folder exists! FileObject originFile = null; ZipInputStream zin = null; byte[] buffer = null; OutputStream dest = null; BufferedOutputStream buff = null; ZipOutputStream out = null; ZipEntry entry = null; String localSourceFilename = realSourceDirectoryOrFile; try { originFile = KettleVFS.getFileObject(realSourceDirectoryOrFile, this); localSourceFilename = KettleVFS.getFilename(originFile); orginExist = originFile.exists(); } catch (Exception e) { // Ignore errors } finally { if (originFile != null) { try { originFile.close(); } catch (IOException ex) { logError("Error closing file '" + originFile.toString() + "'", ex); } } } String localrealZipfilename = realZipfilename; if (realZipfilename != null && orginExist) { FileObject fileObject = null; try { fileObject = KettleVFS.getFileObject(localrealZipfilename, this); localrealZipfilename = KettleVFS.getFilename(fileObject); // Check if Zip File exists if (fileObject.exists()) { Fileexists = true; if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileExists1.Label") + localrealZipfilename + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileExists2.Label")); } } // Let's see if we need to create parent folder of destination zip filename if (createparentfolder) { createParentFolder(localrealZipfilename); } // Let's start the process now if (ifZipFileExists == 3 && Fileexists) { // the zip file exists and user want to Fail resultat = false; } else if (ifZipFileExists == 2 && Fileexists) { // the zip file exists and user want to do nothing if (addFileToResult) { // Add file to result files name ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } resultat = true; } else if (afterZip == 2 && realMovetodirectory == null) { // After Zip, Move files..User must give a destination Folder resultat = false; logError( BaseMessages.getString(PKG, "JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label")); } else { // After Zip, Move files..User must give a destination Folder // Let's see if we deal with file or folder FileObject[] fileList = null; FileObject sourceFileOrFolder = KettleVFS.getFileObject(localSourceFilename); boolean isSourceDirectory = sourceFileOrFolder.getType().equals(FileType.FOLDER); final Pattern pattern; final Pattern patternexclude; if (isSourceDirectory) { // Let's prepare the pattern matcher for performance reasons. // We only do this if the target is a folder ! // if (!Const.isEmpty(realWildcard)) { pattern = Pattern.compile(realWildcard); } else { pattern = null; } if (!Const.isEmpty(realWildcardExclude)) { patternexclude = Pattern.compile(realWildcardExclude); } else { patternexclude = null; } // Target is a directory // Get all the files in the directory... // if (includingSubFolders) { fileList = sourceFileOrFolder.findFiles(new FileSelector() { public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception { return true; } public boolean includeFile(FileSelectInfo fileInfo) throws Exception { boolean include; // Only include files in the sub-folders... // When we include sub-folders we match the whole filename, not just the base-name // if (fileInfo.getFile().getType().equals(FileType.FILE)) { include = true; if (pattern != null) { String name = fileInfo.getFile().getName().getPath(); include = pattern.matcher(name).matches(); } if (include && patternexclude != null) { String name = fileInfo.getFile().getName().getPath(); include = !pattern.matcher(name).matches(); } } else { include = false; } return include; } }); } else { fileList = sourceFileOrFolder.getChildren(); } } else { pattern = null; patternexclude = null; // Target is a file fileList = new FileObject[] { sourceFileOrFolder }; } if (fileList.length == 0) { resultat = false; logError(BaseMessages.getString(PKG, "JobZipFiles.Log.FolderIsEmpty", localSourceFilename)); } else if (!checkContainsFile(localSourceFilename, fileList, isSourceDirectory)) { resultat = false; logError(BaseMessages.getString(PKG, "JobZipFiles.Log.NoFilesInFolder", localSourceFilename)); } else { if (ifZipFileExists == 0 && Fileexists) { // the zip file exists and user want to create new one with unique name // Format Date // do we have already a .zip at the end? if (localrealZipfilename.toLowerCase().endsWith(".zip")) { // strip this off localrealZipfilename = localrealZipfilename.substring(0, localrealZipfilename.length() - 4); } localrealZipfilename += "_" + StringUtil.getFormattedDateTimeNow(true) + ".zip"; if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileNameChange1.Label") + localrealZipfilename + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileNameChange1.Label")); } } else if (ifZipFileExists == 1 && Fileexists) { // the zip file exists and user want to append // get a temp file fileZip = getFile(localrealZipfilename); tempFile = File.createTempFile(fileZip.getName(), null); // delete it, otherwise we cannot rename existing zip to it. tempFile.delete(); renameOk = fileZip.renameTo(tempFile); if (!renameOk) { logError(BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp1.Label") + fileZip.getAbsolutePath() + BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp2.Label") + tempFile.getAbsolutePath() + BaseMessages.getString(PKG, "JobZipFiles.Cant_Rename_Temp3.Label")); } if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.Zip_FileAppend1.Label") + localrealZipfilename + BaseMessages.getString(PKG, "JobZipFiles.Zip_FileAppend2.Label")); } } if (log.isDetailed()) { logDetailed( BaseMessages.getString(PKG, "JobZipFiles.Files_Found1.Label") + fileList.length + BaseMessages.getString(PKG, "JobZipFiles.Files_Found2.Label") + localSourceFilename + BaseMessages.getString(PKG, "JobZipFiles.Files_Found3.Label")); } // Prepare Zip File buffer = new byte[18024]; dest = KettleVFS.getOutputStream(localrealZipfilename, false); buff = new BufferedOutputStream(dest); out = new ZipOutputStream(buff); HashSet<String> fileSet = new HashSet<String>(); if (renameOk) { // User want to append files to existing Zip file // The idea is to rename the existing zip file to a temporary file // and then adds all entries in the existing zip along with the new files, // excluding the zip entries that have the same name as one of the new files. zin = new ZipInputStream(new FileInputStream(tempFile)); entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); if (!fileSet.contains(name)) { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file int len; while ((len = zin.read(buffer)) > 0) { out.write(buffer, 0, len); } fileSet.add(name); } entry = zin.getNextEntry(); } // Close the streams zin.close(); } // 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...) FileObject[] zippedFiles = new FileObject[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! // ..only if target is a folder ! if (isSourceDirectory) { // If we include sub-folders, we match on the whole name, not just the basename // String filename; if (includingSubFolders) { filename = fileList[i].getName().getPath(); } else { filename = fileList[i].getName().getBaseName(); } if (pattern != null) { // Matches the base name of the file (backward compatible!) // Matcher matcher = pattern.matcher(filename); getIt = matcher.matches(); } if (patternexclude != null) { Matcher matcherexclude = patternexclude.matcher(filename); getItexclude = matcherexclude.matches(); } } // Get processing File String targetFilename = KettleVFS.getFilename(fileList[i]); if (sourceFileOrFolder.getType().equals(FileType.FILE)) { targetFilename = localSourceFilename; } FileObject file = KettleVFS.getFileObject(targetFilename); boolean isTargetDirectory = file.exists() && file.getType().equals(FileType.FOLDER); if (getIt && !getItexclude && !isTargetDirectory && !fileSet.contains(targetFilename)) { // We can add the file to the Zip Archive if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip1.Label") + fileList[i] + BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip2.Label") + localSourceFilename + BaseMessages.getString(PKG, "JobZipFiles.Add_FilesToZip3.Label")); } // Associate a file input stream for the current file InputStream in = KettleVFS.getInputStream(file); // Add ZIP entry to output stream. // String relativeName; String fullName = fileList[i].getName().getPath(); String basePath = sourceFileOrFolder.getName().getPath(); if (isSourceDirectory) { if (fullName.startsWith(basePath)) { relativeName = fullName.substring(basePath.length() + 1); } else { relativeName = fullName; } } else if (isFromPrevious) { int depth = determineDepth(environmentSubstitute(storedSourcePathDepth)); relativeName = determineZipfilenameForDepth(fullName, depth); } else { relativeName = fileList[i].getName().getBaseName(); } out.putNextEntry(new ZipEntry(relativeName)); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); 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(); buff.close(); dest.close(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobZipFiles.Log.TotalZippedFiles", "" + zippedFiles.length)); } // Delete Temp File if (tempFile != null) { tempFile.delete(); } // -----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, Move File FileObject fileObjectd = zippedFiles[i]; if (!isSourceDirectory) { fileObjectd = KettleVFS.getFileObject(localSourceFilename); } // Here we can move, delete files if (afterZip == 1) { // Delete File boolean deleted = fileObjectd.delete(); if (!deleted) { resultat = false; logError(BaseMessages.getString(PKG, "JobZipFiles.Cant_Delete_File1.Label") + localSourceFilename + Const.FILE_SEPARATOR + zippedFiles[i] + BaseMessages .getString(PKG, "JobZipFiles.Cant_Delete_File2.Label")); } // File deleted if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.File_Deleted1.Label") + localSourceFilename + Const.FILE_SEPARATOR + zippedFiles[i] + BaseMessages.getString(PKG, "JobZipFiles.File_Deleted2.Label")); } } else if (afterZip == 2) { // Move File FileObject fileObjectm = null; try { fileObjectm = KettleVFS.getFileObject(realMovetodirectory + Const.FILE_SEPARATOR + fileObjectd.getName().getBaseName()); fileObjectd.moveTo(fileObjectm); } catch (IOException e) { logError( BaseMessages.getString(PKG, "JobZipFiles.Cant_Move_File1.Label") + zippedFiles[i] + BaseMessages.getString(PKG, "JobZipFiles.Cant_Move_File2.Label") + e.getMessage()); resultat = false; } finally { try { if (fileObjectm != null) { fileObjectm.close(); } } catch (Exception e) { if (fileObjectm != null) { logError("Error closing file '" + fileObjectm.toString() + "'", e); } } } // File moved if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "JobZipFiles.File_Moved1.Label") + zippedFiles[i] + BaseMessages.getString(PKG, "JobZipFiles.File_Moved2.Label")); } } } } } if (addFileToResult) { // Add file to result files name ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, parentJob.getJobname(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } resultat = true; } } } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobZipFiles.Cant_CreateZipFile1.Label") + localrealZipfilename + BaseMessages.getString(PKG, "JobZipFiles.Cant_CreateZipFile2.Label"), e); resultat = false; } finally { if (fileObject != null) { try { fileObject.close(); fileObject = null; } catch (IOException ex) { logError("Error closing file '" + fileObject.toString() + "'", ex); } } try { if (out != null) { out.close(); } if (buff != null) { buff.close(); } if (dest != null) { dest.close(); } if (zin != null) { zin.close(); } if (entry != null) { entry = null; } } catch (IOException ex) { logError("Error closing zip file entry for file '" + originFile.toString() + "'", ex); } } } else { resultat = true; if (localrealZipfilename == null) { logError(BaseMessages.getString(PKG, "JobZipFiles.No_ZipFile_Defined.Label")); } if (!orginExist) { logError(BaseMessages.getString(PKG, "JobZipFiles.No_FolderCible_Defined.Label", localSourceFilename)); } } // return a verifier return resultat; }
From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java
protected void zipGroupSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, String gradeFileFormat, boolean includeNotSubmitted) { ZipOutputStream out = null; try {/*from ww w . ja v a2s . c o m*/ out = new ZipOutputStream(outputStream); // create the folder structure - named after the assignment's title String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR; SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase()); SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeTypeString); String submittedText = ""; if (!submissions.hasNext()) { exceptionMessage.append("There is no submission yet. "); } // Write the header sheet.addHeader("Group", rb.getString("grades.eid"), rb.getString("grades.members"), rb.getString("grades.grade"), rb.getString("grades.submissionTime"), rb.getString("grades.late")); // allow add assignment members List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference); // Create the ZIP file String submittersName = ""; String caughtException = null; String caughtStackTrace = null; while (submissions.hasNext()) { GroupSubmission gs = (GroupSubmission) submissions.next(); AssignmentSubmission s = gs.getSubmission(); M_log.debug(this + " ZIPGROUP " + (s == null ? "null" : s.getId())); //SAK-29314 added a new value where it's by default submitted but is marked when the user submits if ((s.getSubmitted() && s.isUserSubmission()) || includeNotSubmitted) { try { submittersName = root; User[] submitters = s.getSubmitters(); String submitterString = gs.getGroup().getTitle() + " (" + gs.getGroup().getId() + ")"; String submittersString = ""; String submitters2String = ""; for (int i = 0; i < submitters.length; i++) { if (i > 0) { submittersString = submittersString.concat("; "); submitters2String = submitters2String.concat("; "); } String fullName = submitters[i].getSortName(); // in case the user doesn't have first name or last name if (fullName.indexOf(",") == -1) { fullName = fullName.concat(","); } submittersString = submittersString.concat(fullName); submitters2String = submitters2String.concat(submitters[i].getDisplayName()); // add the eid to the end of it to guarantee folder name uniqness submittersString = submittersString + "(" + submitters[i].getEid() + ")"; } String latenessStatus = whenSubmissionMade(s); //Adding the row sheet.addRow(gs.getGroup().getTitle(), gs.getGroup().getId(), submitters2String, s.getGradeDisplay(), s.getTimeSubmittedString(), latenessStatus); if (StringUtil.trimToNull(submitterString) != null) { submittersName = submittersName.concat(StringUtil.trimToNull(submitterString)); submittedText = s.getSubmittedText(); submittersName = submittersName.concat("/"); // record submission timestamp if (s.getSubmitted() && s.getTimeSubmitted() != null) { ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt"); out.putNextEntry(textEntry); byte[] b = (s.getTimeSubmitted().toString()).getBytes(); out.write(b); textEntry.setSize(b.length); out.closeEntry(); } // create the folder structure - named after the submitter's name if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission text if (withStudentSubmissionText) { // create the text file only when a text submission is allowed ZipEntry textEntry = new ZipEntry(submittersName + submitterString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE); out.putNextEntry(textEntry); byte[] text = submittedText.getBytes(); out.write(text); textEntry.setSize(text.length); out.closeEntry(); } // include student submission feedback text if (withFeedbackText) { // create a feedbackText file into zip ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html"); out.putNextEntry(fTextEntry); byte[] fText = s.getFeedbackText().getBytes(); out.write(fText); fTextEntry.setSize(fText.length); out.closeEntry(); } } if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission attachment if (withStudentSubmissionAttachment) { // create a attachment folder for the submission attachments String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/"; ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder); out.putNextEntry(sSubAttachmentFolderEntry); // add all submission attachment into the submission attachment folder zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments()); out.closeEntry(); } } if (withFeedbackComment) { // the comments.txt file to show instructor's comments ZipEntry textEntry = new ZipEntry( submittersName + "comments" + ZIP_COMMENT_FILE_TYPE); out.putNextEntry(textEntry); byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes(); out.write(b); textEntry.setSize(b.length); out.closeEntry(); } if (withFeedbackAttachment) { // create an attachment folder for the feedback attachments String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment") + "/"; ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry( feedbackSubAttachmentFolder); out.putNextEntry(feedbackSubAttachmentFolderEntry); // add all feedback attachment folder zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments()); out.closeEntry(); } if (submittersString.trim().length() > 0) { // the comments.txt file to show instructor's comments ZipEntry textEntry = new ZipEntry( submittersName + "members" + ZIP_COMMENT_FILE_TYPE); out.putNextEntry(textEntry); byte[] b = FormattedText.encodeUnicode(submittersString).getBytes(); out.write(b); textEntry.setSize(b.length); out.closeEntry(); } } // if } catch (Exception e) { caughtException = e.toString(); if (M_log.isDebugEnabled()) { caughtStackTrace = ExceptionUtils.getStackTrace(e); } break; } } // if the user is still in site } // while -- there is submission if (caughtException == null) { // continue if (withGradeFile) { ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension()); out.putNextEntry(gradesCSVEntry); sheet.write(out); out.closeEntry(); } } else { // log the error exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n"); if (M_log.isDebugEnabled()) { exceptionMessage.append(caughtStackTrace); } } } catch (IOException e) { exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n"); } finally { // Complete the ZIP file if (out != null) { try { out.finish(); out.flush(); } catch (IOException e) { // tried } try { out.close(); } catch (IOException e) { // tried } } } }
From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java
private void zipSubmissions(String assignmentReference, String assignmentTitle, Assignment.GradeType gradeType, Assignment.SubmissionType typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, boolean withoutFolders, String gradeFileFormat, boolean includeNotSubmitted, String siteId) { ZipOutputStream out = null; boolean isAdditionalNotesEnabled = false; Site st = null;/*from w w w .ja v a 2s .com*/ try { st = siteService.getSite(siteId); isAdditionalNotesEnabled = candidateDetailProvider != null && candidateDetailProvider.isAdditionalNotesEnabled(st); } catch (IdUnusedException e) { log.warn("Could not find site {} - isAdditionalNotesEnabled set to false", siteId); } try { out = new ZipOutputStream(outputStream); // create the folder structure - named after the assignment's title final String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR; final SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase()); final SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeType.toString(), getCsvSeparator()); String submittedText = ""; if (!submissions.hasNext()) { exceptionMessage.append("There is no submission yet. "); } if (isAdditionalNotesEnabled) { sheet.addHeader(resourceLoader.getString("grades.id"), resourceLoader.getString("grades.eid"), resourceLoader.getString("grades.lastname"), resourceLoader.getString("grades.firstname"), resourceLoader.getString("grades.grade"), resourceLoader.getString("grades.submissionTime"), resourceLoader.getString("grades.late"), resourceLoader.getString("gen.notes")); } else { sheet.addHeader(resourceLoader.getString("grades.id"), resourceLoader.getString("grades.eid"), resourceLoader.getString("grades.lastname"), resourceLoader.getString("grades.firstname"), resourceLoader.getString("grades.grade"), resourceLoader.getString("grades.submissionTime"), resourceLoader.getString("grades.late")); } // allow add assignment members final List<User> allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference); // Create the ZIP file String caughtException = null; String caughtStackTrace = null; final StringBuilder submittersAdditionalNotesHtml = new StringBuilder(); while (submissions.hasNext()) { final AssignmentSubmission s = (AssignmentSubmission) submissions.next(); boolean isAnon = assignmentUsesAnonymousGrading(s.getAssignment()); //SAK-29314 added a new value where it's by default submitted but is marked when the user submits if ((s.getSubmitted() && s.getUserSubmission()) || includeNotSubmitted) { // get the submitter who submitted the submission see if the user is still in site final Optional<AssignmentSubmissionSubmitter> assignmentSubmitter = s.getSubmitters().stream() .findAny(); try { User u = null; if (assignmentSubmitter.isPresent()) { u = userDirectoryService.getUser(assignmentSubmitter.get().getSubmitter()); } if (allowAddSubmissionUsers.contains(u)) { String submittersName = root; final User[] submitters = s.getSubmitters().stream().map(p -> { try { return userDirectoryService.getUser(p.getSubmitter()); } catch (UserNotDefinedException e) { log.warn("User not found {}, {}", p.getSubmitter(), e.getMessage()); } return null; }).filter(Objects::nonNull).toArray(User[]::new); String submittersString = ""; for (int i = 0; i < submitters.length; i++) { if (i > 0) { submittersString = submittersString.concat("; "); } String fullName = submitters[i].getSortName(); // in case the user doesn't have first name or last name if (!fullName.contains(",")) { fullName = fullName.concat(","); } submittersString = submittersString.concat(fullName); // add the eid to the end of it to guarantee folder name uniqness // if user Eid contains non ascii characters, the user internal id will be used final String userEid = submitters[i].getEid(); final String candidateEid = escapeInvalidCharsEntry(userEid); if (candidateEid.equals(userEid)) { submittersString = submittersString + "(" + candidateEid + ")"; } else { submittersString = submittersString + "(" + submitters[i].getId() + ")"; } submittersString = escapeInvalidCharsEntry(submittersString); // Work out if submission is late. final String latenessStatus = whenSubmissionMade(s); log.debug("latenessStatus: " + latenessStatus); final String anonTitle = resourceLoader.getString("grading.anonymous.title"); final String fullAnonId = s.getId() + " " + anonTitle; String[] params = new String[7]; if (isAdditionalNotesEnabled && candidateDetailProvider != null) { final List<String> notes = candidateDetailProvider .getAdditionalNotes(submitters[i], st).orElse(new ArrayList<String>()); if (!notes.isEmpty()) { params = new String[notes.size() + 7]; System.arraycopy(notes.toArray(new String[notes.size()]), 0, params, 7, notes.size()); } } // SAK-17606 if (!isAnon) { log.debug("Zip user: " + submitters[i].toString()); params[0] = submitters[i].getDisplayId(); params[1] = submitters[i].getEid(); params[2] = submitters[i].getLastName(); params[3] = submitters[i].getFirstName(); params[4] = this.getGradeForSubmitter(s, submitters[i].getId()); if (s.getDateSubmitted() != null) { params[5] = s.getDateSubmitted().toString(); // TODO may need to be formatted } else { params[5] = ""; } params[6] = latenessStatus; } else { params[0] = fullAnonId; params[1] = fullAnonId; params[2] = anonTitle; params[3] = anonTitle; params[4] = this.getGradeForSubmitter(s, submitters[i].getId()); if (s.getDateSubmitted() != null) { params[5] = s.getDateSubmitted().toString(); // TODO may need to be formatted } else { params[5] = ""; } params[6] = latenessStatus; } sheet.addRow(params); } if (StringUtils.trimToNull(submittersString) != null) { submittersName = submittersName.concat(StringUtils.trimToNull(submittersString)); submittedText = s.getSubmittedText(); // SAK-17606 if (isAnon) { submittersString = s.getId() + " " + resourceLoader.getString("grading.anonymous.title"); submittersName = root + submittersString; } if (!withoutFolders) { submittersName = submittersName.concat("/"); } else { submittersName = submittersName.concat("_"); } // record submission timestamp if (!withoutFolders && s.getSubmitted() && s.getDateSubmitted() != null) { final String zipEntryName = submittersName + "timestamp.txt"; final String textEntryString = s.getDateSubmitted().toString(); createTextZipEntry(out, zipEntryName, textEntryString); } // create the folder structure - named after the submitter's name if (typeOfSubmission != Assignment.SubmissionType.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission text if (withStudentSubmissionText) { // create the text file only when a text submission is allowed final StringBuilder submittersNameString = new StringBuilder( submittersName); //remove folder name if Download All is without user folders if (!withoutFolders) { submittersNameString.append(submittersString); } final String zipEntryName = submittersNameString .append("_submissionText" + AssignmentConstants.ZIP_SUBMITTED_TEXT_FILE_TYPE) .toString(); createTextZipEntry(out, zipEntryName, submittedText); } // include student submission feedback text if (withFeedbackText) { // create a feedbackText file into zip final String zipEntryName = submittersName + "feedbackText.html"; final String textEntryString = s.getFeedbackText(); createTextZipEntry(out, zipEntryName, textEntryString); } } if (typeOfSubmission != Assignment.SubmissionType.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION && withStudentSubmissionAttachment) { // include student submission attachment //remove "/" that creates a folder if Download All is without user folders String sSubAttachmentFolder = submittersName + resourceLoader.getString("stuviewsubm.submissatt");//jh + "/"; if (!withoutFolders) { // create a attachment folder for the submission attachments sSubAttachmentFolder = submittersName + resourceLoader.getString("stuviewsubm.submissatt") + "/"; sSubAttachmentFolder = escapeInvalidCharsEntry(sSubAttachmentFolder); final ZipEntry sSubAttachmentFolderEntry = new ZipEntry( sSubAttachmentFolder); out.putNextEntry(sSubAttachmentFolderEntry); } else { sSubAttachmentFolder += "_"; //submittersName = submittersName.concat("_"); } // add all submission attachment into the submission attachment folder zipAttachments(out, submittersName, sSubAttachmentFolder, s.getAttachments()); out.closeEntry(); } if (withFeedbackComment) { // the comments.txt file to show instructor's comments final String zipEntryName = submittersName + "comments" + AssignmentConstants.ZIP_COMMENT_FILE_TYPE; final String textEntryString = formattedText .encodeUnicode(s.getFeedbackComment()); createTextZipEntry(out, zipEntryName, textEntryString); } if (withFeedbackAttachment) { // create an attachment folder for the feedback attachments String feedbackSubAttachmentFolder = submittersName + resourceLoader.getString("download.feedback.attachment"); if (!withoutFolders) { feedbackSubAttachmentFolder += "/"; final ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry( feedbackSubAttachmentFolder); out.putNextEntry(feedbackSubAttachmentFolderEntry); } else { submittersName = submittersName.concat("_"); } // add all feedback attachment folder zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments()); out.closeEntry(); } } // if if (isAdditionalNotesEnabled && candidateDetailProvider != null) { final List<String> notes = candidateDetailProvider.getAdditionalNotes(u, st) .orElse(new ArrayList<String>()); if (!notes.isEmpty()) { final StringBuilder noteList = new StringBuilder("<ul>"); for (String note : notes) { noteList.append("<li>" + StringEscapeUtils.escapeHtml4(note) + "</li>"); } noteList.append("</ul>"); submittersAdditionalNotesHtml .append("<tr><td style='padding-right:10px;padding-left:10px'>" + submittersString + "</td><td style='padding-right:10px'>" + noteList + "</td></tr>"); } } } else { log.warn( "Can't add submission: {} to zip, missing the submittee or they are no longer allowed to submit in the site", s.getId()); } } catch (Exception e) { caughtException = e.toString(); if (log.isDebugEnabled()) { caughtStackTrace = ExceptionUtils.getStackTrace(e); } break; } } // if the user is still in site } // while -- there is submission if (caughtException == null) { // continue if (withGradeFile) { final ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension()); out.putNextEntry(gradesCSVEntry); sheet.write(out); out.closeEntry(); } if (isAdditionalNotesEnabled) { final ZipEntry additionalEntry = new ZipEntry( root + resourceLoader.getString("assignment.additional.notes.file.title") + ".html"); out.putNextEntry(additionalEntry); String htmlString = emailUtil.htmlPreamble("additionalnotes"); htmlString += "<h1>" + resourceLoader.getString("assignment.additional.notes.export.title") + "</h1>"; htmlString += "<div>" + resourceLoader.getString("assignment.additional.notes.export.header") + "</div><br/>"; htmlString += "<table border=\"1\" style=\"border-collapse:collapse;\"><tr><th>" + resourceLoader.getString("gen.student") + "</th><th>" + resourceLoader.getString("gen.notes") + "</th>" + submittersAdditionalNotesHtml + "</table>"; htmlString += "<br/><div>" + resourceLoader.getString("assignment.additional.notes.export.footer") + "</div>"; htmlString += emailUtil.htmlEnd(); log.debug("Additional information html: " + htmlString); final byte[] wes = htmlString.getBytes(); out.write(wes); additionalEntry.setSize(wes.length); out.closeEntry(); } } else { // log the error exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n"); if (log.isDebugEnabled()) { exceptionMessage.append(caughtStackTrace); } } } catch (IOException e) { exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n"); } finally { // Complete the ZIP file if (out != null) { try { out.finish(); out.flush(); } catch (IOException e) { // tried } try { out.close(); } catch (IOException e) { // tried } } } }
From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java
protected void zipSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString, int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage, boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment, boolean withoutFolders, String gradeFileFormat, boolean includeNotSubmitted) { ZipOutputStream out = null; try {//from ww w. j a v a2 s . c o m out = new ZipOutputStream(outputStream); // create the folder structure - named after the assignment's title String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle)) + Entity.SEPARATOR; SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase()); SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeTypeString); String submittedText = ""; if (!submissions.hasNext()) { exceptionMessage.append("There is no submission yet. "); } sheet.addHeader(rb.getString("grades.id"), rb.getString("grades.eid"), rb.getString("grades.lastname"), rb.getString("grades.firstname"), rb.getString("grades.grade"), rb.getString("grades.submissionTime"), rb.getString("grades.late")); // allow add assignment members List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference); // Create the ZIP file String submittersName = ""; String caughtException = null; String caughtStackTrace = null; while (submissions.hasNext()) { AssignmentSubmission s = (AssignmentSubmission) submissions.next(); boolean isAnon = assignmentUsesAnonymousGrading(s); //SAK-29314 added a new value where it's by default submitted but is marked when the user submits if ((s.getSubmitted() && s.isUserSubmission()) || includeNotSubmitted) { // get the submission user id and see if the user is still in site String userId = s.getSubmitterId(); try { User u = UserDirectoryService.getUser(userId); if (allowAddSubmissionUsers.contains(u)) { submittersName = root; User[] submitters = s.getSubmitters(); String submittersString = ""; for (int i = 0; i < submitters.length; i++) { if (i > 0) { submittersString = submittersString.concat("; "); } String fullName = submitters[i].getSortName(); // in case the user doesn't have first name or last name if (fullName.indexOf(",") == -1) { fullName = fullName.concat(","); } submittersString = submittersString.concat(fullName); // add the eid to the end of it to guarantee folder name uniqness // if user Eid contains non ascii characters, the user internal id will be used String userEid = submitters[i].getEid(); String candidateEid = escapeInvalidCharsEntry(userEid); if (candidateEid.equals(userEid)) { submittersString = submittersString + "(" + candidateEid + ")"; } else { submittersString = submittersString + "(" + submitters[i].getId() + ")"; } submittersString = escapeInvalidCharsEntry(submittersString); // Work out if submission is late. String latenessStatus = whenSubmissionMade(s); String fullAnonId = s.getAnonymousSubmissionId(); String anonTitle = rb.getString("grading.anonymous.title"); // SAK-17606 if (!isAnon) { sheet.addRow(submitters[i].getDisplayId(), submitters[i].getEid(), submitters[i].getLastName(), submitters[i].getFirstName(), s.getGradeDisplay(), s.getTimeSubmittedString(), latenessStatus); } else { sheet.addRow(fullAnonId, fullAnonId, anonTitle, anonTitle, s.getGradeDisplay(), s.getTimeSubmittedString(), latenessStatus); } } if (StringUtils.trimToNull(submittersString) != null) { submittersName = submittersName.concat(StringUtils.trimToNull(submittersString)); submittedText = s.getSubmittedText(); // SAK-17606 if (isAnon) { submittersName = root + s.getAnonymousSubmissionId(); submittersString = s.getAnonymousSubmissionId(); } if (!withoutFolders) { submittersName = submittersName.concat("/"); } else { submittersName = submittersName.concat("_"); } // record submission timestamp if (!withoutFolders) { if (s.getSubmitted() && s.getTimeSubmitted() != null) { ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt"); out.putNextEntry(textEntry); byte[] b = (s.getTimeSubmitted().toString()).getBytes(); out.write(b); textEntry.setSize(b.length); out.closeEntry(); } } // create the folder structure - named after the submitter's name if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission text if (withStudentSubmissionText) { // create the text file only when a text submission is allowed String submittersNameString = submittersName + submittersString; //remove folder name if Download All is without user folders if (withoutFolders) { submittersNameString = submittersName; } ZipEntry textEntry = new ZipEntry(submittersNameString + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE); out.putNextEntry(textEntry); byte[] text = submittedText.getBytes(); out.write(text); textEntry.setSize(text.length); out.closeEntry(); } // include student submission feedback text if (withFeedbackText) { // create a feedbackText file into zip ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html"); out.putNextEntry(fTextEntry); byte[] fText = s.getFeedbackText().getBytes(); out.write(fText); fTextEntry.setSize(fText.length); out.closeEntry(); } } if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { // include student submission attachment if (withStudentSubmissionAttachment) { //remove "/" that creates a folder if Download All is without user folders String sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt");//jh + "/"; if (!withoutFolders) { // create a attachment folder for the submission attachments sSubAttachmentFolder = submittersName + rb.getString("stuviewsubm.submissatt") + "/"; sSubAttachmentFolder = escapeInvalidCharsEntry(sSubAttachmentFolder); ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder); out.putNextEntry(sSubAttachmentFolderEntry); } else { sSubAttachmentFolder = sSubAttachmentFolder + "_"; //submittersName = submittersName.concat("_"); } // add all submission attachment into the submission attachment folder zipAttachments(out, submittersName, sSubAttachmentFolder, s.getSubmittedAttachments()); out.closeEntry(); } } if (withFeedbackComment) { // the comments.txt file to show instructor's comments ZipEntry textEntry = new ZipEntry( submittersName + "comments" + ZIP_COMMENT_FILE_TYPE); out.putNextEntry(textEntry); byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes(); out.write(b); textEntry.setSize(b.length); out.closeEntry(); } if (withFeedbackAttachment) { // create an attachment folder for the feedback attachments String feedbackSubAttachmentFolder = submittersName + rb.getString("download.feedback.attachment"); if (!withoutFolders) { feedbackSubAttachmentFolder = feedbackSubAttachmentFolder + "/"; ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry( feedbackSubAttachmentFolder); out.putNextEntry(feedbackSubAttachmentFolderEntry); } else { submittersName = submittersName.concat("_"); } // add all feedback attachment folder zipAttachments(out, submittersName, feedbackSubAttachmentFolder, s.getFeedbackAttachments()); out.closeEntry(); } } // if } } catch (Exception e) { caughtException = e.toString(); if (M_log.isDebugEnabled()) { caughtStackTrace = ExceptionUtils.getStackTrace(e); } break; } } // if the user is still in site } // while -- there is submission if (caughtException == null) { // continue if (withGradeFile) { ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension()); out.putNextEntry(gradesCSVEntry); sheet.write(out); out.closeEntry(); } } else { // log the error exceptionMessage.append(" Exception " + caughtException + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n"); if (M_log.isDebugEnabled()) { exceptionMessage.append(caughtStackTrace); } } } catch (IOException e) { exceptionMessage.append("IOException for creating submission zip file for assignment " + "\"" + assignmentTitle + "\" exception: " + e + "\n"); } finally { // Complete the ZIP file if (out != null) { try { out.finish(); out.flush(); } catch (IOException e) { // tried } try { out.close(); } catch (IOException e) { // tried } } } }