Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

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

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:controllers.SensorController.java

private static String toCsv(List<Sensor> sensors) {
    StringWriter sw = new StringWriter();
    CellProcessor[] processors = new CellProcessor[] { new Optional(), new Optional(), new Optional(),
            new Optional(), new Optional(), new Optional(), new Optional(), new Optional(), new Optional(),
            new Optional(), new Optional(), new Optional() };
    ICsvBeanWriter writer = new CsvBeanWriter(sw, CsvPreference.STANDARD_PREFERENCE);
    try {/* w  w  w  .  ja va2  s  .c  o  m*/
        final String[] header = new String[] { "sensorName", "sensorUserDefinedFields", "deviceUri",
                "sensorTypeName", "manufacturer", "version", "maximumValue", "minimumValue", "unit",
                "interpreter", "sensorTypeUserDefinedFields", "sensorCategoryName" };
        writer.writeHeader(header);
        for (Sensor sensor : sensors) {
            writer.write(sensor, header, processors);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sw.getBuffer().toString();
}

From source file:io.debezium.document.JacksonWriter.java

@Override
public String write(Document document) throws IOException {
    StringWriter writer = new StringWriter();
    try (JsonGenerator jsonGenerator = factory.createGenerator(writer)) {
        configure(jsonGenerator);//from   w  w  w . j  a va  2  s  .c  o  m
        writeDocument(document, jsonGenerator);
    }
    return writer.getBuffer().toString();
}

From source file:org.apache.accumulo.monitor.servlets.BasicServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Verify that this is the active Monitor instance
    if (!isActiveMonitor()) {
        resp.sendError(HttpURLConnection.HTTP_UNAVAILABLE, STANDBY_MONITOR_MESSAGE);
        return;/*from   www  . j a  v a2 s. c om*/
    }
    StringBuilder sb = new StringBuilder();
    try {
        Monitor.fetchData();
        bannerText = sanitize(Monitor.getContext().getConfiguration().get(Property.MONITOR_BANNER_TEXT));
        bannerColor = Monitor.getContext().getConfiguration().get(Property.MONITOR_BANNER_COLOR).replace("'",
                "&#39;");
        bannerBackground = Monitor.getContext().getConfiguration().get(Property.MONITOR_BANNER_BACKGROUND)
                .replace("'", "&#39;");
        pageStart(req, resp, sb);
        pageBody(req, resp, sb);
        pageEnd(req, resp, sb);
    } catch (Throwable t) {
        log.error("Error building page " + req.getRequestURI(), t);
        sb.append("\n<pre>\n");
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        sb.append(sanitize(sw.getBuffer().toString()));
        sb.append("</pre>\n");
    } finally {
        resp.getWriter().print(sb);
        resp.getWriter().flush();
    }
}

From source file:com.eyeq.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();/* w w  w . ja va 2 s .  c  om*/
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("Property 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("Property 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("Property 'sortMode' has been changed after the state restoration", newModel.getSortCriteria(),
            is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:iddb.task.tasks.UpdateTask.java

public void updatePlayer(Server server, List<PlayerInfo> list) throws Exception {
    try {//ww w.ja v  a  2  s .c o m
        for (PlayerInfo playerInfo : list) {
            try {
                Date playerLastUpdate;
                boolean created = false;
                Player player = playerDAO.findByServerAndHash(server.getKey(), playerInfo.getHash());
                if (player == null) {
                    created = true;
                    player = createPlayer(server, playerInfo);
                    playerLastUpdate = playerInfo.getUpdated();
                } else {
                    if (StringUtils.isEmpty(player.getGuid()) && StringUtils.isNotEmpty(playerInfo.getGuid())) {
                        player.setGuid(playerInfo.getGuid());
                    }
                    player.setNickname(playerInfo.getName());
                    player.setIp(playerInfo.getIp());
                    player.setClientId(playerInfo.getClientId());
                    player.setLevel(playerInfo.getLevel());
                    if (player.getClientId() == null || player.getClientId() == 0) {
                        player.setClientId(playerInfo.getClientId());
                    }
                    playerLastUpdate = player.getUpdated();
                }
                if (player.getUpdated() == null || playerInfo.getUpdated().after(player.getUpdated())) {
                    player.setUpdated(playerInfo.getUpdated());
                }

                handlePlayerEvent(playerInfo, player);

                if (created)
                    playerDAO.save(player);

                if (handlePenaltyEvent(playerInfo, player) || !created) {
                    playerDAO.save(player);
                }

                boolean update = false;
                if (Events.CONNECT.equals(playerInfo.getEvent())) {
                    if (server.getUpdated() == null || server.getUpdated().after(playerLastUpdate)) {
                        update = true;
                    }
                }
                AliasManager.createAlias(player, update);

            } catch (Exception e) {
                log.error(e.getMessage());
                StringWriter w = new StringWriter();
                e.printStackTrace(new PrintWriter(w));
                log.error(w.getBuffer().toString());
            }
        }
        server.setDirty(true);
        server.setUpdated(new Date());
        serverDAO.save(server);
    } catch (Exception e) {
        log.error(e.getMessage());
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        log.error(w.getBuffer().toString());
        throw e;
    }
}

From source file:org.apache.ambari.view.hive.resources.uploads.TableDataReader.java

@Override
public int read(char[] cbuf, int off, int len) throws IOException {

    int totalLen = len;
    int count = 0;
    do {/*from  www .  j  ava 2 s.  c  om*/
        int n = stringReader.read(cbuf, off, len);

        if (n != -1) {
            // n  were read
            len = len - n; // len more to be read
            off = off + n; // off now shifted to n more
            count += n;
        }

        if (count == totalLen)
            return count; // all totalLen characters were read

        if (iterator.hasNext()) { // keep reading as long as we keep getting rows
            StringWriter stringWriter = new StringWriter(CAPACITY);
            CSVPrinter csvPrinter = new CSVPrinter(stringWriter, CSV_FORMAT);
            Row row = iterator.next();
            csvPrinter.printRecord(row.getRow());
            stringReader.close(); // close the old string reader
            stringReader = new StringReader(stringWriter.getBuffer().toString());
            csvPrinter.close();
            stringWriter.close();
        } else {
            return count == 0 ? -1 : count;
        }
    } while (count < totalLen);

    return count;
}

From source file:com.linuxbox.enkive.imap.message.EnkiveImapTemplateMessage.java

@Override
public InputStream getBodyContent() throws IOException {
    StringWriter stringWriter = new StringWriter();
    try {/*from   ww  w  . j av  a2s  .  c o  m*/
        messageBody.process(root, stringWriter);
    } catch (TemplateException e) {
        LOGGER.error("Error producing IMAP Inbox message from template", e);
    }
    StringBuffer message = stringWriter.getBuffer();
    return new ByteArrayInputStream(message.toString().getBytes());
}

From source file:org.apache.ode.bpel.rtrep.v2.ExtensionContextImpl.java

public void completeWithFault(Throwable t) {
    if (!hasCompleted) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        FaultData fault = new FaultData(new QName(Namespaces.WSBPEL2_0_FINAL_EXEC, "subLanguageExecutionFault"),
                _activityInfo.o, sw.getBuffer().toString());
        _activityInfo.parent.completed(fault, CompensationHandler.emptySet());
        hasCompleted = true;/* w  w  w .  j a  va 2s  .  c om*/
    } else {
        if (__log.isWarnEnabled()) {
            __log.warn("Activity '" + _activityInfo.o.name + "' has already been completed.");
        }
    }
}

From source file:com.funambol.json.coredb.CoreDBServlet.java

private void writeError(Exception ex, HttpServletResponse response, String action) throws IOException {
    log.error("An error occurred while handling action [" + action + "].", ex);
    String errorPage = HTMLManager.getHtmlHeaderFor("An error occurred processing request:");
    response.setStatus(500);//www.  ja  va 2s . com
    if (action != null) {
        errorPage += "Action was [" + action + "]<b>";
    }
    if (ex != null) {
        errorPage += "Exception was <b>]";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        errorPage += sw.getBuffer();
    }
    errorPage += HTMLManager.closePage(buildCommonFooter());
    sendHtmlPage(response, errorPage);
}

From source file:com.fer.hr.olap.query.QuerySerializer.java

public String createXML() throws QueryParseException {
    if (this.query == null)
        throw new QueryParseException("Query object can not be null");

    try {//from ww w.  j a  v  a 2s  .  c om
        createDocument();
        createDOMTree();

        XMLOutputter serializer = new XMLOutputter();
        Format format = Format.getPrettyFormat();
        StringWriter st = new StringWriter();
        serializer.setFormat(format);
        serializer.output(dom, st);

        return st.getBuffer().toString();

    } catch (Exception e) {
        throw new QueryParseException(e.getMessage(), e);
    }

}