Example usage for java.io StringWriter toString

List of usage examples for java.io StringWriter toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the buffer's current value as a string.

Usage

From source file:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String xhrRequest(String shrDataString) {
    InputStream is = null;/*from  w  w w .jav a  2  s  . c  om*/
    String json = null;

    try {
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "shrDataString [" + shrDataString + "]");

        Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString));
        String url = (String) xhrData.get("url");
        String method = (String) xhrData.get("method");
        List headers = (List) xhrData.get("headers");
        URL requestURL = createURL(url);
        URI uri = new URI(requestURL.toString());

        HashMap httpMethods = new HashMap(7);
        httpMethods.put("DELETE", new HttpDelete(uri));
        httpMethods.put("GET", new HttpGet(uri));
        httpMethods.put("HEAD", new HttpHead(uri));
        httpMethods.put("OPTIONS", new HttpOptions(uri));
        httpMethods.put("POST", new HttpPost(uri));
        httpMethods.put("PUT", new HttpPut(uri));
        httpMethods.put("TRACE", new HttpTrace(uri));
        HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase());

        if (request.equals(null)) {
            throw new Error("SYNTAX_ERR");
        }

        for (Object header : headers) {
            StringTokenizer st = new StringTokenizer((String) header, ":");
            String name = st.nextToken();
            String value = st.nextToken();
            request.addHeader(name, value);
        }

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Map headerMap = new HashMap();

        HeaderIterator headerIter = response.headerIterator();

        while (headerIter.hasNext()) {
            Header header = headerIter.nextHeader();
            headerMap.put(header.getName(), header.getValue());
        }

        int status = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().toString();

        is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        Map m = new HashMap();
        m.put("status", new Integer(status));
        m.put("statusText", statusText);
        m.put("responseText", sb.toString());
        m.put("headers", headerMap.toString());
        StringWriter w = new StringWriter();
        JSONSerializer.serialize(w, m);
        json = w.toString();
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]");
    } catch (Throwable e) {
        logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "Failed request for [" + shrDataString + "]", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    return json;
}

From source file:com.haulmont.bali.util.Dom4j.java

public static String writeDocument(Document doc, boolean prettyPrint) {
    StringWriter writer = new StringWriter();
    writeDocument(doc, prettyPrint, writer);
    return writer.toString();
}

From source file:com.soa.facepond.util.JsonUtil.java

public static String getJsonStringFromObject(Object obj) {
    try {//  w w  w  . java 2s  .  co  m
        StringWriter sw = new StringWriter();
        JsonGenerator gen = jf.createJsonGenerator(sw);
        new ObjectMapper().writeValue(gen, obj);
        gen.flush();
        return sw.toString();
    } catch (Exception e) {
        log.error("JacksonUtil.getJsonStringFromMap error| ErrMsg: " + e.getMessage());
        return null;
    }
}

From source file:edu.washington.iam.tools.XMLHelper.java

public static String serializeXmlToString(XMLSerializable obj) throws IOException {
    StringWriter sw = new StringWriter();
    BufferedWriter xout = new BufferedWriter(sw);
    obj.writeXml(xout);// w w  w  . ja  v a  2  s  . c o m
    xout.close();
    return sw.toString();
}

From source file:net.cloudkit.enterprises.infrastructure.utilities.JaxbMapperHelper.java

/**
 * Java Collection->Xml with encoding, ?Root ElementCollection.
 *///from   ww w  . j  ava 2 s .com
public static String toXml(Collection<?> root, String rootName, Class<?> clazz, String encoding) {
    try {
        CollectionWrapper wrapper = new CollectionWrapper();
        wrapper.collection = root;

        JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
                CollectionWrapper.class, wrapper);

        StringWriter writer = new StringWriter();
        createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

        return writer.toString();
    } catch (JAXBException e) {
        throw ExceptionHelper.unchecked(e);
    }
}

From source file:Main.java

/**
 *  Classe utilitaria para converter Document em InputSource
 * @param documento//  ww w  .java 2s.  c  o  m
 * @return InputSource
 * @throws TransformerFactoryConfigurationError 
 * @throws TransformerException 
 * @throws TransformerConfigurationException 
 */
private static InputSource converterDoc(Document documento)
        throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {

    Document doc = documento;
    DOMSource source = new DOMSource(doc);
    StringWriter xmlAsWriter = new StringWriter();
    StreamResult result = new StreamResult(xmlAsWriter);
    TransformerFactory.newInstance().newTransformer().transform(source, result);
    StringReader xmlReader = new StringReader(xmlAsWriter.toString());
    InputSource iS = new InputSource(xmlReader);
    return iS;
}

From source file:Main.java

/**
 * Transforms a DOM node to a String.//  w  w w .ja v  a  2  s  .  c  o m
 *
 * @param node the node
 * @return the transformed XML representation
 * @throws TransformerException if a transformation error occurs.
 */
public static String transform(Node node) throws TransformerException {
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    Source source = new DOMSource(node);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(source, result);
    return writer.toString();
}

From source file:com.biomeris.i2b2.export.ws.messages.MessageBuilder.java

public static String buildPMGetServiceRequest(Network network) throws JAXBException {
    com.biomeris.i2b2.export.datavo.pm.ObjectFactory pmObjectFactory = new com.biomeris.i2b2.export.datavo.pm.ObjectFactory();
    com.biomeris.i2b2.export.ws.messages.extensions.ObjectFactory extObjectFactory = new com.biomeris.i2b2.export.ws.messages.extensions.ObjectFactory();

    ProxyedRequestMessageType proxyedRequestMessageType = new ProxyedRequestMessageType();

    Proxy proxy = new Proxy();
    proxy.setRedirectUrl(network.getPmServiceAddress() + PMSERVICE_NAME);
    proxyedRequestMessageType.setProxy(proxy);

    MessageHeaderType messageHeaderType = new MessageHeaderType();
    SecurityType securityType = new SecurityType();
    securityType.setDomain(network.getDomain());
    securityType.setUsername(network.getUsername());
    PasswordType passwordType = JAXB.unmarshal(new StringReader(network.getPassword()), PasswordType.class);
    securityType.setPassword(passwordType);
    messageHeaderType.setSecurity(securityType);
    messageHeaderType.setProjectId(network.getProject());
    ApplicationType applicationType = new ApplicationType();
    applicationType.setApplicationName("Export Cell");
    applicationType.setApplicationVersion("1.0");
    messageHeaderType.setSendingApplication(applicationType);
    proxyedRequestMessageType.setMessageHeader(messageHeaderType);

    RequestHeaderType requestHeaderType = new RequestHeaderType();
    requestHeaderType.setResultWaittimeMs(1800000);
    proxyedRequestMessageType.setRequestHeader(requestHeaderType);

    BodyType bodyType = new BodyType();

    GetUserConfigurationType g = pmObjectFactory.createGetUserConfigurationType();
    g.getProject().add("undefined");
    JAXBElement<GetUserConfigurationType> any1 = pmObjectFactory.createGetUserConfiguration(g);

    bodyType.getAny().add(any1);/*  w w w .  ja va2 s .  c  o  m*/
    proxyedRequestMessageType.setMessageBody(bodyType);

    JAXBContext jc = JAXBContext.newInstance(ProxyedRequestMessageType.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter sw = new StringWriter();
    JAXBElement<ProxyedRequestMessageType> xxx = extObjectFactory.createRequestPM(proxyedRequestMessageType);
    m.marshal(xxx, sw);

    return sw.toString();
}

From source file:com.soa.facepond.util.JsonUtil.java

/**
 * Convert Map<String, String>[] to JackSon string
 *
 * @param list Array of Map<String,String>
 * @return jackson string/*from   w w w . jav  a 2  s .  c o m*/
 */
public static String getJsonStringFromList(List<Map<String, String>> list) {
    try {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = jf.createJsonGenerator(sw);
        new ObjectMapper().writeValue(gen, list);
        gen.flush();
        return sw.toString();
    } catch (Exception e) {
        log.error("JacksonUtil.getJsonStringFromMap error| ErrMsg: " + e.getMessage());
        return null;
    }
}

From source file:com.soa.facepond.util.JsonUtil.java

/**
 * Convert Map<String, String> to JackSon string
 *
 * @param aMap Map//from  w ww  . j av a2  s . c  o m
 * @return Map<String, String>
 */
public static String getJsonStringFromMap(Map<String, String> aMap) {
    try {
        StringWriter sw = new StringWriter();
        JsonGenerator gen = jf.createJsonGenerator(sw);
        new ObjectMapper().writeValue(gen, aMap);
        gen.flush();
        return sw.toString();
    } catch (Exception e) {
        log.error("ErrMsg: " + e.getMessage());
        return null;
    }
}