Example usage for java.util.zip ZipOutputStream closeEntry

List of usage examples for java.util.zip ZipOutputStream closeEntry

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream closeEntry.

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public String storeJsonZips(String digits) {

    if ((digits == null) || (digits.length() == 0)) {
        digits = "0";
    }//from  ww w.ja  va  2s  .  c  om
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;

    try {

        for (int i = 0; i < 100; ++i) {

            String zip1 = digits + String.format("%02d", i);
            ParentChild data = getParentChildDao().get(zip1);

            if (data == null) {
                continue;
            }

            Map<String, ParentChild> pcs = new HashMap<String, ParentChild>();
            SortedSet<String> zip2s = new TreeSet<String>();

            for (String json : data.getChildren()) {

                JSONObject jo = new JSONObject(json);
                String key = jo.optString("key", "");
                String zip2 = jo.optString("zip2", "");

                if (key.length() == 0) {
                    continue;
                }
                if (zip2.length() == 0) {
                    continue;
                }

                if (!pcs.containsKey(jo.optString("key", ""))) {
                    pcs.put(key, getParentChildDao().get(key));
                }

                zip2s.add(zip2);
            }

            for (String zip2 : zip2s) {

                String zip = zip1 + zip2;
                String json = toJsonZips(data, zip, pcs);
                ZipEntry entry = new ZipEntry(zip + ".json");
                entry.setTime(timestamp);
                zos.putNextEntry(entry);
                zos.write(json.getBytes("UTF-8"));
                zos.closeEntry();
                ++cnt;
            }
        }

        if (cnt == 0) {

            ZipEntry entry = new ZipEntry("empty.txt");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write("empty".getBytes("UTF-8"));
            zos.closeEntry();
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_zip" + digits + ".zip");
        log.info(digits + ":" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }

    return digits.equals("9") ? null : "" + (Integer.parseInt(digits) + 1);
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

private void setAttachedFilesList(Object[] r, LogWriter log) throws Exception {
    String realSourceFileFoldername = null;
    String realSourceWildcard = null;
    FileObject sourcefile = null;
    FileObject file = null;/*from   w w w .  jav a2s.c om*/

    ZipOutputStream zipOutputStream = null;
    File masterZipfile = null;

    if (meta.isZipFilenameDynamic())
        data.ZipFilename = data.previousRowMeta.getString(r, data.indexOfDynamicZipFilename);

    try {

        if (meta.isDynamicFilename()) {
            // dynamic attached filenames
            if (data.indexOfSourceFilename > -1)
                realSourceFileFoldername = data.previousRowMeta.getString(r, data.indexOfSourceFilename);

            if (data.indexOfSourceWildcard > -1)
                realSourceWildcard = data.previousRowMeta.getString(r, data.indexOfSourceWildcard);

        } else {
            // static attached filenames
            realSourceFileFoldername = data.realSourceFileFoldername;
            realSourceWildcard = data.realSourceWildcard;
        }

        if (!Const.isEmpty(realSourceFileFoldername)) {
            sourcefile = KettleVFS.getFileObject(realSourceFileFoldername);
            if (sourcefile.exists()) {
                long FileSize = 0;
                FileObject list[] = null;
                if (sourcefile.getType() == FileType.FILE) {
                    list = new FileObject[1];
                    list[0] = sourcefile;
                } else
                    list = sourcefile
                            .findFiles(new TextFileSelector(sourcefile.toString(), realSourceWildcard));
                if (list.length > 0) {

                    boolean zipFiles = meta.isZipFiles();
                    if (zipFiles && data.zipFileLimit == 0) {
                        masterZipfile = new File(
                                System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename);

                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
                    }

                    for (int i = 0; i < list.length; i++) {

                        file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                        if (zipFiles) {

                            if (data.zipFileLimit == 0) {
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();
                            } else
                                FileSize += file.getContent().getSize();
                        } else {
                            addAttachedFilePart(file);
                        }
                    } // end for
                    if (zipFiles) {
                        if (log.isDebug())
                            log.logDebug(toString(), Messages.getString("Mail.Log.FileSize", "" + FileSize));
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("Mail.Log.LimitSize", "" + data.zipFileLimit));

                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit) {

                            masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                                    + data.ZipFilename);

                            zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                            for (int i = 0; i < list.length; i++) {

                                file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                            }

                        }
                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit || data.zipFileLimit == 0) {
                            file = KettleVFS.getFileObject(masterZipfile.getAbsolutePath());
                            addAttachedFilePart(file);
                        }
                    }
                }
            } else {
                log.logError(toString(),
                        Messages.getString("Mail.Error.SourceFileFolderNotExists", realSourceFileFoldername));
            }
        }
    } catch (Exception e) {
        log.logError(toString(), e.getMessage());
    } finally {
        if (sourcefile != null) {
            try {
                sourcefile.close();
            } catch (Exception e) {
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
            }
        }

        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
                zipOutputStream.close();
            } catch (IOException e) {
                log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString());
            }
        }
    }

}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }//from  w w  w. j av a  2  s.  c  o  m

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.BrowseExecute.java

private void exportMessage(IMessageBrowser mb, String id, ReceiverBase receiver,
        ZipOutputStream zipOutputStream) {
    IListener listener = null;//  www.jav  a  2  s .c  om
    if (receiver != null) {
        listener = receiver.getListener();
    }
    try {
        Object rawmsg = mb.browseMessage(id);
        IMessageBrowsingIteratorItem msgcontext = mb.getContext(id);
        try {
            String msg = null;
            String msgId = msgcontext.getId();
            String msgMid = msgcontext.getOriginalId();
            String msgCid = msgcontext.getCorrelationId();
            HashMap context = new HashMap();
            if (listener != null) {
                msg = listener.getStringFromRawMessage(rawmsg, context);
            } else {
                msg = (String) rawmsg;
            }
            if (StringUtils.isEmpty(msg)) {
                msg = "<no message found>";
            }
            if (msgId == null) {
                msgId = "";
            }
            if (msgMid == null) {
                msgMid = "";
            }
            if (msgCid == null) {
                msgCid = "";
            }
            String filename = "msg_" + id + "_id[" + msgId.replace(':', '-') + "]" + "_mid["
                    + msgMid.replace(':', '-') + "]" + "_cid[" + msgCid.replace(':', '-') + "]";
            ZipEntry zipEntry = new ZipEntry(filename + ".txt");

            String sentDateString = (String) context.get(IPipeLineSession.tsSentKey);
            if (StringUtils.isNotEmpty(sentDateString)) {
                try {
                    Date sentDate = DateUtils.parseToDate(sentDateString, DateUtils.FORMAT_FULL_GENERIC);
                    zipEntry.setTime(sentDate.getTime());
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not set date for message [" + id + "]", e);
                }
            } else {
                Date insertDate = msgcontext.getInsertDate();
                if (insertDate != null) {
                    zipEntry.setTime(insertDate.getTime());
                }
            }
            //            String comment=msgcontext.getCommentString();
            //            if (StringUtils.isNotEmpty(comment)) {
            //               zipEntry.setComment(comment);
            //            }

            zipOutputStream.putNextEntry(zipEntry);
            String encoding = Misc.DEFAULT_INPUT_STREAM_ENCODING;
            if (msg.startsWith("<?xml")) {
                int lastpos = msg.indexOf("?>");
                if (lastpos > 0) {
                    String prefix = msg.substring(6, lastpos);
                    int encodingStartPos = prefix.indexOf("encoding=\"");
                    if (encodingStartPos > 0) {
                        int encodingEndPos = prefix.indexOf('"', encodingStartPos + 10);
                        if (encodingEndPos > 0) {
                            encoding = prefix.substring(encodingStartPos + 10, encodingEndPos);
                            log.debug("parsed encoding [" + encoding + "] from prefix [" + prefix + "]");
                        }
                    }
                }
            }
            zipOutputStream.write(msg.getBytes(encoding));

            if (listener != null && listener instanceof IBulkDataListener) {
                IBulkDataListener bdl = (IBulkDataListener) listener;
                String bulkfilename = bdl.retrieveBulkData(rawmsg, msg, context);

                zipOutputStream.closeEntry();

                File bulkfile = new File(bulkfilename);

                zipEntry = new ZipEntry(filename + "_" + bulkfile.getName());
                zipEntry.setTime(bulkfile.lastModified());
                zipOutputStream.putNextEntry(zipEntry);
                StreamUtil.copyStream(new FileInputStream(bulkfile), zipOutputStream, 32000);
                bulkfile.delete();
            }
            zipOutputStream.closeEntry();
        } finally {
            msgcontext.release();
        }
    } catch (Throwable e) {
        error(", ", "errors.generic", "Could not export message with id [" + id + "]", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * ??/*from  w ww.ja  v a  2 s.  c  om*/
 * 
 * @param sep "\t" / ","
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 * @param chaset "UTF-8" / "MS932"
 * @param enc "utf8" / "sjis"
 * @param ext "txt" / "csv"
 */
void storeText(String sep, String name, String suffix, String chaset, String enc, String ext) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_" + enc + "." + ext);
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = sep.getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);
                zos.write(zip.getCode().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getX0402().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorp().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorpYomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getNote().getBytes(chaset));
                zos.write(crlf);
                ++cnt;
            }
        }

        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_" + enc + "_" + ext + ".zip");
        log.info("count: " + cnt);

    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.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. java 2s  .co  m*/

            sb.append(long1);
        }
    }

    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);
    }

    if (idsToExport.size() == 1) {
        return this.esporta(idsToExport.get(0), rawValues, uriInfo, bd, zout);
    }

    String fileName = "Domini.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        DominiBD dominiBD = new DominiBD(bd);

        for (Long idDominio : idsToExport) {
            Dominio dominio = dominiBD.getDominio(idDominio);
            String folderName = dominio.getCodDominio();

            IbanAccreditoBD ibanAccreditoDB = new IbanAccreditoBD(bd);
            IbanAccreditoFilter filter = ibanAccreditoDB.newFilter();
            filter.setIdDominio(idDominio);
            List<IbanAccredito> ibans = ibanAccreditoDB.findAll(filter);
            final byte[] contiAccredito = DominioUtils.buildInformativaContoAccredito(dominio, ibans);

            ZipEntry contiAccreditoXml = new ZipEntry(folderName + "/contiAccredito.xml");
            zout.putNextEntry(contiAccreditoXml);
            zout.write(contiAccredito);
            zout.closeEntry();

            final byte[] informativa = DominioUtils.buildInformativaControparte(dominio, true);

            ZipEntry informativaXml = new ZipEntry(folderName + "/informativa.xml");
            zout.putNextEntry(informativaXml);
            zout.write(informativa);
            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:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * XML ??/*www .  j av a  2s. c o  m*/
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeXml(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        zos.putNextEntry(entry);

        OutputStreamWriter writer = new OutputStreamWriter(zos, "UTF-8");
        XMLStreamWriter xwriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("zips");
        xwriter.writeAttribute("type", name);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                Zip zip = Zip.fromJson(json);

                xwriter.writeStartElement("zip");
                xwriter.writeAttribute("zip", zip.getCode());
                xwriter.writeAttribute("x0402", zip.getX0402());
                xwriter.writeAttribute("add1", zip.getAdd1());
                xwriter.writeAttribute("add2", zip.getAdd2());
                xwriter.writeAttribute("corp", zip.getCorp());
                xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi());
                xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi());
                xwriter.writeAttribute("corpYomi", zip.getCorpYomi());
                xwriter.writeAttribute("note", zip.getNote());
                xwriter.writeEndElement();
                ++cnt;
            }
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip");
        log.info("count: " + cnt);

    } catch (XMLStreamException e) {
        log.log(Level.WARNING, "", e);
    } catch (FactoryConfigurationError e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }//w  ww.  j a  v a2 s . c o  m

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    String fileName = "Rendicontazioni.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport();
        FrBD frBD = new FrBD(bd);
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        FrFilter filter = frBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdFr(idsToExport);

        //1. eseguo una count per verificare che il numero dei risultati da esportare sia <= sogliamassimaexport massivo
        boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, frBD, simpleSearch, filter);

        if (!eseguiRicerca) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.operazioneNonPermessa"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        long count = frBD.countExt(filter);

        if (count < 1) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        if (count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        filter.setOffset(0);
        filter.setLimit(limit);
        FilterSortWrapper fsw = new FilterSortWrapper();
        fsw.setField(it.govpay.orm.FR.model().DATA_ORA_FLUSSO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Fr> findAllExt = frBD.findAllExt(filter);

        for (Fr fr : findAllExt) {
            String folderName = "Rendicontazione_" + fr.getIur();

            ZipEntry frXml = new ZipEntry(folderName + "/fr.xml");
            zout.putNextEntry(frXml);
            zout.write(fr.getXml());
            zout.closeEntry();
        }
        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (ExportException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:org.apache.syncope.core.logic.report.ReportJobDelegate.java

@Transactional
public void execute(final String reportKey) throws JobExecutionException {
    Report report = reportDAO.find(reportKey);
    if (report == null) {
        throw new JobExecutionException("Report " + reportKey + " not found");
    }//  ww  w . j  av a2 s  . co m

    if (!report.isActive()) {
        LOG.info("Report {} not active, aborting...", reportKey);
        return;
    }

    // 1. create execution
    ReportExec execution = entityFactory.newEntity(ReportExec.class);
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStart(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    report.add(execution);
    report = reportDAO.save(report);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        tFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
        handler = tFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, SyncopeConstants.DEFAULT_ENCODING);
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.XSD_STRING, report.getName());
        handler.startElement("", "", ReportXMLConst.ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class<? extends Reportlet> reportletClass = implementationLookup
                    .getReportletClass(reportletConf.getClass());
            if (reportletClass == null) {
                LOG.warn("Could not find matching reportlet for {}", reportletConf.getClass());
            } else {
                // fetch (or create) reportlet
                Reportlet reportlet;
                if (ApplicationContextProvider.getBeanFactory().containsSingleton(reportletClass.getName())) {
                    reportlet = (Reportlet) ApplicationContextProvider.getBeanFactory()
                            .getSingleton(reportletClass.getName());
                } else {
                    reportlet = (Reportlet) ApplicationContextProvider.getBeanFactory()
                            .createBean(reportletClass, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                    ApplicationContextProvider.getBeanFactory().registerSingleton(reportletClass.getName(),
                            reportlet);
                }

                // invoke reportlet
                try {
                    reportlet.extract(reportletConf, handler);
                } catch (Throwable t) {
                    LOG.error("While executing reportlet {} for report {}", reportlet, reportKey, t);

                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable effective = t instanceof ReportException ? t.getCause() : t;
                    reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(effective))
                            .append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ReportXMLConst.ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {
            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);
        reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(e));

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            IOUtils.closeQuietly(zos);
            IOUtils.closeQuietly(baos);
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEnd(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:com.joliciel.csvLearner.CSVEventListWriter.java

public void writeFile(GenericEvents events) {
    try {/*from  w  ww  . j a  v  a 2s .  c  om*/
        LOG.debug("writeFile: " + file.getName());
        file.delete();
        file.createNewFile();
        if (file.getName().endsWith(".zip"))
            isZip = true;
        Writer writer = null;
        ZipOutputStream zos = null;
        try {
            if (isZip) {
                zos = new ZipOutputStream(new FileOutputStream(file, false));
                writer = new BufferedWriter(new OutputStreamWriter(zos));
            } else {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
            }
            Set<String> features = new TreeSet<String>();
            if (!filePerEvent) {
                if (isZip) {
                    zos.putNextEntry(new ZipEntry(
                            file.getName().substring(0, file.getName().lastIndexOf('.')) + ".csv"));
                }

                for (GenericEvent event : events) {
                    if (LOG.isTraceEnabled())
                        LOG.trace("Writing event: " + event.getIdentifier());
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }
                }

                writer.append("ID,");

                if (includeOutcomes)
                    writer.append("outcome,");
                for (String feature : features) {
                    writer.append(CSVFormatter.format(feature) + ",");
                }

                writer.append("\n");
                writer.flush();
            }

            for (GenericEvent event : events) {
                if (filePerEvent) {
                    features = new TreeSet<String>();
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }

                    if (isZip)
                        zos.putNextEntry(new ZipEntry(event.getIdentifier() + ".csv"));
                    writer.append("ID,");
                    if (includeOutcomes)
                        writer.append("outcome,");

                    for (String feature : features) {
                        writer.append(CSVFormatter.format(feature) + ",");
                    }

                    writer.append("\n");
                    writer.flush();
                }
                writer.append(CSVFormatter.format(identifierPrefix + event.getIdentifier()) + ",");
                if (includeOutcomes)
                    writer.append(CSVFormatter.format(event.getOutcome()) + ",");

                for (String feature : features) {
                    Integer featureIndexObj = event.getFeatureIndex(feature);
                    int featureIndex = featureIndexObj == null ? -1 : featureIndexObj.intValue();

                    if (featureIndex < 0) {
                        writer.append(missingValueString + ",");
                    } else {
                        String eventFeature = event.getFeatures().get(featureIndex);
                        if (!eventFeature.equals(feature)) {
                            int classIndex = eventFeature.indexOf(CSVLearner.NOMINAL_MARKER);
                            String clazz = eventFeature
                                    .substring(classIndex + CSVLearner.NOMINAL_MARKER.length());
                            writer.append(CSVFormatter.format(clazz) + ",");
                        } else {
                            double value = event.getWeights().get(featureIndex);
                            writer.append(CSVFormatter.format(value) + ",");
                        }
                    }
                }
                writer.append("\n");
                writer.flush();
                if (filePerEvent && isZip)
                    zos.closeEntry();
            }
            if (!filePerEvent && isZip)
                zos.closeEntry();
        } finally {
            if (zos != null) {
                zos.flush();
                zos.close();
            }
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}