Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

In this page you can find the example usage for java.io StringWriter write.

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:com.espertech.esper.dataflow.ops.LogSink.java

public void onInput(int port, Object theEvent) {

    String line;//from  w ww. j  a  va  2s.  c  o  m
    if (layout == null) {

        StringWriter writer = new StringWriter();

        writer.write("[");
        writer.write(dataflowName);
        writer.write("] ");

        if (title != null) {
            writer.write("[");
            writer.write(title);
            writer.write("] ");
        }

        if (dataFlowInstanceId != null) {
            writer.write("[");
            writer.write(dataFlowInstanceId);
            writer.write("] ");
        }

        writer.write("[port ");
        writer.write(Integer.toString(port));
        writer.write("] ");

        getEventOut(port, theEvent, writer);
        line = writer.toString();
    } else {
        String result = layout.replace("%df", dataflowName).replace("%p", Integer.toString(port));
        if (dataFlowInstanceId != null) {
            result = result.replace("%i", dataFlowInstanceId);
        }
        if (title != null) {
            result = result.replace("%t", title);
        }

        StringWriter writer = new StringWriter();
        getEventOut(port, theEvent, writer);
        result = result.replace("%e", writer.toString());

        line = result;
    }

    if (!linefeed) {
        line = line.replaceAll("\n", "").replaceAll("\r", "");
    }

    // output
    if (log) {
        logme.info(line);
    } else {
        System.out.println(line);
    }
}

From source file:org.photovault.imginfo.indexer.ExtVolIndexer.java

/**
 Run the actual indexing operation./*from   www. ja va2 s  . co  m*/
 */
public void run() {
    Session photoSession = null;
    Session oldSession = null;
    try {
        photoSession = HibernateUtil.getSessionFactory().openSession();
        oldSession = ManagedSessionContext.bind((org.hibernate.classic.Session) photoSession);

        startTime = new Date();

        DirectoryIndexer topIndexer = new DirectoryIndexer(volume.getBaseDir(), volume);
        indexDirectory(topIndexer, 0, 100);
        notifyListenersIndexingComplete();
    } catch (Throwable t) {
        StringWriter strw = new StringWriter();
        strw.write("Error indexing " + volume.getBaseDir().getAbsolutePath());
        strw.write("\n");
        t.printStackTrace(new PrintWriter(strw));
        log.error(strw.toString());
        log.error(t);
        notifyListenersIndexingError(t.getMessage());
    } finally {
        if (photoSession != null) {
            photoSession.close();
        }
        ManagedSessionContext.bind((org.hibernate.classic.Session) oldSession);
    }
}

From source file:org.syncope.core.scheduling.NotificationJob.java

public TaskExec executeSingle(final NotificationTask task) {
    init();//from w  ww  .j  ava 2 s  .com

    TaskExec execution = new TaskExec();
    execution.setTask(task);
    execution.setStartDate(new Date());

    if (StringUtils.isBlank(smtpHost) || StringUtils.isBlank(task.getSender())
            || StringUtils.isBlank(task.getSubject()) || task.getRecipients().isEmpty()
            || StringUtils.isBlank(task.getHtmlBody()) || StringUtils.isBlank(task.getTextBody())) {

        String message = "Could not fetch all required information for " + "sending e-mails:\n" + smtpHost + ":"
                + smtpPort + "\n" + task.getRecipients() + "\n" + task.getSender() + "\n" + task.getSubject()
                + "\n" + task.getHtmlBody() + "\n" + task.getTextBody();
        LOG.error(message);

        execution.setStatus(Status.NOT_SENT.name());

        if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {

            execution.setMessage(message);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("About to send e-mails:\n" + smtpHost + ":" + smtpPort + "\n" + task.getRecipients()
                    + "\n" + task.getSender() + "\n" + task.getSubject() + "\n" + task.getHtmlBody() + "\n"
                    + task.getTextBody() + "\n");
        }

        for (String to : task.getRecipients()) {
            try {
                JavaMailSenderImpl sender = new JavaMailSenderImpl();
                sender.setHost(smtpHost);
                sender.setPort(smtpPort);
                if (StringUtils.isNotBlank(smtpUsername)) {
                    sender.setUsername(smtpUsername);
                }
                if (StringUtils.isNotBlank(smtpPassword)) {
                    sender.setPassword(smtpPassword);
                }

                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);

                helper.setTo(to);
                helper.setFrom(task.getSender());
                helper.setSubject(task.getSubject());
                helper.setText(task.getTextBody(), task.getHtmlBody());

                sender.send(message);

                execution.setStatus(Status.SENT.name());

                StringBuilder report = new StringBuilder();
                switch (task.getTraceLevel()) {
                case ALL:
                    report.append("FROM: ").append(task.getSender()).append('\n').append("TO: ").append(to)
                            .append('\n').append("SUBJECT: ").append(task.getSubject()).append('\n')
                            .append('\n').append(task.getTextBody()).append('\n').append('\n')
                            .append(task.getHtmlBody()).append('\n');
                    break;

                case SUMMARY:
                    report.append("E-mail sent to ").append(to).append('\n');
                    break;

                case FAILURES:
                case NONE:
                default:
                }
                if (report.length() > 0) {
                    execution.setMessage(report.toString());
                }
            } catch (Throwable t) {
                LOG.error("Could not send e-mail", t);

                execution.setStatus(Status.NOT_SENT.name());
                StringWriter exceptionWriter = new StringWriter();
                exceptionWriter.write(t.getMessage() + "\n\n");
                t.printStackTrace(new PrintWriter(exceptionWriter));

                if (task.getTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) {

                    execution.setMessage(exceptionWriter.toString());
                }
            }

            execution.setEndDate(new Date());
        }
    }

    if (hasToBeRegistered(execution)) {
        execution = taskExecDAO.save(execution);
    }

    return execution;
}

From source file:com.cognifide.calais.OpenCalaisService.java

private String getResponse(PostMethod method) throws IOException {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
    StringWriter writer = new StringWriter();
    String responseString = "";
    String line;//from  w  ww. jav  a 2s  . com
    while ((line = reader.readLine()) != null) {
        writer.write(line);
    }
    responseString = writer.toString();
    return responseString;
}

From source file:yp.tibco.com.yang.lottery.client.GraphicalLotteryClient.java

public String Object2XmlString(Object object) {
    String xmlString = null;//from   w  ww. ja  v a  2s.c o m

    StringWriter outputWriter = new StringWriter();
    outputWriter.write("<?xml version='1.0' encoding='gb2312' ?>\n");
    BeanWriter beanWriter = new BeanWriter(outputWriter);
    beanWriter.getXMLIntrospector().setAttributesForPrimitives(false);
    beanWriter.setWriteIDs(false);

    try {

        beanWriter.write("webinf", object);

    } catch (Exception e) {

        e.printStackTrace();

    }

    xmlString = outputWriter.toString();
    return xmlString;

}

From source file:cz.vutbr.fit.xzelin15.dp.consumer.WSDynamicClientFactory.java

private String transferWSDL(String wsdlURL, String userPassword, WiseProperties wiseProperties)
        throws WiseConnectionException {
    String filePath = null;//from w  w  w  .  j  a  v  a  2s  .c  o m
    try {
        URL endpoint = new URL(wsdlURL);
        // Create the connection
        HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoOutput(false);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept",
                "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        // set Connection close, otherwise we get a keep-alive
        // connection
        // that gives us fragmented answers.
        conn.setRequestProperty("Connection", "close");
        // BASIC AUTH
        if (userPassword != null) {
            conn.setRequestProperty("Authorization",
                    "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes()));
        }
        // Read response
        InputStream is = null;
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            StringWriter sw = new StringWriter();
            char[] buf = new char[200];
            int read = 0;
            while (read != -1) {
                read = isr.read(buf);
                sw.write(buf);
            }
            throw new WiseConnectionException("Remote server's response is an error: " + sw.toString());
        }
        // saving file
        File file = new File(wiseProperties.getProperty("wise.tmpDir"),
                new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString());
        OutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        IOUtils.copyStream(fos, is);
        fos.close();
        is.close();
        filePath = file.getPath();
    } catch (WiseConnectionException wce) {
        throw wce;
    } catch (Exception e) {
        throw new WiseConnectionException("Wsdl download failed!", e);
    }
    return filePath;
}

From source file:net.mumie.cocoon.msg.TUBWorksheetsMessageImpl.java

/**
 * Adds the contents of the grade to the message.
 *///  w ww .  j a v a 2  s.c  o  m

protected void init(PostMethod method, MessageDestination destination) throws Exception {
    final String METHOD_NAME = "init";
    this.logDebug(METHOD_NAME + " 1/2: Started");
    DbHelper dbHelper = null;
    try {
        dbHelper = (DbHelper) this.serviceManager.lookup(DbHelper.ROLE);
        ResultSet resultSet = dbHelper.queryWorksheetContext(this.worksheetIds);
        StringWriter out = new StringWriter();
        Map<Integer, Integer> courseVCThreads = new HashMap<Integer, Integer>();
        int comaClassId = -1;
        out.write("<?xml version=\"1.0\" encoding=\"ASCII\"?>");
        out.write("<grades:worksheets xmlns:grades=\"http://www.mumie.net/xml-namespace/grades\">");
        while (resultSet.next()) {
            Integer courseId = new Integer(resultSet.getInt(DbColumn.COURSE_ID));
            String label = resultSet.getString(DbColumn.LABEL);
            int points = resultSet.getInt(DbColumn.POINTS);

            int classId = resultSet.getInt(DbColumn.CLASS_ID);
            if (comaClassId == -1)
                comaClassId = classId;
            else if (classId != comaClassId)
                throw new IllegalArgumentException("Multiple classes: " + comaClassId + ", " + classId);

            if (!label.trim().endsWith(".1")) {
                out.write("<grades:worksheet" + " id=\"" + resultSet.getInt(DbColumn.ID) + "\""
                        + " vc_thread_id=\"" + resultSet.getInt(DbColumn.VC_THREAD_ID) + "\"" + " label=\""
                        + label + "\"" + " points=\"" + points + "\"" + " course_id=\"" + courseId + "\""
                        + "/>");
                if (!courseVCThreads.containsKey(courseId))
                    courseVCThreads.put(courseId, new Integer(resultSet.getInt(DbColumn.COURSE_VC_THREAD_ID)));
            }
        }

        for (Map.Entry entry : courseVCThreads.entrySet()) {
            out.write("<grades:course" + " id=\"" + entry.getKey() + "\"" + " vc_thread_id=\""
                    + entry.getValue() + "\"" + " class_id=\"" + comaClassId + "\"" + "/>");
        }

        out.write("<grades:class" + " id=\"" + comaClassId + "\"" + " sync_id=\"" + COMA_CLASS_SYNC_ID + "\""
                + "/>");

        out.write("</grades:worksheets>");
        method.addParameter("body", out.toString());
        this.logDebug(METHOD_NAME + " 2/2: Done");
    } finally {
        this.serviceManager.release(dbHelper);
    }
}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

protected String responseAsString(InputStream responseStream) {
    StringWriter sw = new StringWriter();
    int i;//  www .  jav  a  2  s  . c om
    try {
        while ((i = responseStream.read()) >= 0) {
            sw.write(i);
        }
    } catch (IOException e) {
        LOG.error("Error reading response.", e);
        throw new RetrieveException("Error reading response.", e);
    }
    String result = sw.getBuffer().toString().trim();
    return result;
}

From source file:org.linagora.linshare.view.tapestry.services.impl.MailTemplating.java

public String readFullyTemplateContent(InputStream template) {
    String content = "";
    StringWriter writer = new StringWriter();

    try {/*from   w  w w  .  j a v  a  2s .co m*/
        InputStreamReader streamReader = new InputStreamReader(template);
        BufferedReader buffer = new BufferedReader(streamReader);
        String line = "";
        while (null != (line = buffer.readLine())) {
            writer.write(line + "\n");
        }
        content = writer.toString();
    } catch (IOException e) {
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "The template is not valid", e);
    } catch (Exception ex) {
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "The template is not valid", ex);
    }
    return content;
}

From source file:mobac.program.model.Map.java

public String getToolTip() {
    MapSpace mapSpace = mapSource.getMapSpace();
    EastNorthCoordinate tl = new EastNorthCoordinate(mapSpace, zoom, minTileCoordinate.x, minTileCoordinate.y);
    EastNorthCoordinate br = new EastNorthCoordinate(mapSpace, zoom, maxTileCoordinate.x, maxTileCoordinate.y);

    StringWriter sw = new StringWriter(1024);
    sw.write("<html>");
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_title"));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_source",
            StringEscapeUtils.escapeHtml4(mapSource.toString()),
            StringEscapeUtils.escapeHtml4(mapSource.getName())));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_zoom_lv", zoom));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_area_start", tl.toString(), minTileCoordinate.x,
            minTileCoordinate.y));//from  w ww .  j av  a2  s .  co m
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_area_end", br.toString(), maxTileCoordinate.x,
            maxTileCoordinate.y));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_map_size",
            (maxTileCoordinate.x - minTileCoordinate.x + 1), (maxTileCoordinate.y - minTileCoordinate.y + 1)));
    if (parameters != null) {
        sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_tile_size"),
                parameters.getWidth(), parameters.getHeight()));
        sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_tile_format"),
                parameters.getFormat().toString()));
    } else {
        sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_tile_format_origin"));
    }

    sw.write(String.format(I18nUtils.localizedStringForKey("lp_atlas_info_max_tile"),
            calculateTilesToDownload()));
    sw.write("</html>");
    return sw.toString();
}