Example usage for java.util.zip ZipOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing the contents of the ZIP output stream without closing the underlying stream.

Usage

From source file:org.sakaiproject.assignment.impl.AssignmentServiceTest.java

protected void zipWithFlushing(boolean flushing) {
    String assignmentTitle = "Test Assignment Title";

    try {//from   w  w w. jav a  2s .  c  o  m
        ZipOutputStream out = new ZipOutputStream(new ByteArrayOutputStream());

        // create the folder structor - named after the assignment's title
        String root = assignmentTitle + Entity.SEPARATOR;

        // submission text of size 2KB
        String submittedText = generateBigTestString(2);

        // Create the ZIP file
        String submittersName = "";
        for (int count = 0; count < userNumber; count++) {
            submittersName = root;
            String submittersString = "test user " + count;

            if (StringUtil.trimToNull(submittersString) != null) {
                submittersName = submittersName.concat(StringUtil.trimToNull(submittersString));

                try {
                    submittersName = submittersName.concat("/");
                    // create the folder structure - named after the submitter's name
                    // create the text file only when a text submission is allowed
                    String entryName = submittersName + submittersString + "_submissionText.html";
                    ZipEntry textEntry = new ZipEntry(entryName);
                    out.putNextEntry(textEntry);
                    out.write(submittedText.getBytes());
                    out.closeEntry();

                    // create the attachment file(s)
                    // buffered stream input
                    InputStream content = new ByteArrayInputStream(bigAttachmentContentString.getBytes());
                    byte data[] = new byte[1024 * 10];
                    BufferedInputStream bContent = new BufferedInputStream(content, data.length);

                    ZipEntry attachmentEntry = new ZipEntry(submittersName + "Test Attachment");
                    out.putNextEntry(attachmentEntry);
                    int bCount = -1;
                    while ((bCount = bContent.read(data, 0, data.length)) != -1) {
                        out.write(data, 0, bCount);
                    }
                    out.closeEntry();
                    content.close();

                    // flush or not
                    if (flushing) {
                        out.flush();
                    }
                } catch (IOException e) {
                    log.debug(this + ": --IOException: Problem in creating the attachment file: submittersName="
                            + submittersName + " attachment reference=" + attachmentReference);
                }
            }
        } // for

        // clean up
        out.finish();
        out.close();
    } catch (IOException e) {
        log.debug(this + ": --IOException unable to create the zip file for assignment " + assignmentTitle);
    }
}

From source file:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java

private File createDefaultTheme(String[] themePaths, String[] filterPaths) {
    try {//from  w  w w. j a v a2  s.c  om
        @SuppressWarnings("unchecked")
        Set<String> libs = servletContext.getResourcePaths("/WEB-INF/lib");
        Set<String> zipResources = new HashSet<String>();
        File back = File.createTempFile("devproof-defaulttheme-", ".zip");
        FileOutputStream fos = new FileOutputStream(back);
        ZipOutputStream zos = new ZipOutputStream(fos);
        if (libs.isEmpty()) {
            // development variant
            Resource root[] = applicationContext.getResources("classpath*:/");
            for (String ext : ThemeConstants.ALLOWED_THEME_EXT) {
                for (String themePath : themePaths) {
                    final Resource resources[];
                    if (themePath.endsWith("/")) {
                        resources = applicationContext.getResources("classpath*:" + themePath + "**/*" + ext);
                    } else {
                        resources = applicationContext.getResources("classpath*:" + themePath + ext);
                    }
                    for (Resource r : resources) {
                        String zipPath = getZipPath(root, r);
                        if (zipPath != null && !isFiltered(null, filterPaths, zipPath)
                                && !zipResources.contains(zipPath)) {
                            zipResources.add(zipPath);
                            ZipEntry ze = new ZipEntry(zipPath);
                            zos.putNextEntry(ze);
                            InputStream is = r.getInputStream();
                            byte[] file = new byte[is.available()];
                            is.read(file);
                            is.close();
                            zos.write(file);
                            zos.closeEntry();
                        }
                    }
                }
            }
        } else {
            // prod variant
            for (String lib : libs) {
                URL url = servletContext.getResource(lib);
                JarFile file = new JarFile(url.getFile());
                Enumeration<JarEntry> entries = file.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    if (!isFiltered(themePaths, filterPaths, jarEntry.getName())
                            && !zipResources.contains(jarEntry.getName())) {
                        zipResources.add(jarEntry.getName());
                        ZipEntry ze = new ZipEntry(jarEntry.getName());
                        InputStream is = file.getInputStream(jarEntry);
                        byte[] content = new byte[is.available()];
                        is.read(content);
                        is.close();
                        zos.putNextEntry(ze);
                        zos.write(content);
                        zos.closeEntry();
                    }
                }
            }
        }
        zos.finish();
        zos.close();
        fos.close();
        return back;
    } catch (FileNotFoundException e) {
        logger.error("Unknown: ", e);
    } catch (IOException e) {
        logger.error("Unknown: ", e);
    }
    return null;
}

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

/**
 * JSON ??//from w w w . j  av a2  s  .co m
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeJson(String name, String suffix) {

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

    try {

        zos.putNextEntry(entry);
        zos.write("[".getBytes("UTF-8"));

        for (City city : cities) {

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

            if (pc == null) {
                continue;
            }

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

                if (0 < cnt) {
                    zos.write(",".getBytes("UTF-8"));
                }
                zos.write(json.getBytes("UTF-8"));
                ++cnt;
            }
        }

        zos.write("]".getBytes("UTF-8"));
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_json.zip");
        log.info("count: " + cnt);

    } catch (IOException e) {
        log.log(Level.WARNING, "", 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;// w w  w  .ja  va  2 s.c  o m

    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:org.jahia.services.importexport.ImportExportBaseService.java

@Override
public void exportSites(OutputStream outputStream, Map<String, Object> params, List<JCRSiteNode> sites)
        throws RepositoryException, IOException, SAXException, TransformerException {

    logger.info("Sites " + sites + " export started");
    long startSitesExportTime = System.currentTimeMillis();
    String serverDirectory = (String) params.get(SERVER_DIRECTORY);
    ZipOutputStream zout = getZipOutputStream(outputStream, serverDirectory);
    ZipEntry anEntry = new ZipEntry(EXPORT_PROPERTIES);
    zout.putNextEntry(anEntry);//from w w  w . j  av a2s .  com
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(zout));
    bw.write("JahiaRelease = " + Jahia.getReleaseNumber() + "\n");
    bw.write("Patch = " + Jahia.getPatchNumber() + "\n");
    bw.write("BuildNumber = " + Jahia.getBuildNumber() + "\n");
    bw.write("ExportDate = " + new SimpleDateFormat(ImportExportService.DATE_FORMAT).format(new Date()) + "\n");
    bw.flush();

    Set<String> externalReferences = new HashSet<>();

    for (JCRSiteNode jahiaSite : sites) {
        long startSiteExportTime = System.currentTimeMillis();
        logger.info("Exporting site internal nodes " + jahiaSite.getName() + " content started");
        if (serverDirectory == null) {
            anEntry = new ZipEntry(jahiaSite.getSiteKey() + ".zip");
            zout.putNextEntry(anEntry);

            exportSite(jahiaSite, zout, externalReferences, params, null);
        } else {
            exportSite(jahiaSite, zout, externalReferences, params,
                    serverDirectory + "/" + jahiaSite.getSiteKey());
        }
        logger.info("Exporting site internal nodes {} ended in {} seconds", jahiaSite.getName(),
                getDuration(startSiteExportTime));
    }

    JCRSessionWrapper session = jcrStoreService.getSessionFactory().getCurrentUserSession();

    if (params.containsKey(INCLUDE_USERS)) {
        // export users
        ZipOutputStream zzout;
        if (serverDirectory == null) {
            zout.putNextEntry(new ZipEntry("users.zip"));
            zzout = getZipOutputStream(zout, null);
        } else {
            zzout = getZipOutputStream(zout, serverDirectory + "/users");
        }

        try {
            logger.info("Exporting Users Started");
            exportNodesWithBinaries(session.getRootNode(), Collections.singleton(session.getNode("/users")),
                    zzout, defaultExportNodeTypesToIgnore, externalReferences, params, true);
            logger.info("Exporting Users Ended");
        } catch (IOException e) {
            logger.warn("Cannot export due to some IO exception :" + e.getMessage());
        } catch (Exception e) {
            logger.error("Cannot export Users", e);
        }
        zzout.finish();
    }
    if (params.containsKey(INCLUDE_ROLES)) {
        // export roles
        ZipOutputStream zzout;
        if (serverDirectory == null) {
            zout.putNextEntry(new ZipEntry("roles.zip"));
            zzout = getZipOutputStream(zout, null);
        } else {
            zzout = getZipOutputStream(zout, serverDirectory + "/roles");
        }

        try {
            logger.info("Exporting Roles Started");
            exportNodesWithBinaries(session.getRootNode(), Collections.singleton(session.getNode("/roles")),
                    zzout, defaultExportNodeTypesToIgnore, externalReferences, params, true);
            logger.info("Exporting Roles Ended");
        } catch (Exception e) {
            logger.error("Cannot export roles", e);
        }
        zzout.finish();
    }
    if (params.containsKey(INCLUDE_MOUNTS) && session.nodeExists("/mounts")) {
        JCRNodeWrapper mounts = session.getNode("/mounts");
        if (mounts.hasNodes()) {
            // export mounts
            zout.putNextEntry(new ZipEntry("mounts.zip"));
            ZipOutputStream zzout = new ZipOutputStream(zout);

            try {
                logger.info("Exporting Mount points Started");
                exportNodesWithBinaries(session.getRootNode(), Collections.singleton(mounts), zzout,
                        defaultExportNodeTypesToIgnore, externalReferences, params, true);
                logger.info("Exporting Mount points Ended");
            } catch (Exception e) {
                logger.error("Cannot export mount points", e);
            }
            zzout.finish();
        }
    }

    Set<JCRNodeWrapper> refs = new HashSet<JCRNodeWrapper>();
    for (String reference : externalReferences) {
        JCRNodeWrapper node = session.getNodeByUUID(reference);
        if (!defaultExportNodeTypesToIgnore.contains(node.getPrimaryNodeTypeName())) {
            refs.add(node);
        }
    }
    if (!refs.isEmpty()) {
        zout.putNextEntry(new ZipEntry("references.zip"));
        ZipOutputStream zzout = getZipOutputStream(zout, serverDirectory + "/references.zip");
        try {
            logger.info("Exporting References Started");
            exportNodesWithBinaries(session.getRootNode(), refs, zzout, defaultExportNodeTypesToIgnore,
                    externalReferences, params, true);
            logger.info("Exporting References Ended");
        } catch (Exception e) {
            logger.error("Cannot export References", e);
        }
        zzout.finish();
    }
    zout.finish();

    logger.info("Total Sites {} export ended in {} seconds", sites, getDuration(startSitesExportTime));
}

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

public void storeJsonArea() {

    LinkedList<City> cities = getCities();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;//from w w w.ja  va 2  s  .  c om

    try {

        for (City city : cities) {

            ParentChild data = getParentChildDao().get(city.getCode());

            if (data == null) {
                continue;
            }

            SortedSet<String> children = new TreeSet<String>();
            String json = toJsonAdd1s(data, children);
            ZipEntry entry = new ZipEntry(city.getCode() + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;

            for (String add1 : children) {

                json = toJsonAdd2s(data, add1);
                entry = new ZipEntry(city.getCode() + "-" + toHex(add1) + ".json");
                entry.setTime(timestamp);
                zos.putNextEntry(entry);
                zos.write(json.getBytes("UTF-8"));
                zos.closeEntry();
                ++cnt;
            }
        }

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

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

    return;
}

From source file:org.joget.apps.app.service.AppServiceImpl.java

/**
 * Export an app version in ZIP format into an OutputStream
 * @param appId/* w w w . jav  a2  s  . 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:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal
 * the specified {@code newSequencePath}. Works by creating a temp file and renaming
 *
 * @param targetFile      A .genome file, in zip format
 * @param newSequencePath/*from   ww w  .j  a  v  a  2s . co  m*/
 * @return boolean indicating success or failure.
 * @throws IOException
 */
static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException {

    ZipFile targetZipFile = new ZipFile(targetFile);
    boolean success = false;

    File tmpZipFile = File.createTempFile("tmpGenome", ".zip");
    ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);

    InputStream propertyInputStream = null;
    ZipOutputStream zipOutputStream = null;
    Properties inputProperties = new Properties();

    try {
        propertyInputStream = targetZipFile.getInputStream(propEntry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream));

        //Copy over property.txt, only replacing a few properties
        inputProperties.load(reader);
        inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath);
        inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString());

        ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
        PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));

        inputProperties.store(propertyFileWriter, null);

        propertyFileWriter.flush();
        byte[] newPropertyBytes = propertyBytes.toByteArray();

        Enumeration<? extends ZipEntry> entries = targetZipFile.entries();
        zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile));
        while (entries.hasMoreElements()) {
            ZipEntry curEntry = entries.nextElement();
            ZipEntry writeEntry = null;

            if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                writeEntry.setSize(newPropertyBytes.length);
                zipOutputStream.putNextEntry(writeEntry);
                zipOutputStream.write(newPropertyBytes);
                continue;
            } else {
                //Because the compressed size can vary,
                //we generate a new ZipEntry and copy some attributes
                writeEntry = new ZipEntry(curEntry.getName());
                writeEntry.setSize(curEntry.getSize());
                writeEntry.setComment(curEntry.getComment());
                writeEntry.setTime(curEntry.getTime());
            }

            zipOutputStream.putNextEntry(writeEntry);
            InputStream tmpIS = null;
            try {
                tmpIS = targetZipFile.getInputStream(writeEntry);
                int bytes = IOUtils.copy(tmpIS, zipOutputStream);
                log.debug(bytes + " bytes written to " + targetFile);
            } finally {
                if (tmpIS != null)
                    tmpIS.close();
            }

        }
    } catch (Exception e) {
        tmpZipFile.delete();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (propertyInputStream != null)
            propertyInputStream.close();
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.finish();
            zipOutputStream.close();
        }
        zipOutputStream = null;
        System.gc();
        success = true;
    }

    //This is a hack. I don't know why it's necessary,
    //but for some reason the output zip file seems to be corrupt
    //at least when called from GenomeManager.refreshArchive
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        //
    }

    //Rename tmp file
    if (success) {
        targetFile.delete();
        FileUtils.copyFile(tmpZipFile, targetFile);
        success = targetFile.exists();
        tmpZipFile.delete();
    }
    return success;
}

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;/*  w w  w  .jav  a 2  s. c  om*/

    // 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:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * IME??/*www . ja va  2 s.c  om*/
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeIme(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    SortedMap<String, Pref> prefs = getPrefMap();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_ime_dic.txt");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = "\t".getBytes("MS932");
        byte[] sonota = "\t?????".getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

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

            if (pc == null) {
                continue;
            }

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

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

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

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

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