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:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os)
        throws IOException {
    int subsystemStartLevel = -1;
    ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF");
    try {//from   w  w w .ja  va  2 s  .  c om
        os.putNextEntry(ze);

        Manifest mf = new Manifest();
        Attributes attributes = mf.getMainAttributes();
        attributes.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value
        attributes.putValue("Subsystem-SymbolicName", feature.getName());
        attributes.putValue("Subsystem-Version", "1"); // Version must be an integer (cannot be a long), TODO better idea?
        attributes.putValue("Subsystem-Type", feature.getType());
        for (Section section : feature.getAdditionalSections("subsystem-manifest")) {
            String sl = section.getAttributes().get("startLevel");
            try {
                subsystemStartLevel = Integer.parseInt(sl);
            } catch (NumberFormatException nfe) {
                // Not a valid start level
            }

            BufferedReader br = new BufferedReader(new StringReader(section.getContents()));
            String line = null;
            while ((line = br.readLine()) != null) {
                int idx = line.indexOf(':');
                if (idx > 0) {
                    String key = line.substring(0, idx);
                    String value;
                    idx++;
                    if (line.length() > idx)
                        value = line.substring(idx);
                    else
                        value = "";
                    attributes.putValue(key.trim(), value.trim());
                }
            }
        }
        mf.write(os);
    } finally {
        os.closeEntry();
    }

    return subsystemStartLevel;
}

From source file:org.bonitasoft.engine.test.APITestUtil.java

protected byte[] createTestPageContent(final String pageName, final String displayName,
        final String description) throws Exception {
    try {/*from   w ww.j  ava  2s  .c om*/
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ZipOutputStream zos = new ZipOutputStream(baos);
        zos.putNextEntry(new ZipEntry("Index.groovy"));
        zos.write("return \"\";".getBytes());

        zos.putNextEntry(new ZipEntry("page.properties"));
        final StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("name=");
        stringBuilder.append(pageName);
        stringBuilder.append("\n");
        stringBuilder.append("displayName=");
        stringBuilder.append(displayName);
        stringBuilder.append("\n");
        stringBuilder.append("description=");
        stringBuilder.append(description);
        stringBuilder.append("\n");
        zos.write(stringBuilder.toString().getBytes());

        zos.closeEntry();
        return baos.toByteArray();
    } catch (final IOException e) {
        throw new BonitaException(e);
    }
}

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

public void storeJsonPrefCity() {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;/*from  w  w  w .j av  a  2s .  com*/

    try {

        ParentChild data = getParentChildDao().get("prefs");
        String json = toJsonPrefs(data);
        ZipEntry entry = new ZipEntry("prefs.json");
        entry.setTime(timestamp);
        zos.putNextEntry(entry);
        zos.write(json.getBytes("UTF-8"));
        zos.closeEntry();
        ++cnt;

        for (Pref pref : getPrefs()) {

            data = getParentChildDao().get(pref.getCode());

            if (data == null) {
                continue;
            }

            json = toJsonCities(data);
            entry = new ZipEntry(pref.getCode() + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;
        }

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

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

From source file:com.ichi2.libanki.Media.java

/**
 * Unlike python, our temp zip file will be on disk instead of in memory. This avoids storing
 * potentially large files in memory which is not feasible with Android's limited heap space.
 * <p>//from  w  w  w.j  av  a  2  s  .  co m
 * Notes:
 * <p>
 * - The maximum size of the changes zip is decided by the constant SYNC_ZIP_SIZE. If a media file exceeds this
 * limit, only that file (in full) will be zipped to be sent to the server.
 * <p>
 * - This method will be repeatedly called from MediaSyncer until there are no more files (marked "dirty" in the DB)
 * to send.
 * <p>
 * - Since AnkiDroid avoids scanning the media folder on every sync, it is possible for a file to be marked as a
 * new addition but actually have been deleted (e.g., with a file manager). In this case we skip over the file
 * and mark it as removed in the database. (This behaviour differs from the desktop client).
 * <p>
 */
public Pair<File, List<String>> mediaChangesZip() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));
    Cursor cur = null;
    try {
        ZipOutputStream z = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        z.setMethod(ZipOutputStream.DEFLATED);

        List<String> fnames = new ArrayList<String>();
        // meta is a list of (fname, zipname), where zipname of null is a deleted file
        // NOTE: In python, meta is a list of tuples that then gets serialized into json and added
        // to the zip as a string. In our version, we use JSON objects from the start to avoid the
        // serialization step. Instead of a list of tuples, we use JSONArrays of JSONArrays.
        JSONArray meta = new JSONArray();
        int sz = 0;
        byte buffer[] = new byte[2048];
        cur = mDb.getDatabase()
                .rawQuery("select fname, csum from media where dirty=1 limit " + Consts.SYNC_ZIP_COUNT, null);

        for (int c = 0; cur.moveToNext(); c++) {
            String fname = cur.getString(0);
            String csum = cur.getString(1);
            fnames.add(fname);
            String normname = HtmlUtil.nfcNormalized(fname);

            if (!TextUtils.isEmpty(csum)) {
                try {
                    mCol.log("+media zip " + fname);
                    File file = new File(dir(), fname);
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
                    z.putNextEntry(new ZipEntry(Integer.toString(c)));
                    int count = 0;
                    while ((count = bis.read(buffer, 0, 2048)) != -1) {
                        z.write(buffer, 0, count);
                    }
                    z.closeEntry();
                    bis.close();
                    meta.put(new JSONArray().put(normname).put(Integer.toString(c)));
                    sz += file.length();
                } catch (FileNotFoundException e) {
                    // A file has been marked as added but no longer exists in the media directory.
                    // Skip over it and mark it as removed in the db.
                    removeFile(fname);
                }
            } else {
                mCol.log("-media zip " + fname);
                meta.put(new JSONArray().put(normname).put(""));
            }
            if (sz >= Consts.SYNC_ZIP_SIZE) {
                break;
            }
        }

        z.putNextEntry(new ZipEntry("_meta"));
        z.write(Utils.jsonToString(meta).getBytes());
        z.closeEntry();
        z.close();
        // Don't leave lingering temp files if the VM terminates.
        f.deleteOnExit();
        return new Pair<File, List<String>>(f, fnames);
    } catch (IOException e) {
        Timber.e("Failed to create media changes zip", e);
        throw new RuntimeException(e);
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.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 {// w w w.  j  a va2s .c om
        this.log.info("Esecuzione " + methodName + " in corso...");
        this.darsService.getOperatoreByPrincipal(bd);

        Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita);
        boolean eseguiRicerca = !setDomini.isEmpty();
        FrBD frBD = new FrBD(bd);
        FrFilter filter = frBD.newFilter();
        List<String> idDomini = new ArrayList<String>();
        List<Long> idsToExport = new ArrayList<Long>();
        idsToExport.add(idToExport);

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

            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
            if (eseguiRicerca) {
                filter.setIdFr(idsToExport);
                eseguiRicerca = eseguiRicerca && frBD.count(filter) > 0;
            }
        }
        String fileName = "Rendicontazione.zip";

        if (eseguiRicerca) {
            Fr fr = frBD.getFr(idToExport);
            fileName = "Rendicontazione_" + fr.getIur() + ".zip";
            ZipEntry frXml = new ZipEntry("fr.xml");
            zout.putNextEntry(frXml);
            zout.write(fr.getXml());
            zout.closeEntry();
        } else {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sui flussi 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.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;//ww  w .j  a  v a 2  s. com

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(),
                "Unable to send the mail because the mail-server (SMTP host) is not specified");
        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        protocol = "smtps";
    }

    props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
        authenticator = new Authenticator()
        {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(
                        StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), 
                        StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))
                    );
        }
        };
        */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        String email_address = StringUtil.environmentSubstitute(replyAddress);
        if (!Const.isEmpty(email_address)) {
            msg.setFrom(new InternetAddress(email_address));
        } else {
            throw new MessagingException("reply e-mail address is not filled in");
        }

        // Split the mail-address: space separated
        String destinations[] = StringUtil.environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);

        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }

        msg.setSubject(StringUtil.environmentSubstitute(subject));
        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }

        if (!onlySendComment) {
            messageText.append("Job:").append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append("Name       : ").append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append("Directory  : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append("JobEntry   : ").append(getName()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            Value date = new Value("date", new Date());
            messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append("Previous result:").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append("Job entry nr         : ").append(result.getEntryNr()).append(Const.CR);
            messageText.append("Errors               : ").append(result.getNrErrors()).append(Const.CR);
            messageText.append("Lines read           : ").append(result.getNrLinesRead()).append(Const.CR);
            messageText.append("Lines written        : ").append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append("Lines input          : ").append(result.getNrLinesInput()).append(Const.CR);
            messageText.append("Lines output         : ").append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append("Lines updated        : ").append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append("Script exit status   : ").append(result.getExitStatus()).append(Const.CR);
            messageText.append("Result               : ").append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson))
                || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) {
            messageText.append("Contact information :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson))
                    .append(Const.CR);
            messageText.append("Telephone number  : ").append(StringUtil.environmentSubstitute(contactPhone))
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append("Path to this job entry:").append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part
        part1.setText(messageText.toString());
        parts.addBodyPart(part1);
        if (includingFiles && result != null) {
            List resultFiles = result.getResultFilesList();
            if (resultFiles != null && resultFiles.size() > 0) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                        ResultFile resultFile = (ResultFile) iter.next();
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(fds.getName());
                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + StringUtil.environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                            ResultFile resultFile = (ResultFile) iter.next();

                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getURI());
                                zipOutputStream.putNextEntry(zipEntry);

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

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    //System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String[] exportSelectedMappings(String[] selectedMappings) {
    String[] cleanedSelectedMappings = cleanSelectedMappings(selectedMappings);
    String msg = "";
    String[] returnStr = new String[2];
    String path = null;//  w  w w. jav  a2s.c  o m

    try {
        byte[] buffer = new byte[1024];
        String sourceDirectory = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_MAPPINGS_FOLDER
                + File.separator;
        String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
                + File.separator;
        String suffix = ".mapping.json";
        String zipFile = tempFolderName + "exported-mappings_" + (new Date()).getTime() + ".zip";

        (new File(tempFolderName)).mkdirs();

        FileOutputStream fout = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(fout);
        File dir = new File(sourceDirectory);

        if (!dir.isDirectory()) {
            System.out.println(sourceDirectory + " is not a directory");
        } else {
            File[] files = dir.listFiles();
            String mappings = "";

            if (files.length == 0) {
                msg = Context.getMessageSourceService()
                        .getMessage("dhisconnector.exportMapping.noMappingsFound");
            } else {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith(suffix)) {
                        FileInputStream fin = new FileInputStream(files[i]);

                        mappings += files[i].getName() + "<:::>";
                        System.out.println("Compressing " + files[i].getName());
                        if (cleanedSelectedMappings.length == 0) {
                            copyToZip(buffer, zout, files, i, fin);
                        } else {
                            if (selectedMappingsIncludes(cleanedSelectedMappings, files[i].getName())) {
                                copyToZip(buffer, zout, files, i, fin);
                            }
                        }
                        msg = Context.getMessageSourceService()
                                .getMessage("dhisconnector.exportMapping.success");
                        zout.closeEntry();
                        fin.close();
                    }
                }
                if (mappings.split("<:::>").length == 0) {
                    msg = Context.getMessageSourceService()
                            .getMessage("dhisconnector.exportMapping.noMappingsFound");
                }
                path = zipFile;
            }
        }
        zout.close();
        System.out.println("Zip file has been created!");
    } catch (IOException e) {
        e.printStackTrace();
    }
    returnStr[0] = msg;
    returnStr[1] = path;
    return returnStr;
}

From source file:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException //ww  w . j a v a 2s.co m
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

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

                zipOutputStream.closeEntry();

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

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:com.migo.utils.GenUtils.java

/**
 * ??/*from   w w w  . j a va  2s . com*/
 */
public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns,
        ZipOutputStream zip) {
    //??
    Configuration config = getConfig();

    //?
    TableEntity tableEntity = new TableEntity();
    tableEntity.setTableName(table.get("tableName"));
    tableEntity.setComments(table.get("tableComment"));
    //????Java??
    String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
    tableEntity.setClassName(className);
    tableEntity.setClassname(StringUtils.uncapitalize(className));

    //?
    List<ColumnEntity> columsList = new ArrayList<>();
    for (Map<String, String> column : columns) {
        ColumnEntity columnEntity = new ColumnEntity();
        columnEntity.setColumnName(column.get("columnName"));
        columnEntity.setDataType(column.get("dataType"));
        columnEntity.setComments(column.get("columnComment"));
        columnEntity.setExtra(column.get("extra"));

        //????Java??
        String attrName = columnToJava(columnEntity.getColumnName());
        columnEntity.setAttrName(attrName);
        columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

        //???Java
        String attrType = config.getString(columnEntity.getDataType(), "unknowType");
        columnEntity.setAttrType(attrType);

        //?
        if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
            tableEntity.setPk(columnEntity);
        }

        columsList.add(columnEntity);
    }
    tableEntity.setColumns(columsList);

    //
    if (tableEntity.getPk() == null) {
        tableEntity.setPk(tableEntity.getColumns().get(0));
    }

    //velocity?
    Properties prop = new Properties();
    prop.put("file.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(prop);

    //???
    Map<String, Object> map = new HashMap<>();
    map.put("tableName", tableEntity.getTableName());
    map.put("comments", tableEntity.getComments());
    map.put("pk", tableEntity.getPk());
    map.put("className", tableEntity.getClassName());
    map.put("classname", tableEntity.getClassname());
    map.put("pathName", tableEntity.getClassname().toLowerCase());
    map.put("columns", tableEntity.getColumns());
    map.put("package", config.getString("package"));
    map.put("author", config.getString("author"));
    map.put("email", config.getString("email"));
    map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
    VelocityContext context = new VelocityContext(map);

    //??
    List<String> templates = getTemplates();
    for (String template : templates) {
        //?
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, "UTF-8");
        tpl.merge(context, sw);

        try {
            //zip
            zip.putNextEntry(new ZipEntry(
                    getFileName(template, tableEntity.getClassName(), config.getString("package"))));
            IOUtils.write(sw.toString(), zip, "UTF-8");
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        } catch (IOException e) {
            throw new RRException("???" + tableEntity.getTableName(), e);
        }
    }
}

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

public void storeJsonCorp() {

    LinkedList<City> cities = getCities();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;/*  w w  w.  j  av  a  2s  .  com*/

    try {

        for (City city : cities) {

            String key = city.getCode() + "c";
            ParentChild data = getParentChildDao().get(key);

            if (data == null) {
                continue;
            }

            String json = toJsonCorps(data);
            ZipEntry entry = new ZipEntry(key + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;
        }

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

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

    return;
}