Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

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());
    }/*from w w  w .j a va2  s  . c o m*/

    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:cz.tomas.StockAnalyze.utils.DownloadService.java

public String readStream(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {/*from  w  w w  . j a  v  a  2 s .c om*/
            Reader reader = new BufferedReader(new InputStreamReader(is));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:org.dhatim.templating.freemarker.FreeMarkerTemplateProcessor.java

private void applyTemplate(Template template, SAXElement element, ExecutionContext executionContext)
        throws SmooksException {
    if (getAction() == Action.BIND_TO) {
        Writer writer = new StringWriter();
        applyTemplate(template, element, executionContext, writer);

        executionContext.getBeanContext().addBean(getBindBeanId(), writer.toString(), new Fragment(element));
    } else {//from  w w w  . java  2  s . com
        Writer writer = element.getWriter(this);
        applyTemplate(template, element, executionContext, writer);
    }
}

From source file:any.servable.VsetServable.java

@Override
public void process(Message cmd, BlockingQueue<Message> outQueue) {
    if (cmd == null) {
        loopqueue = outQueue;//from ww w.  j av  a  2 s .  c  o  m
    } else {

        String filename = cmd.getContent();

        currentfile = new File(res, filename);

        logger.debug(currentfile.getAbsolutePath());
        FileOutputStream fw;
        try {
            fw = new FileOutputStream(currentfile);

            fw.write(cmd.getData());
            fw.flush();
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
            final Writer result = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(result);
            e.printStackTrace(printWriter);
            outQueue.add(new Message("vset", "_error", "text/plain", "YES", result.toString().getBytes()));
        }

        if (cmd.getFullContent().contains("show=YES")) {
            Display display = Display.getDefault();
            display.syncExec(new Runnable() {
                public void run() {
                    URL pageUrl = null;
                    try {
                        pageUrl = currentfile.toURI().toURL();
                        browser.setUrl(pageUrl.toString());
                        blockpage = false;
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

From source file:org.n52.youngs.harvest.PoxCswSource.java

private HttpEntity createRequest(long startPosition, long maxRecords) {
    Marshaller m;/* www  .  j  ava2s . co m*/
    try {
        m = getMarshaller();
    } catch (JAXBException e) {
        log.error("Could not create marshaller", e);
        return null;
    }

    GetRecordsType getRecords = new GetRecordsType();
    ObjectFactory objectFactory = new ObjectFactory();
    JAXBElement<GetRecordsType> jaxb_getRecords = objectFactory.createGetRecords(getRecords);

    getRecords.setResultType(ResultType.RESULTS);
    getRecords.setOutputSchema(getOutputSchemaParameter());
    getRecords.setStartPosition(BigInteger.valueOf(startPosition));
    getRecords.setMaxRecords(BigInteger.valueOf(maxRecords));
    QueryType query = new QueryType();
    ElementSetNameType esn = new ElementSetNameType();
    esn.setValue(ElementSetType.FULL);
    query.setElementSetName(esn);
    query.setTypeNames(Lists.newArrayList(new QName(getOutputSchemaParameter(),
            getTypeNamesParameter().substring(getTypeNamesParameter().indexOf(":") + 1))));
    getRecords.setAbstractQuery(objectFactory.createQuery(query));

    Writer w = new StringWriter();
    try {
        m.marshal(jaxb_getRecords, w);
    } catch (JAXBException e) {
        log.error("Error marshalling request", e);
    }

    log.trace("Created GetRecords request starting at {} for {} records:\n{}", startPosition, maxRecords,
            w.toString());

    StringEntity entity = new StringEntity(w.toString(), Charsets.UTF_8);
    return entity;
}

From source file:org.apache.ambari.server.orm.helpers.dbms.GenericDbmsHelper.java

@Override
public String getAddUniqueConstraintStatement(String tableName, String constraintName, String... columnNames) {
    UniqueKeyConstraint uniqueKeyConstraint = new UniqueKeyConstraint();
    uniqueKeyConstraint.setName(constraintName);
    for (String columnName : columnNames) {
        uniqueKeyConstraint.addSourceField(columnName);
    }/*from   w ww  .  j a  v  a 2s  . co m*/

    TableDefinition tableDefinition = new TableDefinition();
    tableDefinition.setName(tableName);
    Writer writer = new StringWriter();
    tableDefinition.buildUniqueConstraintCreationWriter(createStubAbstractSessionFromPlatform(databasePlatform),
            uniqueKeyConstraint, writer);
    return writer.toString();
}

From source file:org.apache.ambari.server.orm.helpers.dbms.GenericDbmsHelper.java

@Override
public String getAddForeignKeyStatement(String tableName, String constraintName, List<String> keyColumns,
        String referenceTableName, List<String> referenceColumns, boolean shouldCascadeOnDelete) {
    ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint();
    foreignKeyConstraint.setName(constraintName);
    foreignKeyConstraint.setTargetTable(referenceTableName);
    foreignKeyConstraint.setSourceFields(keyColumns);
    foreignKeyConstraint.setTargetFields(referenceColumns);
    foreignKeyConstraint.setShouldCascadeOnDelete(shouldCascadeOnDelete);

    TableDefinition tableDefinition = new TableDefinition();
    tableDefinition.setName(tableName);//from  www  .  j  a va2  s. c  om

    Writer writer = new StringWriter();
    tableDefinition.buildConstraintCreationWriter(createStubAbstractSessionFromPlatform(databasePlatform),
            foreignKeyConstraint, writer);

    return writer.toString();

}

From source file:de.betterform.agent.web.servlet.UploadServlet.java

private String getFieldValue(FileItem item) throws IOException {
    InputStream is = item.getInputStream();
    if (is != null) {
        Writer writer = new StringWriter();
        try {//  w  w  w .j  a  v  a 2 s .c o m
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            char[] buffer = new char[1024];
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return null;
    }
}

From source file:org.alfresco.repo.web.scripts.bean.KeywordSearch.java

/**
 * Execute the search/*from ww w .ja va2 s. c o  m*/
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, Locale locale,
        WebScriptRequest req) {
    SearchResult searchResult = null;
    ResultSet results = null;

    try {
        // construct search statement
        String[] terms = searchTerms.split(" ");
        searchTerms = searchTerms.replaceAll("\"", "&quot;");

        // Escape special characters in the terms, so that they can't confuse the parser 
        for (int i = 0; i < terms.length; i++) {
            terms[i] = SearchLanguageConversion.escapeLuceneQuery(terms[i]);
        }

        Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
        statementModel.put("args", createArgs(req));
        statementModel.put("terms", terms);
        Writer queryWriter = new StringWriter(1024);
        renderFormatTemplate(QUERY_FORMAT, statementModel, queryWriter);
        String query = queryWriter.toString();

        // execute query
        if (logger.isDebugEnabled()) {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage
                    + ", itemsPerPage=" + itemsPerPage + ", search locale=" + locale.toString());
            logger.debug("Issuing lucene search: " + query);
        }

        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(query);
        if (locale != null) {
            parameters.addLocale(locale);
        }
        results = searchService.query(parameters);
        int totalResults = results.length();

        if (logger.isDebugEnabled())
            logger.debug("Results: " + totalResults + " rows (limited: "
                    + results.getResultSetMetaData().getLimitedBy() + ")");

        // are we out-of-range
        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
        if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
            throw new WebScriptException(
                    "Start page " + startPage + " is outside boundary of " + totalPages + " pages");
        }

        // construct search result
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0) {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
            searchResult
                    .setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            // Make the search resilient to invalid nodes
            if (!nodeService.exists(node)) {
                continue;
            }
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:org.apache.ambari.server.view.ViewContextImpl.java

/**
 * Parameterize string using VelocityContext instance
 *
 * @param raw original string with parameters in formal or shorthand notation
 *
 * @return parameterized string/*  ww w. j ava2  s  .c om*/
 *
 * @throws ParseErrorException if original string cannot be parsed by Velocity
 */
private String parameterize(String raw) throws ParseErrorException {
    if (raw != null) {
        Writer templateWriter = new StringWriter();
        Velocity.evaluate(velocityContext, templateWriter, raw, raw);
        return templateWriter.toString();
    }
    return null;
}