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:org.opcfoundation.ua.stacktest.io.TestSequenceWriter.java

public String write(TestSequence testSequence) {
    try {//  ww w .  ja  v  a 2 s.  com
        // Start by preparing the writer
        // We'll write to a string 
        StringWriter outputWriter = new StringWriter();
        try {
            // Betwixt just writes out the bean as a fragment
            // So if we want well-formed xml, we need to add the prolog
            outputWriter.write("<?xml version='1.0' ?>\n");

            // create write and set basic properties
            BeanWriter beanWriter = new BeanWriter(outputWriter);
            //beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
            beanWriter.enablePrettyPrint();
            beanWriter.setInitialIndentLevel(0);
            beanWriter.getBindingConfiguration().setMapIDs(false);

            // set a custom name mapper for attributes
            beanWriter.getXMLIntrospector().getConfiguration()
                    .setAttributeNameMapper(new CapitalizeNameMapper());
            // set a custom name mapper for elements
            beanWriter.getXMLIntrospector().getConfiguration().setElementNameMapper(new CapitalizeNameMapper());

            // write out the bean
            beanWriter.write(testSequence);
            return outputWriter.toString();
        } finally {
            outputWriter.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        return "Failed.";
    }
}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Reads the contents of the text file at the given path into a string and
 * returns it./*w  ww  .j  ava  2 s.c  o m*/
 *
 * @param  filePath  Path to file to read.
 *
 * @return  Contents of file or null if file does not exist or is empty.
 *
 * @throws  IOException  On read errors.
 */
private String readTextFile(final String filePath) throws IOException {
    final BufferedReader reader = new BufferedReader(new FileReader(filePath));
    final StringWriter writer = new StringWriter();
    String line = null;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
    }
    return writer.toString();
}

From source file:com.icesoft.faces.async.common.PushServerAdaptingServlet.java

public PushServerAdaptingServlet(final HttpSession httpSession, final String iceFacesId,
        final Collection synchronouslyUpdatedViews, final ViewQueue allUpdatedViews,
        final Configuration configuration, final CoreMessageService coreMessageService)
        throws MessageServiceException {
    blockingRequestHandlerContext = configuration.getAttribute("blockingRequestHandlerContext", "push-server");
    allUpdatedViews.onPut(new Runnable() {
        public void run() {
            allUpdatedViews.removeAll(synchronouslyUpdatedViews);
            synchronouslyUpdatedViews.clear();
            Set _viewIdentifierSet = new HashSet(allUpdatedViews);
            if (!_viewIdentifierSet.isEmpty()) {
                Long _sequenceNumber;
                synchronized (lock) {
                    _sequenceNumber = (Long) httpSession.getAttribute(SEQUENCE_NUMBER_KEY);
                    if (_sequenceNumber != null) {
                        _sequenceNumber = new Long(_sequenceNumber.longValue() + 1);
                    } else {
                        _sequenceNumber = new Long(1);
                    }//from  w w w  . j a va  2 s .c o  m
                    httpSession.setAttribute(SEQUENCE_NUMBER_KEY, _sequenceNumber);
                }
                String[] _viewIdentifiers = (String[]) _viewIdentifierSet
                        .toArray(new String[_viewIdentifierSet.size()]);
                StringWriter _stringWriter = new StringWriter();
                for (int i = 0; i < _viewIdentifiers.length; i++) {
                    if (i != 0) {
                        _stringWriter.write(',');
                    }
                    _stringWriter.write(_viewIdentifiers[i]);
                }
                Properties _messageProperties = new Properties();
                _messageProperties.setStringProperty(Message.DESTINATION_SERVLET_CONTEXT_PATH,
                        blockingRequestHandlerContext);
                coreMessageService.publish(iceFacesId + ";" + // ICEfaces ID
                _sequenceNumber + ";" + // Sequence Number
                _stringWriter.toString(), // Message Body
                        _messageProperties, UPDATED_VIEWS_MESSAGE_TYPE, MessageServiceClient.PUSH_TOPIC_NAME);
            }
        }
    });
}

From source file:net.officefloor.plugin.socket.server.http.integrate.HttpCleanupServerTest.java

/**
 * Ensure report cleanup {@link Escalation}.
 */// w  w  w .j  a v  a 2  s.com
public void testCleanupEscalation() throws Exception {

    // Specify the escalations
    final Throwable escalation = new Throwable("TEST");
    RecycleEscalationManagedObjectSource.escalation = escalation;

    // Undertake request
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

        // Create the request
        HttpGet method = new HttpGet(this.getServerUrl() + "/path");

        // Obtain the response (should be server error)
        HttpResponse response = client.execute(method);
        int status = response.getStatusLine().getStatusCode();
        assertEquals("Incorrect status", 500, status);

        // Read in the body of the response
        String responseEntity = HttpTestUtil.getEntityBody(response);
        StringWriter expectedEntity = new StringWriter();
        expectedEntity.write("Cleanup of object type " + RecycleEscalationManagedObjectSource.class.getName()
                + ": TEST (" + escalation.getClass().getSimpleName() + ")\n");
        assertEquals("Incorrect response entity", expectedEntity.toString(), responseEntity);
    }
}

From source file:org.springsource.ide.eclipse.commons.browser.swt.StsBrowserManager.java

private String serializeArguments(Object[] fargs)
        throws JsonGenerationException, JsonMappingException, IOException {
    StringWriter serialized = new StringWriter();
    boolean first = true;
    for (Object arg : fargs) {
        serialized.write(first ? "(" : ", ");
        mapper.writeValue(serialized, arg);
        first = false;//from  w w w .j a va2 s.com
    }
    serialized.write(")");
    return serialized.toString();
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale,
        Map<String, Object> templateContext, Delegator delegator, Appendable out, boolean cache)
        throws IOException, GeneralException {
    Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("context"));
    if (context == null) {
        context = new HashMap<String, Object>();
    }//  ww w  .j a  v a 2 s.  co  m
    String webSiteId = (String) templateContext.get("webSiteId");
    if (UtilValidate.isEmpty(webSiteId)) {
        if (context != null)
            webSiteId = (String) context.get("webSiteId");
    }

    String https = (String) templateContext.get("https");
    if (UtilValidate.isEmpty(https)) {
        if (context != null)
            https = (String) context.get("https");
    }

    String rootDir = (String) templateContext.get("rootDir");
    if (UtilValidate.isEmpty(rootDir)) {
        if (context != null)
            rootDir = (String) context.get("rootDir");
    }

    String dataResourceId = dataResource.getString("dataResourceId");
    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");

    // default type
    if (UtilValidate.isEmpty(dataResourceTypeId)) {
        dataResourceTypeId = "SHORT_TEXT";
    }

    // text types
    if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
        String text = dataResource.getString("objectInfo");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
        GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                .where("dataResourceId", dataResourceId).cache(cache).queryOne();
        if (electronicText != null) {
            String text = electronicText.getString("textData");
            writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
        }

        // object types
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        String text = (String) dataResource.get("dataResourceId");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);

        // resource type
    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
        String text = null;
        URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo"));

        if (url.getHost() != null) { // is absolute
            InputStream in = url.openStream();
            int c;
            StringWriter sw = new StringWriter();
            while ((c = in.read()) != -1) {
                sw.write(c);
            }
            sw.close();
            text = sw.toString();
        } else {
            String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
            String sep = "";
            if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
                sep = "/";
            }
            String fixedUrlStr = prefix + sep + url.toString();
            URL fixedUrl = new URL(fixedUrlStr);
            text = (String) fixedUrl.getContent();
        }
        out.append(text);

        // file types
    } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
        writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
    } else if (dataResourceTypeId.endsWith("_FILE")) {
        String dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
        String objectInfo = dataResource.getString("objectInfo");

        if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) {
            renderFile(dataResourceTypeId, objectInfo, rootDir, out);
        } else {
            writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
        }
    } else {
        throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId
                + "] is not supported in renderDataResourceAsText");
    }
}

From source file:com.bitsofproof.btc1k.server.resource.BopShopResource.java

private String executeGet(HttpGet get)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    String authorizationString = "Basic "
            + new String(Base64.encode((customerId + ":" + password).getBytes()), "US-ASCII");
    get.setHeader("Authorization", authorizationString);
    HttpResponse response = client.execute(get);
    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    StringWriter writer = new StringWriter();
    String line;/*from   www . j ava2  s.  com*/
    while ((line = in.readLine()) != null) {
        writer.write(line);
    }
    String req = writer.toString();
    return req;
}

From source file:org.cloudml.connectors.DockerConnector.java

public void BuildImageFromDockerFile(String path) {
    File baseDir = new File(path);

    InputStream response = dockerClient.buildImageCmd(baseDir).exec();

    StringWriter logwriter = new StringWriter();

    try {//from w  ww.  j av  a2s  .c o  m
        LineIterator itr = IOUtils.lineIterator(response, "UTF-8");
        while (itr.hasNext()) {
            String line = itr.next();
            logwriter.write(line);
            journal.log(Level.INFO, line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:org.apache.velocity.tools.generic.log.LogSystemCommonsLog.java

private void log(int level, Object message, Throwable t) {
    if (printStackTrace) {
        StringWriter sw = new StringWriter();
        sw.write(String.valueOf(message));
        t.printStackTrace(new PrintWriter(sw));
        log(level, sw);/*from  ww  w  . j  a  v  a  2s .c o  m*/
    } else {
        StringBuffer buffer = new StringBuffer(String.valueOf(message));
        buffer.append(" - ");
        buffer.append(t.getMessage());
        log(level, buffer);
    }
}

From source file:org.datacleaner.monitor.server.job.ExecutionLoggerImpl.java

@Override
public void log(String message, Throwable throwable) {
    final StringWriter stringWriter = new StringWriter();
    if (message != null) {
        stringWriter.write(message);
        stringWriter.write('\n');
    }/*from w  w w. java  2 s  .c o m*/

    final PrintWriter printWriter = new PrintWriter(stringWriter);
    throwable.printStackTrace(printWriter);
    printWriter.flush();

    log(stringWriter.toString());
}