Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:io.fabric8.insight.log.support.LogQuerySupport.java

protected static String loadString(URL url) throws IOException {
    InputStream is = url.openStream();
    if (is == null) {
        return null;
    }/*  w  w  w  . j  av  a2s.  c  om*/
    try {
        InputStreamReader reader = new InputStreamReader(is);
        StringWriter writer = new StringWriter();
        final char[] buffer = new char[4096];
        int n;
        while (-1 != (n = reader.read(buffer))) {
            writer.write(buffer, 0, n);
        }
        writer.flush();
        return writer.toString();
    } finally {
        is.close();
    }
}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static String getResponseMessage(final HttpEntity httpEntity) throws IOException {

    final StringWriter writer = new StringWriter();
    IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8);
    final String response = writer.toString();
    writer.flush();
    writer.close();/* w w w .  j av a2  s .  com*/

    return response;
}

From source file:org.wso2.carbon.humantask.core.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *
 * @param node DOM Node/*from  w  w w  . j a  v a 2  s .  c  o m*/
 * @return String
 */
public static String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static String getStackTrace(Throwable t) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter, true);
    t.printStackTrace(printWriter);//  w  ww  .  j a v  a 2  s.  c  om
    printWriter.flush();
    stringWriter.flush();
    return stringWriter.toString();
}

From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java

/** Generic function for calling web services with parameters which are more than one level deep.<BR>
 * Directly returns the webservice results if callback is null.
 * //w ww. j a v  a  2s.  c o  m
 * @param parameterMap - name, value pairs map for all the parameters(OMEChild) to be sent to the service, if a value is another LinkedHashMap, then it is assumed to contain subnodes of that parameter's key node.
 * @param serviceMethod - name of the specific method of the service to be called.  e.g. "copyDataFilesToAnalysis"
 * @param serviceName - name of the web service to invoke, e.g. "dataTransferService"
 * @param serviceURL - URL of machine the web service runs from. e.g. "http://icmv058.icm.jhu.edu:8080/axis2/services/"
 * @param callback - function to which the service will return result XML to. Calls service without callback if null.
 * @param filesMap - name, value pairs map for all the files(OMEChild) to be sent to the service.
 * @return
 */
public static OMElement callWebServiceComplexParam(Map<String, ?> parameterMap, String serviceMethod,
        String serviceName, String serviceURL, SvcAxisCallback callback, Map<String, FSFile> filesMap) {
    log.info("waveform-utilities.WebServiceUtility.callWebServiceComplexParam()");

    String serviceTarget = "";

    if (serviceName != null) {
        if (!serviceName.equals("")) {
            serviceTarget = serviceName; // + "/" + serviceMethod;
        } else {
            serviceTarget = serviceMethod;
        }
    }

    EndpointReference targetEPR = new EndpointReference(serviceURL + "/" + serviceTarget);

    OMFactory omFactory = OMAbstractFactory.getOMFactory();

    OMNamespace omNamespace = omFactory.createOMNamespace(serviceURL + "/" + serviceName, serviceName);
    OMElement omWebService = omFactory.createOMElement(serviceMethod, omNamespace);

    extractParameter(parameterMap, omFactory, omNamespace, omWebService);

    addFiles(filesMap, omWebService, omFactory, omNamespace);

    ServiceClient sender = getSender(targetEPR, serviceMethod);

    OMElement result = null;
    try {
        if (callback == null) {
            log.info("Service/method, no callback:" + serviceName + "/" + serviceMethod);
            //  Directly invoke an anonymous operation with an In-Out message exchange pattern.
            result = sender.sendReceive(omWebService);
            StringWriter writer = new StringWriter();
            result.serialize(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));
            writer.flush();
        } else {
            log.info("Service/method, WITH callback:" + serviceName + "/" + serviceMethod);
            // Directly invoke an anonymous operation with an In-Out message exchange pattern without waiting for a response.
            sender.sendReceiveNonBlocking(omWebService, callback);
        }
    } catch (AxisFault e) {
        e.printStackTrace();
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (FactoryConfigurationError e) {
        e.printStackTrace();
    }

    return result;
}

From source file:net.erdfelt.android.sdkfido.project.FilteredFileUtil.java

public static String loadExpandedAsString(String resourceId, Map<String, String> props)
        throws OutputProjectException {
    LOG.log(Level.INFO, "Loading resource: " + resourceId);
    if (StringUtils.isBlank(resourceId)) {
        throw new IllegalArgumentException("resourceId cannot be blank");
    }// ww  w  .j  a v  a2  s  .  c o m
    URL url = FilteredFileUtil.class.getResource(resourceId);
    if (url == null) {
        throw new OutputProjectException("Unable to find resourceID: " + resourceId);
    }

    InputStream in = null;
    InputStreamReader reader = null;
    BufferedReader buf = null;
    StringWriter writer = null;
    PrintWriter out = null;
    try {
        in = url.openStream();
        reader = new InputStreamReader(in);
        buf = new BufferedReader(reader);
        writer = new StringWriter();
        out = new PrintWriter(writer);

        PropertyExpander expander = new PropertyExpander(props);
        String line;

        while ((line = buf.readLine()) != null) {
            out.println(expander.expand(line));
        }

        out.flush();
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new OutputProjectException("Unable to open input stream for url: " + url, e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(buf);
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.aurel.track.item.SendItemEmailBL.java

public static String getItemInfo(WorkItemContext workItemContext, boolean useProjectSpecificID, Locale locale) {
    Integer workItemID = workItemContext.getWorkItemBean().getObjectID();
    String infoHtml = "";
    TWorkItemBean workItemBean = workItemContext.getWorkItemBean();
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("issueNoLabel",
            FieldRuntimeBL.getLocalizedDefaultFieldLabel(SystemFields.INTEGER_ISSUENO, locale));

    String statusDisplay = "";
    IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(SystemFields.INTEGER_STATE);
    if (workItemBean != null) {
        Object state = workItemBean.getAttribute(SystemFields.INTEGER_STATE);
        statusDisplay = fieldTypeRT.getShowValue(state, locale);
    }//from  w  w  w .j  a  v  a2  s . c om
    root.put("statusDisplay", statusDisplay);
    root.put("synopsis", workItemBean.getSynopsis());
    root.put("workItemID", workItemID);
    String id = "";
    if (useProjectSpecificID) {
        id = ItemBL.getSpecificProjectID(workItemContext);
    } else {
        id = workItemBean.getObjectID().toString();
    }
    root.put("itemID", id);
    root.put("screenBean", ItemBL.loadFullRuntimeScreenBean(workItemContext.getScreenID()));

    Map<String, String> fieldLabels = new HashMap<String, String>();
    Map<String, String> fieldDisplayValues = new HashMap<String, String>();
    Map<Integer, TFieldConfigBean> mapFieldsConfig = workItemContext.getFieldConfigs();
    Iterator<Integer> it = mapFieldsConfig.keySet().iterator();
    while (it.hasNext()) {
        Integer fieldID = it.next();
        TFieldConfigBean cfg = mapFieldsConfig.get(fieldID);
        fieldLabels.put("f_" + fieldID, cfg.getLabel());
        String displayValue = SendItemEmailBL.getFieldDisplayValue(fieldID, workItemContext,
                useProjectSpecificID);
        fieldDisplayValues.put("f_" + fieldID, displayValue);
    }
    root.put("fieldLabels", fieldLabels);
    root.put("fieldDisplayValues", fieldDisplayValues);
    try {
        URL propURL = ApplicationBean.getInstance().getServletContext()
                .getResource("/WEB-INF/classes/template/printItem.ftl");
        InputStream in = propURL.openStream();
        Template fmtemplate = new Template("name", new InputStreamReader(in));
        StringWriter w = new StringWriter();
        try {
            fmtemplate.process(root, w);
        } catch (Exception e) {
            LOGGER.error(
                    "Processing reminder template " + fmtemplate.getName() + " failed with " + e.getMessage());
        }
        w.flush();
        infoHtml = w.toString();
    } catch (Exception ex) {
        LOGGER.error(ExceptionUtils.getStackTrace(ex));
    }
    return infoHtml;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets <tt>ODataEntitySet</tt> from the given feed resource.
 *
 * @param resource feed resource./*w  w  w  .  j av  a  2s .  c o m*/
 * @param defaultBaseURI default base URI.
 * @return <tt>ODataEntitySet</tt> object.
 */
public static ODataEntitySet getODataEntitySet(final FeedResource resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        Serializer.feed(resource, writer);
        writer.flush();
        LOG.debug("FeedResource -> ODataEntitySet:\n{}", writer.toString());
    }

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final URI next = resource.getNext();

    final ODataEntitySet entitySet = next == null ? ODataFactory.newEntitySet()
            : ODataFactory.newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getCount() != null) {
        entitySet.setCount(resource.getCount());
    }

    for (EntryResource entryResource : resource.getEntries()) {
        entitySet.addEntity(getODataEntity(entryResource));
    }

    return entitySet;
}

From source file:nl.nn.adapterframework.align.Json2Xml.java

public static String translate(JsonStructure json, URL schemaURL, boolean compactJsonArrays, String rootElement,
        boolean strictSyntax, boolean deepSearch, String targetNamespace, Map<String, Object> overrideValues)
        throws SAXException, IOException {

    // create the ValidatorHandler
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(schemaURL);
    ValidatorHandler validatorHandler = schema.newValidatorHandler();

    // create the XSModel
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(schemaURL.toExternalForm());
    List<XSModel> schemaInformation = new LinkedList<XSModel>();
    schemaInformation.add(xsModel);/*www.  j ava  2 s  .  c om*/

    // create the validator, setup the chain
    Json2Xml j2x = new Json2Xml(validatorHandler, schemaInformation, compactJsonArrays, rootElement,
            strictSyntax);
    if (overrideValues != null) {
        j2x.setOverrideValues(overrideValues);
    }
    if (targetNamespace != null) {
        //if (DEBUG) System.out.println("setting targetNamespace ["+targetNamespace+"]");
        j2x.setTargetNamespace(targetNamespace);
    }
    j2x.setDeepSearch(deepSearch);
    Source source = j2x.asSource(json);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    String xml = null;
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(source, result);
        writer.flush();
        xml = writer.toString();
    } catch (TransformerConfigurationException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    } catch (TransformerException e) {
        SAXException se = new SAXException(e);
        se.initCause(e);
        throw se;
    }
    return xml;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

/**
 * Gets <tt>ODataEntity</tt> from the given entry resource.
 *
 * @param resource entry resource./*from w  w  w. j  a  v  a2  s  .  co  m*/
 * @param defaultBaseURI default base URI.
 * @return <tt>ODataEntity</tt> object.
 */
public static ODataEntity getODataEntity(final EntryResource resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        Serializer.entry(resource, writer);
        writer.flush();
        LOG.debug("EntryResource -> ODataEntity:\n{}", writer.toString());
    }

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final ODataEntity entity = resource.getSelfLink() == null ? ODataFactory.newEntity(resource.getType())
            : ODataFactory.newEntity(resource.getType(),
                    URIUtils.getURI(base, resource.getSelfLink().getHref()));

    if (StringUtils.isNotBlank(resource.getETag())) {
        entity.setETag(resource.getETag());
    }

    if (resource.getEditLink() != null) {
        entity.setEditLink(URIUtils.getURI(base, resource.getEditLink().getHref()));
    }

    for (LinkResource link : resource.getAssociationLinks()) {
        entity.addLink(ODataFactory.newAssociationLink(link.getTitle(), base, link.getHref()));
    }

    for (LinkResource link : resource.getNavigationLinks()) {
        final EntryResource inlineEntry = link.getInlineEntry();
        final FeedResource inlineFeed = link.getInlineFeed();

        if (inlineEntry == null && inlineFeed == null) {
            entity.addLink(ODataFactory.newEntityNavigationLink(link.getTitle(), base, link.getHref()));
        } else if (inlineFeed == null) {
            entity.addLink(ODataFactory.newInlineEntity(link.getTitle(), base, link.getHref(), getODataEntity(
                    inlineEntry, inlineEntry.getBaseURI() == null ? base : inlineEntry.getBaseURI())));
        } else {
            entity.addLink(
                    ODataFactory.newInlineEntitySet(link.getTitle(), base, link.getHref(), getODataEntitySet(
                            inlineFeed, inlineFeed.getBaseURI() == null ? base : inlineFeed.getBaseURI())));
        }
    }

    for (LinkResource link : resource.getMediaEditLinks()) {
        entity.addLink(ODataFactory.newMediaEditLink(link.getTitle(), base, link.getHref()));
    }

    for (ODataOperation operation : resource.getOperations()) {
        operation.setTarget(URIUtils.getURI(base, operation.getTarget()));
        entity.addOperation(operation);
    }

    final Element content;
    if (resource.isMediaEntry()) {
        entity.setMediaEntity(true);
        entity.setMediaContentSource(resource.getMediaContentSource());
        entity.setMediaContentType(resource.getMediaContentType());
        content = resource.getMediaEntryProperties();
    } else {
        content = resource.getContent();
    }
    if (content != null) {
        for (Node property : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
            try {
                entity.addProperty(getProperty((Element) property));
            } catch (IllegalArgumentException e) {
                LOG.warn("Failure retrieving EdmType for {}", property.getTextContent(), e);
            }
        }
    }

    return entity;
}