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:it.govpay.web.rs.dars.monitoraggio.incassi.IncassiHandler.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 + "]";

    try {/* www  .java  2  s .  c o  m*/
        int numeroZipEntries = 0;
        this.log.info("Esecuzione " + methodName + " in corso...");
        Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita);
        boolean eseguiRicerca = !setDomini.isEmpty();
        List<String> idDomini = new ArrayList<String>();
        IncassiBD incassiBD = new IncassiBD(bd);
        IncassoFilter filter = incassiBD.newFilter();

        List<Long> ids = new ArrayList<Long>();
        ids.add(idToExport);

        if (!setDomini.contains(-1L)) {
            List<Long> lstCodDomini = new ArrayList<Long>();
            lstCodDomini.addAll(setDomini);
            idDomini.addAll(this.toListCodDomini(lstCodDomini, bd));
            filter.setCodDomini(idDomini);
        }

        if (eseguiRicerca) {
            filter.setIdIncasso(ids);
            eseguiRicerca = eseguiRicerca && incassiBD.count(filter) > 0;
        }

        Incasso incasso = eseguiRicerca ? incassiBD.getIncasso(idToExport) : null;
        String fileName = "Export.zip";

        if (incasso != null) {
            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Applicazione applicazione = incasso.getApplicazione(incassiBD);
            List<Pagamento> pagamenti = incasso.getPagamenti(incassiBD);
            List<it.govpay.model.Pagamento> pagamentiList = new ArrayList<it.govpay.model.Pagamento>();
            pagamentiList.addAll(pagamenti);
            IncassoPdf.getPdfIncasso(pathLoghi, incasso, pagamentiList, applicazione, baos, this.log);
            String incassoPdfEntryName = incasso.getTrn() + ".pdf";
            numeroZipEntries++;
            ZipEntry rtPdf = new ZipEntry(incassoPdfEntryName);
            zout.putNextEntry(rtPdf);
            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 sugli incassi 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:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);/* w ww . j a  va2 s  .c  o m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

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

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } 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:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

private void convertOutputZip(String userId, String workflowId, String jobId, String fileName, InputStream is,
        OutputStream os) throws IOException {

    InputStream exactFile = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;//  w w  w. ja v a  2s . c  o m
    String runtimeID = getRuntimeID(userId, workflowId);
    ZipOutputStream zos = new ZipOutputStream(os);
    while ((entry = zis.getNextEntry()) != null) {

        if (jobId == null || (entry.getName().contains(jobId + "/outputs/" + runtimeID + "/")
                && (fileName == null || (fileName != null && entry.getName().endsWith(fileName))))) {
            int size;
            byte[] buffer = new byte[2048];

            String parentDir = entry.getName().split("/")[entry.getName().split("/").length - 2];
            String fileNameInZip = parentDir + "/"
                    + entry.getName().split("/")[entry.getName().split("/").length - 1];
            ZipEntry newFile = new ZipEntry(fileNameInZip);
            zos.putNextEntry(newFile);

            while ((size = zis.read(buffer, 0, buffer.length)) != -1) {

                zos.write(buffer, 0, size);
            }
            zos.closeEntry();

        }
    }
    zis.close();
    zos.close();

}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * Download an HTML page and all its referenced files into a ZIP
 * @param sBasePath String Base path for page and its referenced files
 * @param sFilePath String File path from sBasePath
 * @param oOutStrm OutputStream where ZIP is written
 * @param sDefaultEncoding Character encoding of file to be downloaded
 * @throws IOException/*from   ww  w .j  ava  2s . c  om*/
 * @since 7.0
 */
public void downloadhtmlpage(String sBasePath, String sFilePath, OutputStream oOutStrm, String sDefaultEncoding)
        throws IOException {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.downloadhtmlpage(" + sBasePath + "," + sFilePath
                + ",[OutputStream]," + sDefaultEncoding + ")");
        DebugFile.incIdent();
    }

    String sEncoding = sDefaultEncoding;
    String sBaseHref = "";
    boolean bAutoDetectEncoding = (sDefaultEncoding == null);
    TreeSet<String> oFiles = new TreeSet<String>();
    TreeSet<String> oEntries = new TreeSet<String>();
    Perl5Matcher oMatcher = new Perl5Matcher();
    Perl5Matcher oReplacer = new Perl5Matcher();
    Perl5Compiler oCompiler = new Perl5Compiler();

    if (sDefaultEncoding == null)
        sDefaultEncoding = "ASCII";

    try {
        String sHtml = readfilestr(sBasePath + sFilePath, sDefaultEncoding);

        if (null == sHtml) {
            if (DebugFile.trace) {
                DebugFile.writeln("Could not read file " + sBasePath + sFilePath);
                DebugFile.decIdent();
                throw new IOException("Could not read file " + sBasePath + sFilePath);
            }
        }

        if (DebugFile.trace) {
            DebugFile.writeln(
                    String.valueOf(sHtml.length()) + " characters readed from file " + sBasePath + sFilePath);
        }

        if (bAutoDetectEncoding) {
            if (oMatcher.contains(sHtml, oCompiler.compile(
                    "<meta\\x20+http-equiv=(\"|')?Content-Type(\"|')?\\x20+content=(\"|')?text/html;\\x20+charset=(\\w|-){3,32}(\"|')?>",
                    Perl5Compiler.CASE_INSENSITIVE_MASK))) {
                if (DebugFile.trace)
                    DebugFile.writeln("<meta http-equiv> tag found");
                String sHttpEquiv = oMatcher.getMatch().toString();
                int iCharset = Gadgets.indexOfIgnoreCase(sHttpEquiv, "charset=");
                if (iCharset > 0) {
                    int iQuoute = sHttpEquiv.indexOf('"', iCharset);
                    if (iQuoute < 0)
                        iQuoute = sHttpEquiv.indexOf((char) 39, iCharset);
                    if (iQuoute < 0) {
                        bAutoDetectEncoding = true;
                    } else {
                        sEncoding = sHttpEquiv.substring(iCharset + 8, iQuoute);
                        if (DebugFile.trace)
                            DebugFile.writeln("setting charset encoding to " + sEncoding);
                        bAutoDetectEncoding = false;
                        try {
                            byte[] aTest = new String("Test").getBytes(sEncoding);
                        } catch (UnsupportedEncodingException uex) {
                            bAutoDetectEncoding = true;
                        }
                    }
                } else {
                    bAutoDetectEncoding = true;
                }
            } else {
                bAutoDetectEncoding = true;
            }
        }

        if (bAutoDetectEncoding) {
            if (DebugFile.trace)
                DebugFile.writeln("Autodetecting encoding");
            ByteArrayInputStream oHtmlStrm = new ByteArrayInputStream(sHtml.getBytes(sDefaultEncoding));
            sEncoding = new CharacterSetDetector().detect(oHtmlStrm, sDefaultEncoding);
            oHtmlStrm.close();
            if (DebugFile.trace)
                DebugFile.writeln("Encoding set to " + sEncoding);
        }

        Pattern oPattern = oCompiler.compile("<base(\\x20)+href=(\"|')?([^'\"\\r\\n]+)(\"|')?(\\x20)*/?>",
                Perl5Compiler.CASE_INSENSITIVE_MASK);
        if (oMatcher.contains(sHtml, oPattern)) {
            sBaseHref = Gadgets.chomp(oMatcher.getMatch().group(3), "/");
            if (DebugFile.trace)
                DebugFile.writeln("<base href=" + sBaseHref + ">");
        }

        PatternMatcherInput oMatchInput = new PatternMatcherInput(sHtml);
        oPattern = oCompiler.compile(
                "\\x20(src=|background=|background-image:url\\x28)(\"|')?([^'\"\\r\\n]+)(\"|')?(\\x20|\\x29|/|>)",
                Perl5Compiler.CASE_INSENSITIVE_MASK);
        StringSubstitution oSrcSubs = new StringSubstitution();
        int nMatches = 0;
        while (oMatcher.contains(oMatchInput, oPattern)) {
            nMatches++;
            String sMatch = oMatcher.getMatch().toString();
            String sAttr = oMatcher.getMatch().group(1);
            String sQuo = oMatcher.getMatch().group(2);
            if (sQuo == null)
                sQuo = "";
            String sSrc = oMatcher.getMatch().group(3);
            if (DebugFile.trace)
                DebugFile.writeln("Source file found at " + sSrc);
            String sEnd = oMatcher.getMatch().group(5);
            if (!oFiles.contains(sSrc))
                oFiles.add(sSrc);
            String sFilename = sSrc.substring(sSrc.replace('\\', '/').lastIndexOf('/') + 1);
            if (DebugFile.trace)
                DebugFile.writeln("StringSubstitution.setSubstitution(" + sMatch + " replace with "
                        + sMatch.substring(0, sAttr.length() + 1) + sQuo + sFilename + sQuo + sEnd + ")");
            oSrcSubs.setSubstitution(sMatch.substring(0, sAttr.length() + 1) + sQuo + sFilename + sQuo + sEnd);
            sHtml = Util.substitute(oReplacer, oCompiler.compile(sMatch), oSrcSubs, sHtml, Util.SUBSTITUTE_ALL);
        } //wend

        oMatchInput = new PatternMatcherInput(sHtml);
        oPattern = oCompiler.compile(
                "<link\\x20+(rel=(\"|')?stylesheet(\"|')?\\x20+)?(type=(\"|')?text/css(\"|')?\\x20+)?href=(\"|')?([^'\"\\r\\n]+)(\"|')?");
        while (oMatcher.contains(oMatchInput, oPattern)) {
            nMatches++;
            String sMatch = oMatcher.getMatch().toString();
            String sSrc = oMatcher.getMatch().group(8);
            String sFilename = sSrc.substring(sSrc.replace('\\', '/').lastIndexOf('/') + 1);
            if (!oFiles.contains(sSrc))
                oFiles.add(sSrc);
            if (DebugFile.trace)
                DebugFile.writeln("StringSubstitution.setSubstitution(" + sMatch + " replace with "
                        + Gadgets.replace(sMatch, sSrc, sFilename) + ")");
            oSrcSubs.setSubstitution(Gadgets.replace(sMatch, sSrc, sFilename));
            sHtml = Util.substitute(oReplacer, oCompiler.compile(sMatch), oSrcSubs, sHtml);
        } // wend     

        if (DebugFile.trace) {
            DebugFile.writeln(String.valueOf(nMatches) + " matches found");
            DebugFile.write("\n" + sHtml + "\n");
        }

        ZipOutputStream oZOut = new ZipOutputStream(oOutStrm);
        String sLocalName = sFilePath.substring(sFilePath.replace('\\', '/').lastIndexOf('/') + 1);
        int iDot = sLocalName.lastIndexOf('.');
        if (iDot > 0)
            sLocalName = Gadgets.ASCIIEncode(sLocalName.substring(0, iDot)).toLowerCase() + ".html";
        else
            sLocalName = Gadgets.ASCIIEncode(sLocalName).toLowerCase();
        oEntries.add(sLocalName);
        if (DebugFile.trace)
            DebugFile.writeln("Putting entry " + sLocalName + " into ZIP");
        oZOut.putNextEntry(new ZipEntry(sLocalName));
        StringBufferInputStream oHtml = new StringBufferInputStream(sHtml);
        new StreamPipe().between(oHtml, oZOut);
        oHtml.close();
        oZOut.closeEntry();

        for (String sName : oFiles) {
            String sZipEntryName = sName.substring(sName.replace('\\', '/').lastIndexOf('/') + 1);
            if (!oEntries.contains(sZipEntryName)) {
                oEntries.add(sZipEntryName);
                if (DebugFile.trace)
                    DebugFile.writeln("Putting entry " + sZipEntryName + " into ZIP");
                oZOut.putNextEntry(new ZipEntry(sZipEntryName));
                if (sName.startsWith("http://") || sName.startsWith("https://") || sName.startsWith("file://")
                        || sBaseHref.length() > 0) {
                    try {
                        new StreamPipe().between(new ByteArrayInputStream(readfilebin(sBaseHref + sName)),
                                oZOut);
                    } catch (IOException ioe) {
                        if (DebugFile.trace) {
                            DebugFile.decIdent();
                            DebugFile.writeln("Could not download file " + sName);
                        }
                    }
                } else {
                    try {
                        byte[] aFile = readfilebin(
                                sBasePath + (sName.startsWith("/") ? sName.substring(1) : sName));
                        if (null != aFile) {
                            if (aFile.length > 0)
                                new StreamPipe().between(new ByteArrayInputStream(aFile), oZOut);
                        } else {
                            DebugFile.writeln("Could not find file " + sBasePath
                                    + (sName.startsWith("/") ? sName.substring(1) : sName));
                        }
                    } catch (IOException ioe) {
                        if (DebugFile.trace) {
                            DebugFile.decIdent();
                            DebugFile.writeln("Could not download file " + sBasePath
                                    + (sName.startsWith("/") ? sName.substring(1) : sName));
                        }
                    }
                }
                oZOut.closeEntry();
            } // fi (sName!=sLocalName)
        } // next
        oZOut.close();

    } catch (MalformedPatternException mpe) {

    } catch (FTPException ftpe) {

    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.downloadhtmlpage()");
    }
}

From source file:org.apache.syncope.core.report.ReportJob.java

@SuppressWarnings("rawtypes")
@Override//  w  w  w .j  av  a  2s. c om
public void execute(final JobExecutionContext context) throws JobExecutionException {
    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }

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

    report.addExec(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();
        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();
    StringWriter exceptionWriter = new StringWriter();
    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<Reportlet> reportletClass = dataBinder
                    .findReportletClassHavingConfClass(reportletConf.getClass());
            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) ApplicationContextProvider.getBeanFactory()
                        .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;
                    reportExecutionMessage.append(ExceptionUtil.getFullStackTrace(t))
                            .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(ExceptionUtil.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.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

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

@SuppressWarnings("rawtypes")
@Override/*from w  ww.ja  va2  s  .c  o  m*/
public void execute(final JobExecutionContext context) throws JobExecutionException {
    Report report = reportDAO.find(reportKey);
    if (report == null) {
        throw new JobExecutionException("Report " + reportKey + " not found");
    }

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

    report.addExec(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();
        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<Reportlet> reportletClass = dataBinder
                    .findReportletClassHavingConfClass(reportletConf.getClass());
            if (reportletClass != null) {
                Reportlet<ReportletConf> autowired = (Reportlet<ReportletConf>) ApplicationContextProvider
                        .getBeanFactory()
                        .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;
                    reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(t))
                            .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.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Operation for fetching data of type FILE.
 * //  w  ww.j a  va2 s .  c  o  m
 * @param importSource
 * @param identifier
 * @param listOfFormats
 * @return byte[] of the fetched file, zip file if more than one record was
 *         fetched
 * @throws RuntimeException
 * @throws SourceNotAvailableException
 */
private byte[] fetchData(String identifier, Format[] formats)
        throws SourceNotAvailableException, RuntimeException, FormatNotAvailableException {
    byte[] in = null;
    FullTextVO fulltext = new FullTextVO();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {
        // Call fetch file for every given format
        for (int i = 0; i < formats.length; i++) {
            Format format = formats[i];
            fulltext = this.util.getFtObjectToFetch(this.currentSource, format.getName(), format.getType(),
                    format.getEncoding());
            // Replace regex with identifier
            String decoded = java.net.URLDecoder.decode(fulltext.getFtUrl().toString(),
                    this.currentSource.getEncoding());
            fulltext.setFtUrl(new URL(decoded));
            fulltext.setFtUrl(
                    new URL(fulltext.getFtUrl().toString().replaceAll(this.regex, identifier.trim())));
            this.logger.debug("Fetch file from URL: " + fulltext.getFtUrl());

            // escidoc file
            if (this.currentSource.getHarvestProtocol().equalsIgnoreCase("ejb")) {
                in = this.fetchEjbFile(fulltext, identifier);
            }
            // other file
            else {
                in = this.fetchFile(fulltext);
            }

            this.setFileProperties(fulltext);
            // If only one file => return it in fetched format
            if (formats.length == 1) {
                return in;
            }
            // If more than one file => add it to zip
            else {
                // If cone service is not available (we do not get a
                // fileEnding) we have
                // to make sure that the zip entries differ in name.
                String fileName = identifier;
                if (this.getFileEnding().equals("")) {
                    fileName = fileName + "_" + i;
                }
                ZipEntry ze = new ZipEntry(fileName + this.getFileEnding());
                ze.setSize(in.length);
                ze.setTime(this.currentDate());
                CRC32 crc321 = new CRC32();
                crc321.update(in);
                ze.setCrc(crc321.getValue());
                zos.putNextEntry(ze);
                zos.write(in);
                zos.flush();
                zos.closeEntry();
            }
        }
        this.setContentType("application/zip");
        this.setFileEnding(".zip");
        zos.close();

    } catch (SourceNotAvailableException e) {
        this.logger.error("Import Source " + this.currentSource + " not available.", e);
        throw new SourceNotAvailableException(e);
    } catch (FormatNotAvailableException e) {
        throw new FormatNotAvailableException(e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:it.govpay.web.rs.dars.monitoraggio.eventi.EventiHandler.java

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

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

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";
    String fileName = "Eventi.zip";
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Map<String, String> params = new HashMap<String, String>();
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        EventiBD eventiBD = new EventiBD(bd);

        EventiFilter filter = eventiBD.newFilter(simpleSearch);

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

        boolean checkCount = this.popolaFiltroRicerca(rawValues, uriInfo, params, simpleSearch, filter);

        long count = eventiBD.count(filter);

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

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

        filter.setOffset(0);
        if (checkCount)
            filter.setLimit(ConsoleProperties.getInstance().getNumeroMassimoElementiExport());

        List<Evento> list = eventiBD.findAll(filter);

        if (list != null && list.size() > 0) {
            this.scriviCSVEventi(baos, list);

            ZipEntry datiEvento = new ZipEntry("eventi.csv");
            zout.putNextEntry(datiEvento);
            zout.write(baos.toByteArray());
            zout.closeEntry();
        } else {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sugli eventi selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

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

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

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);//from  w  w  w .  j a  v a  2  s .  co m
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

                Pattern pattern = null;
                if (!Const.isEmpty(realWildcard)) {
                    pattern = Pattern.compile(realWildcard);

                }
                Pattern patternexclude = null;
                if (!Const.isEmpty(realWildcardExclude)) {
                    patternexclude = Pattern.compile(realWildcardExclude);

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

                // Set the method
                out.setMethod(ZipOutputStream.DEFLATED);

                // Set the compression level
                if (compressionrate == 0) {
                    out.setLevel(Deflater.NO_COMPRESSION);
                } else if (compressionrate == 1) {
                    out.setLevel(Deflater.DEFAULT_COMPRESSION);
                }
                if (compressionrate == 2) {
                    out.setLevel(Deflater.BEST_COMPRESSION);
                }
                if (compressionrate == 3) {
                    out.setLevel(Deflater.BEST_SPEED);
                }

                // Specify Zipped files (After that we will move,delete them...)
                String[] ZippedFiles = new String[filelist.length];
                int FileNum = 0;

                // Get the files in the list...
                for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

                        int len;
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }

                        out.closeEntry();

                        // Close the current file input stream
                        in.close();

                        // Get Zipped File
                        ZippedFiles[FileNum] = filelist[i];
                        FileNum = FileNum + 1;
                    }
                }

                // Close the ZipOutPutStream
                out.close();

                //-----Get the list of Zipped Files and Move or Delete Them
                if (afterzip == 1 || afterzip == 2) {
                    // iterate through the array of Zipped files
                    for (int i = 0; i < ZippedFiles.length; i++) {
                        if (ZippedFiles[i] != null) {
                            // Delete File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

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

/**
 * IME??/*from w  ww. ja  va  2  s  .  c  o m*/
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeIme(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    SortedMap<String, Pref> prefs = getPrefMap();
    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 + "_ime_dic.txt");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = "\t".getBytes("MS932");
        byte[] sonota = "\t?????".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;
            }

            String prefName = prefs.get(city.getCode().substring(0, 2)).getName();
            String cityName = city.getName();

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

                Zip zip = Zip.fromJson(json);
                zos.write(ZenHanHelper.convertZipHankakuZenkaku(zip.getCode()).getBytes("MS932"));
                zos.write(tab);
                zos.write(prefName.getBytes("MS932"));
                zos.write(cityName.getBytes("MS932"));
                zos.write(zip.getAdd1().getBytes("MS932"));
                zos.write(zip.getAdd2().getBytes("MS932"));
                zos.write(zip.getCorp().getBytes("MS932"));
                zos.write(sonota);
                zos.write(crlf);
                ++cnt;
            }
        }

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

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