Example usage for java.util.zip ZipOutputStream flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

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

/**
 * Operation for fetching data of type FILE.
 * //from   w ww  . j  a  va  2 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:org.joget.apps.app.service.AppServiceImpl.java

/**
 * Export an app version in ZIP format into an OutputStream
 * @param appId/* ww w. j  a v a2s  . c o m*/
 * @param version If null, the latest app version will be used.
 * @param output The OutputStream the ZIP content will be streamed into
 * @return Returns the OutputStream object parameter passed in. If null, a ByteArrayOutputStream will be created and returned. 
 * @throws IOException 
 */
public OutputStream exportApp(String appId, String version, OutputStream output) throws IOException {
    ZipOutputStream zip = null;
    if (output == null) {
        output = new ByteArrayOutputStream();
    }
    try {
        AppDefinition appDef = loadAppDefinition(appId, version);
        if (appDef != null && output != null) {
            zip = new ZipOutputStream(output);

            // write zip entry for app XML
            byte[] data = getAppDefinitionXml(appId, appDef.getVersion());
            zip.putNextEntry(new ZipEntry("appDefinition.xml"));
            zip.write(data);
            zip.closeEntry();

            // write zip entry for app XML
            PackageDefinition packageDef = appDef.getPackageDefinition();
            if (packageDef != null) {
                byte[] xpdl = workflowManager.getPackageContent(packageDef.getId(),
                        packageDef.getVersion().toString());
                zip.putNextEntry(new ZipEntry("package.xpdl"));
                zip.write(xpdl);
                zip.closeEntry();
            }

            // finish the zip
            zip.finish();
        }
    } catch (Exception ex) {
        LogUtil.error(getClass().getName(), ex, "");
    } finally {
        if (zip != null) {
            zip.flush();
        }
    }
    return output;
}

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 {/*from   w w w .  j ava2s. 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:org.phpmaven.phpnar.PackageMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    super.execute();

    final File packageFolder = new File(this.project.getBuild().getDirectory());

    for (final AolItem item : this.aolItems) {
        item.check(getLog(), project);//from   www  .j av  a  2  s  .  co m

        final File targetFolder = new File(this.project.getBuild().getDirectory() + "/" + item.getAol());

        try {
            if ("Windows".equalsIgnoreCase(item.getEffectiveOs())) {
                final String effectiveArch = item.getArch().equals("amd64") ? "x64" : item.getArch();
                final File buildRootFolder = new File(targetFolder,
                        "phpdev/vc9/" + item.getArch() + "/php-" + this.project.getVersion());

                // executables
                final File executablePackage = new File(buildRootFolder,
                        "Release_TS\\php-" + project.getVersion() + "-Win32-VC9-" + effectiveArch + ".zip");
                if (!executablePackage.exists()) {
                    throw new MojoFailureException("executable package " + executablePackage.getAbsolutePath()
                            + " not found. Possible build failure.");
                }
                final File executableNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + ".nar");
                FileUtils.copyFileIfModified(executablePackage, executableNarFile);
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier(), executableNarFile);

                // developer pack
                final File developerPackage = new File(buildRootFolder, "Release_TS\\php-devel-pack-"
                        + project.getVersion() + "-Win32-VC9-" + effectiveArch + ".zip");
                if (!new File(buildRootFolder, "win32/build/config.w32.phpize.in").exists()
                        && developerPackage.exists() && this.project.getVersion().startsWith("5.3.")) {
                    // ensure the file is recreated for early php 5.3 versions
                    if (developerPackage.exists()) {
                        developerPackage.delete();
                    }
                }
                if (!developerPackage.exists()) {
                    if (this.project.getVersion().startsWith("5.3.")) {
                        // create the developer pack manually for 5.3.x
                        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(developerPackage));
                        final String prefix = "/php-" + project.getVersion() + "-devel-VC9-" + effectiveArch
                                + "/";
                        zip(zos, new File(buildRootFolder, "win32/build/confutils.js"),
                                prefix + "script/confutils.js");
                        zip(zos, new File(buildRootFolder, "win32/build/configure.tail"),
                                prefix + "script/configure.tail");
                        zipConfigW32PhpizeIn(zos, new File(buildRootFolder, "win32/build/config.w32.phpize.in"),
                                prefix + "script/config.w32.phpize.in");
                        zipMakefilePhpize(zos, new File(buildRootFolder, "win32/build/Makefile.phpize"),
                                prefix + "script/Makefile.phpize");
                        zipPhpizeBat(zos, new File(buildRootFolder, "win32/build/phpize.bat"),
                                prefix + "phpize.bat");
                        zipConfigPhpizeJs(zos, new File(buildRootFolder, "Release_TS\\devel\\config.phpize.js"),
                                prefix + "script/config.phpize.js");
                        zipPhpizeJs(zos, new File(buildRootFolder, "Release_TS\\devel\\phpize.js"),
                                prefix + "script/phpize.js");
                        zipExtDepsJs(zos, new File(buildRootFolder, "Release_TS\\devel\\ext_deps.js"),
                                prefix + "script/ext_deps.js");
                        zip(zos, new File(buildRootFolder, "php5ts.lib"), prefix + "lib/php5ts.lib");
                        zipHeaders(zos, new File(buildRootFolder, "TSRM"), prefix + "include/TSRM");
                        zipHeaders(zos, new File(buildRootFolder, "Zend"), prefix + "include/Zend");
                        zipHeaders(zos, new File(buildRootFolder, "main"), prefix + "include/main");
                        zipHeaders(zos, new File(buildRootFolder, "main/streams"),
                                prefix + "include/main/streams");
                        zipHeaders(zos, new File(buildRootFolder, "win32"), prefix + "include/win32");
                        // TODO what extensions to take?
                        zipHeaders(zos, new File(buildRootFolder, "ext/ereg/regex"),
                                prefix + "include/ext/ereg/regex");
                        zipHeaders(zos, new File(buildRootFolder, "ext/iconv"), prefix + "include/iconv");
                        zipHeaders(zos, new File(buildRootFolder, "ext/mysqlnd"),
                                prefix + "include/ext/mysqlnd");
                        zipHeaders(zos, new File(buildRootFolder, "ext/pcre/pcrelib"),
                                prefix + "include/ext/pcre/pcrelib");
                        zipHeaders(zos, new File(buildRootFolder, "ext/standard"),
                                prefix + "include/ext/standard");
                        zipHeaders(zos, new File(buildRootFolder, "ext/xml"), prefix + "include/ext/xml");
                        zos.flush();
                        zos.close();
                    } else {
                        // fail
                        throw new MojoFailureException("developer package " + developerPackage.getAbsolutePath()
                                + " not found. Possible build failure.");
                    }
                }
                final File developerNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + "-devel.nar");
                FileUtils.copyFileIfModified(developerPackage, developerNarFile);
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier() + "-devel",
                        developerNarFile);
                //                    
                //                    // test pack
                //                    final File testPackage = new File(buildRootFolder, "Release_TS\\php-test-pack-" + project.getVersion() + "-Win32-VC9-" + effectiveArch + ".zip");
                //                    if (!testPackage.exists()) {
                //                        throw new MojoFailureException("test package " + testPackage.getAbsolutePath() + " not found. Possible build failure.");
                //                    }
                //                    final File testNarFile = new File(packageFolder, this.project.getArtifactId() + "-" + this.project.getVersion() + "-" + item.getClassifier() + "-test.nar");
                //                    FileUtils.copyFileIfModified(testPackage, testNarFile);

                // sdk files
                final File sdkNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + "-sdk.nar");
                if (!sdkNarFile.exists()) {
                    ZipOutputStream target = new ZipOutputStream(new FileOutputStream(sdkNarFile));
                    zip(target, new File(targetFolder, "bin"), "/bin");
                    zip(target, new File(targetFolder, "script"), "/script");
                    target.flush();
                    target.close();
                }
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier() + "-sdk",
                        sdkNarFile);

                // dependencies files
                final File depsNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + "-deps.nar");
                if (!depsNarFile.exists()) {
                    ZipOutputStream target = new ZipOutputStream(new FileOutputStream(depsNarFile));
                    zip(target, new File(buildRootFolder.getParentFile(), "deps"), "/deps");
                    target.flush();
                    target.close();
                }
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier() + "-deps",
                        depsNarFile);
            } else {
                final File buildRootFolder = new File(targetFolder, "phpmaven.install");

                // executable
                final File executableNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + ".nar");
                if (executableNarFile.exists()) {
                    executableNarFile.delete();
                }
                if (!new File(buildRootFolder, "bin/php").exists()
                        && !new File(buildRootFolder, "bin/php-cgi").exists()) {
                    throw new MojoFailureException(
                            "executables bin/php and bin/php-cgi not found. Possible build failure.");
                }

                final ZipOutputStream executableTarget = new ZipOutputStream(
                        new FileOutputStream(executableNarFile));
                zip(executableTarget, new File(buildRootFolder, "bin/php"), "/bin/php");
                zip(executableTarget, new File(buildRootFolder, "bin/php-cgi"), "/bin/php-cgi");
                zip(executableTarget, new File(buildRootFolder, "modules"), "/modules");
                executableTarget.flush();
                executableTarget.close();
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier(), executableNarFile);

                // developer pack
                final File developerNarFile = new File(packageFolder, this.project.getArtifactId() + "-"
                        + this.project.getVersion() + "-" + item.getClassifier() + "-devel.nar");
                if (developerNarFile.exists()) {
                    developerNarFile.delete();
                }
                final ZipOutputStream developerTarget = new ZipOutputStream(
                        new FileOutputStream(developerNarFile));
                if (!new File(buildRootFolder, "lib/libphp5.so").exists()
                        && !new File(buildRootFolder, "include").exists()) {
                    throw new MojoFailureException(
                            "library lib/libphp5.so not built or include folder not found. Ensure you used --enable-embed=shared if you overwrite the configure options.");
                }
                zipFilterFile(developerTarget, new File(buildRootFolder, "bin/php-config"), "/bin/php-config",
                        buildRootFolder.getAbsolutePath(), "${MAVEN.INSTALL.ROOT}");
                zipFilterFile(developerTarget, new File(buildRootFolder, "bin/phpize"), "/bin/phpize",
                        buildRootFolder.getAbsolutePath(), "${MAVEN.INSTALL.ROOT}");
                zip(developerTarget, new File(buildRootFolder, "lib/libphp5.so"), "/lib/libphp5.so");
                zip(developerTarget, new File(buildRootFolder, "include"), "/include");
                developerTarget.flush();
                developerTarget.close();
                this.projectHelper.attachArtifact(this.project, "nar", item.getClassifier() + "-devel",
                        developerNarFile);
            }
        } catch (IOException ex) {
            throw new MojoFailureException("Error copying/creating nar files", ex);
        }
    }

    this.projectHelper.attachArtifact(this.project, "jar", "jar",
            new File(packageFolder, this.project.getArtifactId() + "-" + this.project.getVersion() + ".jar"));
}

From source file:cz.zcu.kiv.eegdatabase.logic.zip.ZipGenerator.java

public File generate(Experiment exp, MetadataCommand mc, Set<DataFile> dataFiles, byte[] licenseFile,
        String licenseFileName) throws Exception, SQLException, IOException {

    ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    File tempZipFile = null;//from   w ww .jav a2 s .c o  m

    try {
        log.debug("creating output stream");
        // create temp zip file
        tempZipFile = File.createTempFile("experimentDownload_", ".zip");
        // open stream to temp zip file
        fileOutputStream = new FileOutputStream(tempZipFile);
        // prepare zip stream
        zipOutputStream = new ZipOutputStream(fileOutputStream);

        log.debug("transforming metadata from database to xml file");
        OutputStream meta = getTransformer().transformElasticToXml(exp);
        Scenario scen = exp.getScenario();
        log.debug("getting scenario file");

        byte[] xmlMetadata = null;
        if (meta instanceof ByteArrayOutputStream) {
            xmlMetadata = ((ByteArrayOutputStream) meta).toByteArray();
        }

        ZipEntry entry;

        if (licenseFileName != null && !licenseFileName.isEmpty()) {
            zipOutputStream.putNextEntry(entry = new ZipEntry("License/" + licenseFileName));
            IOUtils.copyLarge(new ByteArrayInputStream(licenseFile), zipOutputStream);
            zipOutputStream.closeEntry();
        }

        if (mc.isScenFile() && scen.getScenarioFile() != null) {
            try {

                log.debug("saving scenario file (" + scen.getScenarioName() + ") into a zip file");
                entry = new ZipEntry("Scenario/" + scen.getScenarioName());
                zipOutputStream.putNextEntry(entry);
                IOUtils.copyLarge(scen.getScenarioFile().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();

            } catch (Exception ex) {
                log.error(ex);
            }
        }

        if (xmlMetadata != null) {
            log.debug("saving xml file of metadata to zip file");
            entry = new ZipEntry(getMetadata() + ".xml");
            zipOutputStream.putNextEntry(entry);
            zipOutputStream.write(xmlMetadata);
            zipOutputStream.closeEntry();
        }

        for (DataFile dataFile : dataFiles) {
            entry = new ZipEntry(getDataZip() + "/" + dataFile.getFilename());

            if (dataFile.getFileContent().length() > 0) {

                log.debug("saving data file to zip file");

                try {

                    zipOutputStream.putNextEntry(entry);

                } catch (ZipException ex) {

                    String[] partOfName = dataFile.getFilename().split("[.]");
                    String filename;
                    if (partOfName.length < 2) {
                        filename = partOfName[0] + "" + fileCounter;
                    } else {
                        filename = partOfName[0] + "" + fileCounter + "." + partOfName[1];
                    }
                    entry = new ZipEntry(getDataZip() + "/" + filename);
                    zipOutputStream.putNextEntry(entry);
                    fileCounter++;
                }

                IOUtils.copyLarge(dataFile.getFileContent().getBinaryStream(), zipOutputStream);
                zipOutputStream.closeEntry();
            }
        }

        log.debug("returning output stream of zip file");
        return tempZipFile;

    } finally {

        zipOutputStream.flush();
        zipOutputStream.close();
        fileOutputStream.flush();
        fileOutputStream.close();
        fileCounter = 0;

    }
}

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

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

            if (sb.length() > 0) {
                sb.append(", ");
            }/*from   ww  w  .ja v  a  2 s  .  com*/

            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: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  .  ja va 2s  . 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: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  ww  .j a va 2s  .  c  om

            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:org.pentaho.di.trans.steps.zipfile.ZipFile.java

private void zipFile() throws KettleException {

    String localrealZipfilename = KettleVFS.getFilename(data.zipFile);
    boolean updateZip = false;

    byte[] buffer = null;
    OutputStream dest = null;//from   w w  w.  j a  va  2 s.c  om
    BufferedOutputStream buff = null;
    ZipOutputStream out = null;
    InputStream in = null;
    ZipInputStream zin = null;
    ZipEntry entry = null;
    File tempFile = null;
    HashSet<String> fileSet = new HashSet<String>();

    try {

        updateZip = (data.zipFile.exists() && meta.isOverwriteZipEntry());

        if (updateZip) {
            // the Zipfile exists
            // and we weed to update entries
            // Let's create a temp file
            File fileZip = getFile(localrealZipfilename);
            tempFile = File.createTempFile(fileZip.getName(), null);
            // delete it, otherwise we cannot rename existing zip to it.
            tempFile.delete();

            updateZip = fileZip.renameTo(tempFile);
        }

        // Prepare Zip File
        buffer = new byte[18024];
        dest = KettleVFS.getOutputStream(localrealZipfilename, false);
        buff = new BufferedOutputStream(dest);
        out = new ZipOutputStream(buff);

        if (updateZip) {
            // 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);
        out.setLevel(Deflater.BEST_COMPRESSION);

        // Associate a file input stream for the current file
        in = KettleVFS.getInputStream(data.sourceFile);

        // Add ZIP entry to output stream.
        //
        String relativeName = data.sourceFile.getName().getBaseName();

        if (meta.isKeepSouceFolder()) {
            // Get full filename
            relativeName = KettleVFS.getFilename(data.sourceFile);

            if (data.baseFolder != null) {
                // Remove base folder
                data.baseFolder += Const.FILE_SEPARATOR;
                relativeName = relativeName.replace(data.baseFolder, "");
            }
        }
        if (!fileSet.contains(relativeName)) {
            out.putNextEntry(new ZipEntry(relativeName));

            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "ZipFile.ErrorCreatingZip"), e);
    } finally {
        try {
            if (in != null) {
                // Close the current file input stream
                in.close();
            }
            if (out != null) {
                // Close the ZipOutPutStream
                out.flush();
                out.closeEntry();
                out.close();
            }
            if (buff != null) {
                buff.close();
            }
            if (dest != null) {
                dest.close();
            }
            // Delete Temp File
            if (tempFile != null) {
                tempFile.delete();
            }
            fileSet = null;

        } catch (Exception e) { /* Ignore */
        }
    }

}

From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java

/**
 * Process the access request for a download (not CHS private docs).
 *
 * @param req//w w  w . j av a  2 s  . co  m
 * @param res
 * @param ref
 * @param copyrightAcceptedRefs
 * @throws PermissionException
 * @throws IdUnusedException
 * @throws ServerOverloadException
 * @throws CopyrightException
 */
protected void handleAccessDownload(HttpServletRequest req, HttpServletResponse res, Reference ref,
        Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException,
        EntityAccessOverloadException, EntityCopyrightException {
    if (DOWNLOAD_ALL_SUBMISSIONS_QUESTION.equals(ref.getSubType())) {
        // the file name has assessment_question.zip
        String[] outerParts = StringUtil.split(ref.getId(), ".");
        String[] parts = StringUtil.split(outerParts[0], "_");

        // assessment
        Assessment assessment = this.assessmentService.getAssessment(parts[0]);
        if (assessment == null) {
            M_log.warn("handleAccessDownload: invalid assessment id: " + parts[0]);
            return;
        }

        // check that this is not a formal course evaluation
        if (assessment.getFormalCourseEval()) {
            throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), "access",
                    ref.getReference());
        }

        // question
        Question question = assessment.getParts().getQuestion(parts[1]);
        if (question == null) {
            M_log.warn("handleAccessDownload: invalid question id: " + parts[1]);
            return;
        }

        String contentType = (String) ref.getProperties().get(ResourceProperties.PROP_CONTENT_TYPE);
        String disposition = "attachment; filename=\"" + (String) ref.getProperties().get("DAV:displayname")
                + "\"";

        OutputStream out = null;
        ZipOutputStream zip = null;
        try {
            res.setContentType(contentType);
            res.addHeader("Content-Disposition", disposition);

            out = res.getOutputStream();
            zip = new ZipOutputStream(out);

            this.submissionService.zipSubmissionsQuestion(zip, assessment, question);

            zip.flush();
        } catch (Throwable e) {
            M_log.warn("zipping: ", e);
        } finally {
            if (zip != null) {
                try {
                    zip.close();
                } catch (Throwable e) {
                    M_log.warn("closing zip: " + e.toString());
                }
            }
        }

        // track event
        this.eventTrackingService
                .post(this.eventTrackingService.newEvent(MnemeService.DOWNLOAD_SQ, ref.getReference(), false));
    } else if (EXPORT_SUMMARY.equals(ref.getSubType())) {
        // the file name has assessment_question.zip
        String[] outerParts = StringUtil.split(ref.getId(), ".");
        String[] parts = StringUtil.split(outerParts[0], "_");

        // assessment
        Assessment assessment = this.assessmentService.getAssessment(parts[0]);

        if (assessment == null) {
            M_log.warn("handleAccessDownload: invalid assessment id: " + parts[0]);
            return;
        }

        // check that this is not a formal course evaluation
        if (assessment.getFormalCourseEval()) {
            throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), "access",
                    ref.getReference());
        }

        OutputStream out = null;
        try {
            HSSFWorkbook wb = new HSSFWorkbook();

            if (createResponsesSheet(wb, assessment) != null) {
                String contentType = (String) ref.getProperties().get(ResourceProperties.PROP_CONTENT_TYPE);
                String disposition = "attachment; filename=\""
                        + (String) ref.getProperties().get("DAV:displayname") + "\"";
                res.setContentType(contentType);
                res.addHeader("Content-Disposition", disposition);

                out = res.getOutputStream();
                wb.write(out);
                out.flush();
            } else {
                res.setContentType("text/plain; charset=UTF-8");
                out = res.getOutputStream();
                String msg = this.messages.getFormattedMessage("nosub_msg", null);
                out.write(msg.getBytes());
                out.flush();
            }
        } catch (Throwable e) {
            M_log.warn("summary spreadsheet: ", e);
        } finally {

        }

        // track event
        //this.eventTrackingService.post(this.eventTrackingService.newEvent(MnemeService.DOWNLOAD_SQ, ref.getReference(), false));
    } else if (ITEM_ANALYSIS.equals(ref.getSubType())) {
        // the file name has assessment_question.zip
        String[] outerParts = StringUtil.split(ref.getId(), ".");
        String[] parts = StringUtil.split(outerParts[0], "_");

        // assessment
        Assessment assessment = this.assessmentService.getAssessment(parts[0]);

        if (assessment == null) {
            M_log.warn("handleAccessDownload: invalid assessment id: " + parts[0]);
            return;
        }

        // check that this is not a formal course evaluation
        if (assessment.getFormalCourseEval()) {
            throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), "access",
                    ref.getReference());
        }

        OutputStream out = null;
        try {
            HSSFWorkbook wb = new HSSFWorkbook();

            if (createItemAnalysisSheet(wb, assessment) != null) {
                String contentType = (String) ref.getProperties().get(ResourceProperties.PROP_CONTENT_TYPE);
                String disposition = "attachment; filename=\""
                        + (String) ref.getProperties().get("DAV:displayname") + "\"";
                res.setContentType(contentType);
                res.addHeader("Content-Disposition", disposition);

                out = res.getOutputStream();
                wb.write(out);
                out.flush();
            } else {
                res.setContentType("text/plain; charset=UTF-8");
                out = res.getOutputStream();
                String msg = this.messages.getFormattedMessage("nosub_msg", null);
                out.write(msg.getBytes());
                out.flush();
            }
        } catch (Throwable e) {
            M_log.warn("summary spreadsheet: ", e);
        } finally {

        }

        // track event
        //this.eventTrackingService.post(this.eventTrackingService.newEvent(MnemeService.DOWNLOAD_SQ, ref.getReference(), false));
    } else if (ASMT_STATS.equals(ref.getSubType())) {
        // the file name has assessment_question.zip
        String[] outerParts = StringUtil.split(ref.getId(), ".");
        String[] parts = StringUtil.split(outerParts[0], "_");

        // assessment
        Assessment assessment = this.assessmentService.getAssessment(parts[0]);

        if (assessment == null) {
            M_log.warn("handleAccessDownload: invalid assessment id: " + parts[0]);
            return;
        }

        // check that this is not a formal course evaluation
        if (assessment.getFormalCourseEval()) {
            throw new EntityPermissionException(sessionManager.getCurrentSessionUserId(), "access",
                    ref.getReference());
        }

        List<Submission> submissions = this.submissionService.findAssessmentSubmissions(assessment,
                SubmissionService.FindAssessmentSubmissionsSort.userName_a, Boolean.FALSE, null, null, null,
                null);

        OutputStream out = null;
        try {
            HSSFWorkbook wb = new HSSFWorkbook();

            if (createAsmtStatsSheet(wb, submissions) != null) {
                String contentType = (String) ref.getProperties().get(ResourceProperties.PROP_CONTENT_TYPE);
                String disposition = "attachment; filename=\""
                        + (String) ref.getProperties().get("DAV:displayname") + "\"";
                res.setContentType(contentType);
                res.addHeader("Content-Disposition", disposition);

                out = res.getOutputStream();
                wb.write(out);
                out.flush();
            } else {
                res.setContentType("text/plain; charset=UTF-8");
                out = res.getOutputStream();
                String msg = this.messages.getFormattedMessage("nosub_msg", null);
                out.write(msg.getBytes());
                out.flush();
            }
        } catch (Throwable e) {
            M_log.warn("summary spreadsheet: ", e);
        } finally {

        }

        // track event
        //this.eventTrackingService.post(this.eventTrackingService.newEvent(MnemeService.DOWNLOAD_SQ, ref.getReference(), false));
    } else if (ASMT_CERT.equals(ref.getSubType())) {
        StringBuilder contents = new StringBuilder();
        BufferedReader input = null;
        String message = null;
        InputStream inputStream = null;

        try {
            inputStream = AttachmentServiceImpl.class.getClassLoader().getResourceAsStream("cert.html");

            input = new BufferedReader(new InputStreamReader(inputStream));

            String line = null;
            String siteId = ref.getContext();

            while ((line = input.readLine()) != null) {
                if (line.contains(".png") || line.contains(".jpg") || line.contains(".gif")
                        || line.contains(".bmp")) {
                    line = adjustImagePath(line, siteId);
                }
                contents.append(line);
            }

            message = contents.toString();
            String subId = ref.getId();

            if (subId != null) {
                Submission submission = this.submissionService.getSubmission(subId);
                if (submission != null) {
                    String userId = submission.getUserId();
                    if (userId != null) {
                        try {
                            User user = this.userDirectoryService.getUser(userId);
                            message = message.replace("student.name",
                                    user.getFirstName() + " " + user.getLastName());
                        } catch (UserNotDefinedException e) {
                            M_log.warn("handleAccessDownload: " + e.toString());
                        }
                    }
                    message = message.replace("student.score",
                            String.valueOf(submission.getTotalScore().floatValue()));
                    Assessment assmt = submission.getAssessment();
                    message = message.replace("test.points",
                            String.valueOf(assmt.getParts().getTotalPoints().floatValue()));
                    message = message.replace("test.title", assmt.getTitle());
                    String siteTitle = null;
                    try {
                        Site site = this.siteService.getSite(siteId);
                        siteTitle = site.getTitle();
                    } catch (IdUnusedException e) {
                    }
                    message = message.replace("course.title", siteTitle);
                    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
                    Date date = new Date();
                    message = message.replace("today.date", dateFormat.format(date));
                }
            }
            OutputStream out = null;

            try {
                res.setContentType("text/html; charset=UTF-8");
                out = res.getOutputStream();
                out.write(message.getBytes());
                out.flush();

            } catch (Throwable e) {
                M_log.warn("view certificate: ", e);
            } finally {

            }
        } catch (Exception e) {
            M_log.warn("Error in handleAccessDownload", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {

                }
            }
        }

        // track event
        // this.eventTrackingService.post(this.eventTrackingService.newEvent(MnemeService.DOWNLOAD_SQ, ref.getReference(), false));
    } else if (ASMT_EXPORT.equals(ref.getSubType())) {
        String[] outerParts = StringUtil.split(ref.getReference(), "/");

        ZipOutputStream zip = null;
        try {
            String disposition = "attachment; filename=\"" + (String) ref.getProperties().get("DAV:displayname")
                    + "\"";

            OutputStream out = null;

            res.setContentType("application/zip");
            res.addHeader("Content-Disposition", disposition);

            out = res.getOutputStream();
            zip = new ZipOutputStream(out);

            String values = outerParts[outerParts.length - 1];
            values = values.replace(".zip", "");
            String[] ids = StringUtil.split(values, "+");

            this.assessmentService.exportAssessments(ref.getContext(), ids, zip);

            zip.flush();
        } catch (Throwable e) {
            M_log.warn("zipping: ", e);
        } finally {
            if (zip != null) {
                try {
                    zip.close();
                } catch (Throwable e) {
                    M_log.warn("closing zip: " + e.toString());
                }
            }
        }
    } else {
        M_log.warn("handleAccessDownload: unknown request: " + ref.getReference());
    }
}