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:com.francetelecom.clara.cloud.mvn.consumer.maven.PomGenerator.java

/**
 * Generate a pom.xml file from a MavenProject description
 * @return//from  w ww. j a v a  2s.c  o  m
 */
private String modelToStringXml(Model model) {

    DefaultModelWriter modelWriter = new DefaultModelWriter();

    StringWriter output = new StringWriter();
    String result = "";
    try {
        modelWriter.write(output, null, model);
        result = output.getBuffer().toString();
    } catch (IOException e) {
        logger.error("Cannot convert model to pom: " + e.getMessage());
        throw new TechnicalException("Cannot convert model to pom", e);
    }
    return result;
}

From source file:jp.mathes.databaseWiki.wiki.NewPlugin.java

@SuppressWarnings("unchecked")
@Override//w  w w  .  j  ava2 s.co  m
public void process(final Document doc, final String fieldname, final String user, final String password,
        final Backend backend) throws PluginException {
    Field<String> field = doc.getAllFields().get(fieldname);
    String renderedText = field.getValue();
    Matcher matcher = NewPlugin.REGEX.matcher(renderedText);
    while (matcher.find()) {
        String target = "";
        String param = "";
        if (StringUtils.isEmpty(matcher.group(1))) {
            target = String.format("../../%s/_new", matcher.group(2));
            param = matcher.group(3);
        } else {
            target = String.format("../../../%s/%s/_new", matcher.group(1), matcher.group(2));
            param = matcher.group(3);
        }
        try {
            Configuration conf = new Configuration();
            conf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
            Template template = new Template("name", new StringReader(param), new Configuration());
            HashMap<String, Object> data = new HashMap<String, Object>();
            data.put("doc", doc);
            data.put("fields", doc.getAllFields());
            StringWriter sw = new StringWriter();
            template.process(data, sw);
            param = sw.getBuffer().toString();
        } catch (IOException e) {
            throw new PluginException(e);
        } catch (TemplateException e) {
            throw new PluginException(e);
        }
        // match a comma except if it is preceeded by a backslash
        String[] split = param.split("(?<!\\\\),");
        StringBuilder sbForm = new StringBuilder(
                "<form method=\"post\" class=\"new\" action=\"%s\"><input type=\"text\" name=\"name\" />");
        for (String oneParameter : split) {
            String[] oneParameterSplit = StringUtils.split(oneParameter, "(?<!\\\\)=", 2);
            if (oneParameterSplit.length == 2) {
                sbForm.append(String.format("<input type=\"hidden\" name=\"%s\" value=\"%s\"/>",
                        oneParameterSplit[0], oneParameterSplit[1]));
            }
        }
        sbForm.append("<input type=\"submit\" value=\"create\"/></form>");
        String formString = String.format(sbForm.toString(), target);
        renderedText = renderedText.replace(matcher.group(0), formString);
        field.setValue(renderedText);
    }
}

From source file:controllers.SensorTypeController.java

private static String toCsv(List<SensorType> types) {
    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() };
    ICsvBeanWriter writer = new CsvBeanWriter(sw, CsvPreference.STANDARD_PREFERENCE);

    try {/*www.j a v  a 2 s  .co m*/
        final String[] header = new String[] { "sensorTypeName", "manufacturer", "version", "maximumValue",
                "minimumValue", "unit", "interpreter", "sensorTypeUserDefinedFields", "sensorCategoryName" };
        writer.writeHeader(header);
        for (SensorType type : types) {
            writer.write(type, header, processors);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sw.getBuffer().toString();
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.util.UnifiedFormatter.java

@Override
public String format(LogRecord record) {
    String username = "ANONYMOUS";
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User) {
            username = ((User) principal).getUsername();
        } else {//from w  w w  .  jav a  2  s. c o m
            username = principal.toString();
        }
    }

    int dotIndex = record.getSourceClassName().lastIndexOf(".");
    String className = record.getSourceClassName().substring(dotIndex != -1 ? dotIndex + 1 : 0);
    String msg = record.getMessage();
    if (record.getParameters() != null && record.getParameters().length > 0) {
        msg = MessageFormat.format(record.getMessage(), record.getParameters());
    }
    if (record.getThrown() != null) {
        Throwable thrown = record.getThrown();
        StringWriter result = new StringWriter();
        thrown.printStackTrace(new PrintWriter(result));
        result.flush();
        msg += "\n" + result.getBuffer();
    }
    return FST + dateFormat.format(record.getMillis()) + FET + FSEP + RST + FST + record.getLevel() + FET + FSEP
            + FST + className + "." + record.getSourceMethodName() + FET + FSEP + FST + username + FET + FSEP
            + FST + record.getThreadID() + FET + FSEP + FST + msg + FET + RET;
}

From source file:net.sf.jasperreports.charts.util.SvgChartRendererFactory.java

@Override
public Renderable getRenderable(JasperReportsContext jasperReportsContext, JFreeChart chart,
        ChartHyperlinkProvider chartHyperlinkProvider, Rectangle2D rectangle) {
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);
    SVGGraphics2D grx = new SVGGraphics2D(document);

    grx.setSVGCanvasSize(rectangle.getBounds().getSize());

    List<JRPrintImageAreaHyperlink> areaHyperlinks = null;

    if (chartHyperlinkProvider != null && chartHyperlinkProvider.hasHyperlinks()) {
        areaHyperlinks = ChartUtil.getImageAreaHyperlinks(chart, chartHyperlinkProvider, grx, rectangle);
    } else {//from ww w  .  jav  a 2  s  .  com
        chart.draw(grx, rectangle);
    }

    try {
        StringWriter swriter = new StringWriter();
        grx.stream(swriter);
        byte[] svgData = null;
        try {
            svgData = swriter.getBuffer().toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new JRRuntimeException(e);
        }
        return new SimpleRenderToImageAwareDataRenderer(svgData, areaHyperlinks);
    } catch (SVGGraphics2DIOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:org.dataconservancy.packaging.tool.ser.PackageNameConverterTest.java

@Test
public void testMarshal() throws Exception {
    StringWriter writer = new StringWriter();
    underTest.marshal(PACKAGE_NAME, new PrettyPrintWriter(writer), getMarshalingContext());

    assertTrue(writer.getBuffer().length() > 0);
    String result = writer.getBuffer().toString();

    assertTrue(result.contains(PACKAGE_NAME));
    assertTrue(result.contains(PackageNameConverter.E_PACKAGE_NAME));
}

From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java

public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException {

    request.request.technicalUser.username = this.user;
    request.request.technicalUser.password = this.password;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, request);//from  ww w  .  j av  a  2  s. c o  m

    String requestJson = sw.getBuffer().toString();

    logger.debug("callWebService(): jsonRequest:" + requestJson);

    URL url = new URL(this.endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(requestJson.getBytes("UTF-8"));
    out.flush();
    int responseCode = conn.getResponseCode();

    InputStream input = conn.getInputStream();

    ByteArrayOutputStream data = new ByteArrayOutputStream();
    int len;
    byte[] buf = new byte[50000];
    while ((len = input.read(buf)) > 0) {
        data.write(buf, 0, len);
    }
    conn.disconnect();
    String jsonResponse = new String(data.toByteArray(), "UTF-8");

    if (responseCode != 200) {
        throw new IOException(jsonResponse);
    }

    logger.debug("callWebService(): jsonResponse:" + jsonResponse);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T response = mapper.readValue(new StringReader(jsonResponse), clazz);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    sw = new StringWriter();
    mapper.writeValue(sw, response);
    logger.debug(
            "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString());

    return response;
}

From source file:com.controlj.addon.weather.noaa.WeatherServiceUIImpl.java

public String getAddDialogHTML() {
    StringWriter result = new StringWriter();
    copyHTMLTemplate(WeatherServiceUIImpl.class, "adddialog.html", result);
    return result.getBuffer().toString();
}

From source file:org.dataconservancy.packaging.tool.ser.ApplicationVersionConverterTest.java

@Test
public void testMarshal() throws Exception {
    StringWriter writer = new StringWriter();

    underTest.marshal(versionInfo, new PrettyPrintWriter(writer), getMarshalingContext());
    assertTrue(writer.getBuffer().length() > 1);

    String result = writer.getBuffer().toString();
    assertTrue(result.contains(ApplicationVersionConverter.E_APPLICATION_VERSION));
    assertTrue(result.contains(ApplicationVersionConverter.E_BUILDNO));
    assertTrue(result.contains(ApplicationVersionConverter.E_BUILDREV));
    assertTrue(result.contains(ApplicationVersionConverter.E_BUILDTS));
}

From source file:siia.booking.domain.trip.LegMarshallingTest.java

@Test
public void testMarshallingLeg() throws Exception {
    long day = 24 * 60 * 60 * 1000;
    Leg leg = new Leg(new DateTime(day, ISOChronology.getInstanceUTC()),
            new DateTime(day * 2, ISOChronology.getInstanceUTC()), new Location("UK", "London"),
            new Location("US", "New York"));

    StringWriter writer = new StringWriter();
    StreamResult res = new StreamResult(writer);
    marshaller.marshal(leg, res);//from  ww  w . j a v  a 2  s . c o  m

    assertXMLEqual("Leg marshalling incorrect", marshalledLeg, writer.getBuffer().toString());
}