Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

In this page you can find the example usage for java.io Writer close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:com.veight.mail.template.MailTemplateLocal.java

public String makeContent(String templateName, Map<String, String> root) {
    Writer out = null;
    try {/*  w w  w  . ja  v a 2  s  . c  om*/
        Template template = configuration.getTemplate(templateName);
        out = new StringWriter();
        template.process(root, out);

        out.flush();
        return out.toString();
    } catch (IOException | TemplateException ex) {
        logger.error("Fail to get content from freemaker. [mailTemplate={}][mail={}]", templateName, ex);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ex) {
                logger.error("Fail to close StringWriter.", ex);
            }
        }
    }
    return StringUtils.EMPTY;
}

From source file:com.glaf.mail.MailSenderImpl.java

public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception {
    if (StringUtils.isEmpty(mailMessage.getMessageId())) {
        mailMessage.setMessageId(UUID32.getUUID());
    }/* www.  jav a 2  s . c om*/

    mailHelper = new MxMailHelper();
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    if (StringUtils.isNotEmpty(mailMessage.getFrom())) {
        messageHelper.setFrom(mailMessage.getFrom());
        mailFrom = mailMessage.getFrom();
    } else {
        if (StringUtils.isEmpty(mailFrom)) {
            mailFrom = MailProperties.getString("mail.mailFrom");
        }
        messageHelper.setFrom(mailFrom);
    }

    logger.debug("mailFrom:" + mailFrom);

    if (mailMessage.getTo() != null) {
        messageHelper.setTo(mailMessage.getTo());
    }

    if (mailMessage.getCc() != null) {
        messageHelper.setCc(mailMessage.getCc());
    }

    if (mailMessage.getBcc() != null) {
        messageHelper.setBcc(mailMessage.getBcc());
    }

    if (mailMessage.getReplyTo() != null) {
        messageHelper.setReplyTo(mailMessage.getReplyTo());
    }

    String mailSubject = mailMessage.getSubject();
    if (mailSubject == null) {
        mailSubject = "";
    }

    if (mailSubject != null) {
        // mailSubject = MimeUtility.encodeText(new
        // String(mailSubject.getBytes(), encoding), encoding, "B");
        mailSubject = MimeUtility.encodeWord(mailSubject);
    }

    mimeMessage.setSubject(mailSubject);

    Map<String, Object> dataMap = mailMessage.getDataMap();
    if (dataMap == null) {
        dataMap = new java.util.HashMap<String, Object>();
    }

    String serviceUrl = SystemConfig.getServiceUrl();

    logger.debug("mailSubject:" + mailSubject);
    logger.debug("serviceUrl:" + serviceUrl);

    if (serviceUrl != null) {
        String loginUrl = serviceUrl + "/mx/login";
        String mainUrl = serviceUrl + "/mx/main";
        logger.debug("loginUrl:" + loginUrl);
        dataMap.put("loginUrl", loginUrl);
        dataMap.put("mainUrl", mainUrl);
    }

    mailMessage.setDataMap(dataMap);

    if (StringUtils.isEmpty(mailMessage.getContent())) {
        Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId());
        if (template != null) {
            String templateType = template.getTemplateType();
            logger.debug("templateType:" + templateType);
            // logger.debug("content:" + template.getContent());
            if (StringUtils.equals(templateType, "eml")) {
                if (template.getContent() != null) {
                    Mail m = mailHelper.getMail(template.getContent().getBytes());
                    String content = m.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        template.setContent(content);
                        try {
                            Writer writer = new StringWriter();
                            TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer);
                            String text = writer.toString();
                            writer.close();
                            writer = null;
                            mailMessage.setContent(text);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }
            } else {
                try {
                    String text = TemplateUtils.process(dataMap, template.getContent());
                    mailMessage.setContent(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    if (StringUtils.isNotEmpty(mailMessage.getContent())) {
        String text = mailMessage.getContent();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            String href = callbackUrl + "?messageId=" + mailMessage.getMessageId();
            text = mailHelper.embedCallbackScript(text, href);
            mailMessage.setContent(text);
            logger.debug(text);
            messageHelper.setText(text, true);
        }
        messageHelper.setText(text, true);
    }

    logger.debug("mail body:" + mailMessage.getContent());

    Collection<Object> files = mailMessage.getFiles();

    if (files != null && !files.isEmpty()) {
        Iterator<Object> iterator = files.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof java.io.File) {
                java.io.File file = (java.io.File) object;
                FileSystemResource resource = new FileSystemResource(file);
                String name = file.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, resource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataSource) {
                DataSource dataSource = (DataSource) object;
                String name = dataSource.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, dataSource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataFile) {
                DataFile dataFile = (DataFile) object;
                if (StringUtils.isNotEmpty(dataFile.getFilename())) {
                    String name = dataFile.getFilename();
                    name = MailTools.chineseStringToAscii(name);
                    InputStreamSource inputStreamSource = new MxMailInputSource(dataFile);
                    messageHelper.addAttachment(name, inputStreamSource);
                    logger.debug("add attachment:" + name);
                }
            }
        }
    }

    mimeMessage.setSentDate(new java.util.Date());

    javaMailSender.send(mimeMessage);

    logger.info("-----------------------------------------");
    logger.info("????");
    logger.info("-----------------------------------------");
}

From source file:hu.petabyte.redflags.engine.gear.export.FlagExporter.java

private void writeFile() throws IOException {
    File csvFile = new File(filename);
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"));
    for (ArrayList<String> row : grid) {
        for (String col : row) {
            if (null != col) {
                out.write(col);//from   ww  w. ja  v a 2 s  .  c om
            }
            out.write("\t");
        }
        out.write("\n");
    }
    out.flush();
    out.close();
}

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

public void writeCombination(Writer writer) {
    try {/* w w w  .  j av a2s .  c om*/
        try {
            writer.write("ID,outcome,\n");
            for (Entry<String, String> entry : this.combination.entrySet()) {
                writer.write(CSVFormatter.format(entry.getKey()) + "," + CSVFormatter.format(entry.getValue())
                        + ",\n");
            }
        } finally {
            writer.flush();
            writer.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected void createMetadataFile(FileObject metadataFile) throws InstantiationException,
        IllegalAccessException, UnsupportedEncodingException, FileSystemException, IOException {
    DesignMetadata metadata = createDefaultMetadata();
    Writer writer = new OutputStreamWriter(metadataFile.getContent().getOutputStream(),
            getManager().getFileEncoding());
    writer.write(DesignSyncManager.getXstream().toXML(metadata.getInfo()));
    writer.close();
}

From source file:com.polyvi.xface.extension.XExtensionManager.java

/**
 * ???umeng?/*from  w  w w.  ja v a 2  s  .c o m*/
 * 
 * @param e
 */
public void reportError(Exception e) {
    try {
        // ?Writer
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        printWriter.flush();
        writer.flush();
        String stackTrackInfo = writer.toString();
        printWriter.close();
        writer.close();
        MobclickAgent.reportError(mExtensionContext.getSystemContext().getContext(), stackTrackInfo);
    } catch (IOException ioE) {
        XLog.e(CLASS_NAME, ioE.getMessage());
    } catch (Exception genericE) {
        XLog.e(CLASS_NAME, genericE.getMessage());
    }
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testOutputStreamOpenWriteAutocloseFlush() throws Exception {
    final FileObject fo = openFileObject("out.txt");
    final Writer writer = openWriter(fo);
    try {/*from  w ww. j a  v  a2 s .  c o m*/
        writer.write("ghi");
        Thread.sleep(SLEEP_TIME);
        writer.flush();
        assertContentEquals(fo, "ghi");
    } finally {
        writer.close();
    }
    fo.close();
}

From source file:com.aurotech.workfront.sharepoint.dao.WorkfrontServiceDao.java

@SuppressWarnings("rawtypes")
private Object request(String path, Map<String, Object> params, Set<String> fields, String method,
        boolean callAPI) throws WorkfrontException {
    HttpURLConnection conn = null;
    try {/*  w ww . j  a  v a2s .c om*/
        String query = "";
        query = "sessionID=" + sessionID + "&method=" + method;
        if (params != null) {
            for (String key : params.keySet()) {
                Object val = params.get(key);
                if (val instanceof List) {
                    List lVal = (List) val;
                    for (Object obj : lVal) {
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                + URLEncoder.encode(String.valueOf(obj), "UTF-8");
                    }
                } else {
                    if (val instanceof Set) {
                        Set sVal = (Set) val;
                        for (Object obj : sVal) {
                            query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                    + URLEncoder.encode(String.valueOf(obj), "UTF-8");
                        }
                    } else {
                        query += "&" + URLEncoder.encode(key, "UTF-8") + "="
                                + URLEncoder.encode(String.valueOf(val), "UTF-8");
                    }
                }
            }
        }

        if (fields != null) {
            query += "&fields=";
            for (String field : fields) {
                query += URLEncoder.encode(field, "UTF-8") + ",";
            }
            query = query.substring(0, query.lastIndexOf(","));
        }

        conn = createConnection(hostname + (callAPI ? apiURL : "") + path, METH_POST);

        // Send request
        Writer out = new OutputStreamWriter(conn.getOutputStream());
        // logger.debug("Query: " + URLDecoder.decode(query));

        out.write(query);
        out.flush();
        out.close();

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = in.readLine()) != null) {
            response.append(line);
        }

        in.close();
        // Decode JSON
        JSONObject result = new JSONObject(response.toString());
        // Verify result
        if (result.has("error")) {
            throw new WorkfrontException(result.getJSONObject("error").getString("message"));
        } else if (!result.has("data") && callAPI) {
            throw new WorkfrontException("Invalid response from server");
        }

        // Manage the session
        if (path.equals(PATH_LOGIN)) {
            sessionID = result.getJSONObject("data").getString("sessionID");
        } else if (path.equals(PATH_LOGOUT)) {
            sessionID = null;
        }
        if (callAPI) {
            return result.get("data");
        }
        return result;
    } catch (Exception e) {
        logger.debug(e.getMessage(), e);

        if (conn == null) {
            throw new WorkfrontException("Unable to connect. Please check the server name");
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        StringBuilder response = new StringBuilder();
        String line;

        try {
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        JSONObject result;
        try {
            result = new JSONObject(response.toString());
            throw new WorkfrontException(result.getJSONObject("error").getString("message"));
        } catch (JSONException e1) {
            throw new WorkfrontException(response.toString());
        }

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.cloudera.sqoop.io.TestLobFile.java

private long[] writeClobFile(Path p, String codec, String... records) throws Exception {
    if (fs.exists(p)) {
        fs.delete(p, false);//from w w w. j  a v  a  2 s .  co m
    }

    // memorize the offsets of each record we write.
    long[] offsets = new long[records.length];

    // Create files with four entries per index segment.
    LobFile.Writer writer = LobFile.create(p, conf, true, codec, 4);

    int i = 0;
    for (String r : records) {
        offsets[i++] = writer.tell();
        Writer w = writer.writeClobRecord(r.length());
        w.write(r);
        w.close();
    }

    writer.close();
    return offsets;
}

From source file:com.google.glassware.NotifyServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Respond with OK and status 200 in a timely fashion to prevent redelivery
    response.setContentType("text/html");
    Writer writer = response.getWriter();
    writer.append("OK");
    writer.close();

    // Get the notification object from the request body (into a string so we
    // can log it)
    BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String notificationString = "";

    String responseStringForFaceDetection = null;
    // Count the lines as a very basic way to prevent Denial of Service attacks
    int lines = 0;
    String line;/*  ww w .ja  v a 2 s .  co m*/
    while ((line = notificationReader.readLine()) != null) {
        notificationString += line;
        lines++;

        // No notification would ever be this long. Something is very wrong.
        if (lines > 1000) {
            throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
        }
    }
    notificationReader.close();

    LOG.info("got raw notification " + notificationString);

    JsonFactory jsonFactory = new JacksonFactory();

    // If logging the payload is not as important, use
    // jacksonFactory.fromInputStream instead.
    Notification notification = jsonFactory.fromString(notificationString, Notification.class);

    LOG.info("Got a notification with ID: " + notification.getItemId());

    // Figure out the impacted user and get their credentials for API calls
    String userId = notification.getUserToken();
    Credential credential = AuthUtil.getCredential(userId);
    Mirror mirrorClient = MirrorClient.getMirror(credential);

    if (notification.getCollection().equals("locations")) {
        LOG.info("Notification of updated location");
        Mirror glass = MirrorClient.getMirror(credential);
        // item id is usually 'latest'
        Location location = glass.locations().get(notification.getItemId()).execute();

        LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude());
        MirrorClient.insertTimelineItem(credential, new TimelineItem()
                .setText("Java Quick Start says you are now at " + location.getLatitude() + " by "
                        + location.getLongitude())
                .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location)
                .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE"))));

        // This is a location notification. Ping the device with a timeline item
        // telling them where they are.
    } else if (notification.getCollection().equals("timeline")) {
        // Get the impacted timeline item
        TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute();
        LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId());

        // If it was a share, and contains a photo, update the photo's caption to
        // acknowledge that we got it.
        if (notification.getUserActions().contains(new UserAction().setType("SHARE"))
                && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) {
            String finalresponseForCard = null;

            String questionString = timelineItem.getText();
            if (!questionString.isEmpty()) {
                String[] questionStringArray = questionString.split(" ");

                LOG.info(timelineItem.getText() + " is the questions asked by the user");
                LOG.info("A picture was taken");

                if (questionString.toLowerCase().contains("search")
                        || questionString.toLowerCase().contains("tag")
                        || questionString.toLowerCase().contains("train")
                        || questionString.toLowerCase().contains("mark")
                        || questionString.toLowerCase().contains("recognize")
                        || questionString.toLowerCase().contains("what is")) {

                    //Fetching the image from the timeline
                    InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(),
                            timelineItem.getAttachments().get(0));

                    //converting the image to Base64
                    Base64 base64Object = new Base64(false);
                    String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray()
                    // byteArrayForOutputStream.close();
                    encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1");

                    //sending the API request
                    LOG.info("Sending request to API");
                    //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call
                    try {
                        String urlParameters = "";
                        String tag = "";

                        if (questionString.toLowerCase().contains("tag")
                                || questionString.toLowerCase().contains("mark")) {

                            tag = extractTagFromQuestion(questionString);
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag="
                                    + tag + "&base64=" + encodedImageToBase64;

                        } else if (questionString.toLowerCase().contains("train")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1";
                        } else if (questionString.toLowerCase().contains("search")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        } else if (questionString.toLowerCase().contains("recognize")
                                || questionString.toLowerCase().contains("what is")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        }
                        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
                        int postDataLength = postData.length;
                        String newrequest = "http://rekognition.com/func/api/";
                        URL url = new URL(newrequest);
                        HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection();

                        // Increase the timeout for reading the response
                        connectionFaceDetection.setReadTimeout(15000);

                        connectionFaceDetection.setDoOutput(true);
                        connectionFaceDetection.setDoInput(true);
                        connectionFaceDetection.setInstanceFollowRedirects(false);
                        connectionFaceDetection.setRequestMethod("POST");
                        connectionFaceDetection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                        connectionFaceDetection.setRequestProperty("X-Mashape-Key",
                                "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp");
                        connectionFaceDetection.setRequestProperty("charset", "utf-8");
                        connectionFaceDetection.setRequestProperty("Accept", "application/json");
                        connectionFaceDetection.setRequestProperty("Content-Length",
                                Integer.toString(postDataLength));
                        connectionFaceDetection.setUseCaches(false);

                        DataOutputStream outputStreamForFaceDetection = new DataOutputStream(
                                connectionFaceDetection.getOutputStream());
                        outputStreamForFaceDetection.write(postData);

                        BufferedReader inputStreamForFaceDetection = new BufferedReader(
                                new InputStreamReader((connectionFaceDetection.getInputStream())));

                        StringBuilder responseForFaceDetection = new StringBuilder();

                        while ((responseStringForFaceDetection = inputStreamForFaceDetection
                                .readLine()) != null) {
                            responseForFaceDetection.append(responseStringForFaceDetection);
                        }

                        //closing all the connections
                        inputStreamForFaceDetection.close();
                        outputStreamForFaceDetection.close();
                        connectionFaceDetection.disconnect();

                        responseStringForFaceDetection = responseForFaceDetection.toString();
                        LOG.info(responseStringForFaceDetection);

                        JSONObject responseJSONObjectForFaceDetection = new JSONObject(
                                responseStringForFaceDetection);
                        if (questionString.toLowerCase().contains("train") || questionString.contains("tag")
                                || questionString.toLowerCase().contains("mark")) {
                            JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection
                                    .getJSONObject("usage");
                            finalresponseForCard = usageKeyFromResponse.getString("status");
                            if (!tag.equals(""))
                                finalresponseForCard = "Object is tagged as " + tag;
                        } else {
                            JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection
                                    .getJSONObject("scene_understanding");
                            JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches");
                            JSONObject firstResultFromArray = matchesArray.getJSONObject(0);

                            double percentSureOfObject;
                            //If an score has value 1, then the value type is Integer else the value type is double
                            if (firstResultFromArray.get("score") instanceof Integer) {
                                percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100;
                            } else
                                percentSureOfObject = (Double) firstResultFromArray.get("score") * 100;

                            finalresponseForCard = "The object is " + firstResultFromArray.getString("tag")
                                    + ". Match score is" + percentSureOfObject;
                        }

                        //section where if it doesn't contain anything about tag or train

                    } catch (Exception e) {
                        LOG.warning(e.getMessage());
                    }

                }

                else
                    finalresponseForCard = "Could not understand your words";
            } else
                finalresponseForCard = "Could not understand your words";

            TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem();

            responseCardForSDKAlchemyAPI.setText(finalresponseForCard);
            responseCardForSDKAlchemyAPI
                    .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD")));
            responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard);
            responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows");
            responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT"));
            mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute();
            LOG.info("New card added to the timeline");

        } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) {
            LOG.info("It was a note taken with the 'take a note' voice command. Processing it.");

            // Grab the spoken text from the timeline card and update the card with
            // an HTML response (deleting the text as well).
            String noteText = timelineItem.getText();
            String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)];

            timelineItem.setText(null);
            timelineItem.setHtml(makeHtmlForCard(
                    "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>"));
            timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE")));

            mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute();
        } else {
            LOG.warning("I don't know what to do with this notification, so I'm ignoring it.");
        }
    }
}