Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:de.tu_dortmund.ub.data.dswarm.Init.java

public String call() {

    final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER);
    final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER);
    final Optional<Boolean> optionalEnhanceInputDataResource = TPUUtil
            .getBooleanConfigValue(TPUStatics.ENHANCE_INPUT_DATA_RESOURCE, config);

    LOG.info(String.format("[%s][%d] Starting 'Init (Task)' ...", serviceName, cnt));

    try {/*from  ww w. j  a  v a 2  s. c  om*/

        final boolean doIngest;

        final String doIngestString = config.getProperty(TPUStatics.DO_INITIAL_DATA_MODEL_INGEST_IDENTIFIER);

        if (doIngestString != null && !doIngestString.trim().isEmpty()) {

            doIngest = Boolean.valueOf(doIngestString);
        } else {

            // default = true
            doIngest = true;
        }

        if (doIngest) {

            LOG.debug("[{}][{}] do data model creation with data ingest", serviceName, cnt);

            TPUUtil.initSchemaIndices(serviceName, config);
        }

        final String configurationFileName = config.getProperty(TPUStatics.CONFIGURATION_NAME_IDENTIFIER);
        final String configurationJSONString = readFile(configurationFileName, Charsets.UTF_8);
        final JsonObject configurationJSON = TPUUtil.getJsonObject(configurationJSONString);

        final String finalInputResourceFile;

        if (optionalEnhanceInputDataResource.isPresent()
                && Boolean.TRUE.equals(optionalEnhanceInputDataResource.get())) {

            final Optional<String> optionalUpdatedInputResourceFile = enhanceInputDataResource(initResourceFile,
                    configurationJSON);

            if (optionalUpdatedInputResourceFile.isPresent()) {

                finalInputResourceFile = optionalUpdatedInputResourceFile.get();
            } else {

                finalInputResourceFile = initResourceFile;
            }
        } else {

            finalInputResourceFile = initResourceFile;
        }

        final String name = String.format("resource for project '%s'", initResourceFile);
        final String description = String.format("'resource does not belong to a project' - case %d", cnt);
        final String inputResourceJson = uploadFileAndCreateResource(finalInputResourceFile, name, description,
                serviceName, engineDswarmAPI);

        if (inputResourceJson == null) {

            final String message = "something went wrong at resource creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject inputResourceJSON = TPUUtil.getJsonObject(inputResourceJson);
        final String inputResourceID = inputResourceJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] input resource id = %s", serviceName, cnt, inputResourceID));

        if (inputResourceID == null) {

            final String message = "something went wrong at resource creation, no resource uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // TODO: refactor this, so that a configuration only needs to be create once per TPU task
        // create configuration
        final String finalConfigurationJSONString = createConfiguration(configurationJSONString, serviceName,
                engineDswarmAPI);

        if (finalConfigurationJSONString == null) {

            final String message = "something went wrong at configuration creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject finalConfigurationJSON = TPUUtil.getJsonObject(finalConfigurationJSONString);
        final String configurationID = finalConfigurationJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] configuration id = %s", serviceName, cnt, configurationID));

        if (configurationID == null) {

            final String message = "something went wrong at configuration creation, no configuration uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // check for existing input schema
        final Optional<JsonObject> optionalInputSchema = getInputSchema(serviceName, engineDswarmAPI);

        // create the datamodel (will use it's resource)
        final String dataModelName = String.format("data model %d", cnt);
        final String dataModelDescription = String.format("data model description %d", cnt);
        final String dataModelJSONString = createDataModel(inputResourceJSON, finalConfigurationJSON,
                optionalInputSchema, dataModelName, dataModelDescription, serviceName, engineDswarmAPI,
                doIngest);

        if (dataModelJSONString == null) {

            final String message = "something went wrong at data model creation";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        final JsonObject dataModelJSON = TPUUtil.getJsonObject(dataModelJSONString);
        final String dataModelID = dataModelJSON.getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s][%d] data model id = %s", serviceName, cnt, dataModelID));

        if (dataModelID == null) {

            final String message = "something went wrong at data model creation, no data model uuid available";

            LOG.error(message);

            throw new RuntimeException(message);
        }

        // we don't need to transform after each ingest of a slice of records,
        // so transform and export will be done separately
        LOG.info(String.format("[%s][%d] (Note: Only ingest, but no transformation or export done.)",
                serviceName, cnt));

        final StringWriter stringWriter = new StringWriter();
        final JsonGenerator jp = Json.createGenerator(stringWriter);

        jp.writeStartObject();
        jp.write(DATA_MODEL_ID, dataModelID);
        jp.write(RESOURCE_ID, inputResourceID);
        jp.write(CONFIGURATION_ID, configurationID);
        jp.writeEnd();

        jp.flush();
        jp.close();

        final String result = stringWriter.toString();

        stringWriter.flush();
        stringWriter.close();

        return result;
    } catch (final Exception e) {

        final String message = String.format("[%s][%d] Processing resource '%s' failed with a %s", serviceName,
                cnt, initResourceFile, e.getClass().getSimpleName());

        LOG.error(message, e);

        throw new RuntimeException(message, e);
    }
}

From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

protected String readCode(DesignMetadata md) throws FileNotFoundException, IOException, WGDesignSyncException,
        InstantiationException, IllegalAccessException {

    // No, filecontainers have no code, but thanks for asking....
    if (getType() == WGDocument.TYPE_FILECONTAINER) {
        return null;
    }/*  w  ww  .  j  ava2  s .  c o  m*/

    FileObject codeFile = getCodeFile();
    if (!codeFile.exists()) {
        throw new WGDesignSyncException("Code of file '" + getCodeFile().getName().getPath()
                + "' could not be read because the file does not exist.");
    }

    LineNumberReader reader = new LineNumberReader(createReader(codeFile));
    StringWriter writer = new StringWriter();
    int headerLines = 0;
    try {
        String line;
        boolean lookForHeaders = true;
        boolean firstLine = true;

        while ((line = reader.readLine()) != null) {
            if (lookForHeaders == true && line.startsWith("##")) {
                processDesignHeader(line, md.getInfo());
                headerLines++;
            } else {
                lookForHeaders = false;

                if (!firstLine) {
                    writer.write("\n");
                } else {
                    firstLine = false;
                }

                writer.write(line);
            }
        }
    } finally {
        reader.close();
        codeFile.getContent().close();
    }
    writer.close();
    md.setHeaderLines(headerLines);
    String code = writer.toString();
    return code;
}

From source file:org.tequila.template.engine.FreemarkerEngine.java

@Override
public void match(TemplateModel templateModel) {

    try {//from  w  ww  .jav a  2s  .  co  m
        TemplateDef templateDef = templateModel.getTemplateDef();
        InputStream is = templateDef.getLocation().getInputStream();
        InputStreamReader reader = new InputStreamReader(is);
        Template template = new Template(templateDef.getName(), reader, cfg);

        StringWriter sw = new StringWriter();

        // create model root
        Map root = new HashMap();

        // put directives
        root.putAll(directivesWrapped);

        // ${project}
        root.putAll(projectWrapped);
        // ${metapojos}
        List<MetaPojo> metaPojos = templateModel.getMetaPojos();
        if (metaPojos != null) {
            Object metaPojosWrapped = getEngineWrappersFactory().getMetaPojosWrapper().wrap(metaPojos);
            root.putAll((Map) metaPojosWrapped);
        }

        // ${metaproperty}
        MetaProperty metaProperty = templateModel.getMetaProperty();
        if (metaProperty != null) {
            MetaPropertyWrapper metaPropertyWrapper = getEngineWrappersFactory().getMetaPropertyWrapper();
            Object metaPropertyWrapped = metaPropertyWrapper.wrap(metaProperty);
            root.putAll((Map) metaPropertyWrapped);
        }

        Environment env = template.createProcessingEnvironment(root, sw);
        env.process(); // process the template
        sw.close();
        log.debug("->Resultado del matcheo:" + sw.toString());
    } catch (TemplateException ex) {
        String templateName = templateModel.getTemplateDef().getName();
        throw new MatchException("No se pudo hacer match del template '" + templateName
                + "' por un error en la definicin del template", ex);
    } catch (IOException ex) {
        String templateName = templateModel.getTemplateDef().getName();
        throw new MatchException(
                "No se pudo hacer match del template '" + templateName + "' por un error de i/o", ex);
    }
}

From source file:uk.ac.ebi.embl.api.validation.EnaValidator.java

/**
 * Validate files./*ww w . j  ava 2  s .co m*/
 * @throws ValidationEngineException
 */
private void validateFiles() {
    List<ValidationPlanResult> planResults = new ArrayList<ValidationPlanResult>();
    int parseErrorCount = 0;
    try {
        long timeIn = System.currentTimeMillis();

        if (filterMode && filterPrefix != null) {
            goodFilesWriter = new FileWriter(filterPrefix + "_good.txt");
            badFilesWriter = new FileWriter(filterPrefix + "_bad.txt");
        }

        for (File file : entryFiles) {
            List<ValidationPlanResult> results = validateFile(file, errorWriter);
            planResults.addAll(results);
        }

        infoWriter.flush();
        errorWriter.flush();
        reportWriter.flush();
        fixWriter.flush();

        infoWriter.close();
        errorWriter.close();
        reportWriter.close();
        fixWriter.close();

        if (filterMode && filterPrefix != null) {
            badFilesWriter.flush();
            badFilesWriter.close();
            goodFilesWriter.flush();
            goodFilesWriter.close();
        }

        List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>();

        for (ValidationPlanResult planResult : planResults) {
            messages.addAll(planResult.getMessages());
        }
        for (ValidationResult parseResult : parseResults) {
            messages.addAll(parseResult.getMessages());
            for (ValidationMessage message : parseResult.getMessages()) {
                parseErrorCount++;
            }
        }

        /**
         * will be built up to form the summary for the whole run
         */
        String summaryLine = "";

        if (!planResults.isEmpty()) {
            FlattenedMessageResult results = Utils.flattenMessages(messages, MESSAGE_FLATTEN_THRESHOLD);
            List<ValidationMessage> flattenedMessages = results.getFlattenedMessages();
            List<ValidationMessage> unFlattenedMessages = results.getUnFlattenedMessages();

            Collections.sort(flattenedMessages, new ValidationMessageComparator());
            Collections.sort(unFlattenedMessages, new ValidationMessageComparator());

            if (!flattenedMessages.isEmpty()) {
                summaryLine = summaryLine.concat("\n\n***MESSAGES SUMMARY***");
                summaryLine = summaryLine.concat(
                        "\nCompressed messages (occurring more than " + MESSAGE_FLATTEN_THRESHOLD + " times)");
                for (ValidationMessage message : flattenedMessages) {
                    summaryLine = summaryLine.concat("\n" + message.getSeverity());
                    summaryLine = summaryLine.concat(": ");
                    summaryLine = summaryLine.concat(message.getMessage());
                    summaryLine = summaryLine.concat(" (" + message.getMessageKey() + ") ");
                }
            }

            if (!unFlattenedMessages.isEmpty()) {
                summaryLine = summaryLine.concat("\n\nMessages");
                for (ValidationMessage message : unFlattenedMessages) {

                    summaryLine = summaryLine.concat("\n" + message.getSeverity());
                    summaryLine = summaryLine.concat(": ");
                    summaryLine = summaryLine.concat(message.getMessage());
                    summaryLine = summaryLine.concat(" (" + message.getMessageKey() + ") ");
                    for (Object origin : message.getOrigins()) {
                        StringWriter writer = new StringWriter();
                        String text = ((Origin) origin).getOriginText();
                        writer.write(text);
                        summaryLine = summaryLine.concat(writer.toString());
                        writer.close();
                    }
                }
            }

            summaryLine = summaryLine.concat("\n\n***FILE SUMMARY***\n");
            List<FlattenedValidationPlanResult> flattenedPlanResults = Utils
                    .flattenValidationPlans(planResults);
            for (FlattenedValidationPlanResult flattenedResult : flattenedPlanResults) {
                summaryLine = summaryLine.concat(flattenedResult.getFileName() + " - ");
                summaryLine = summaryLine.concat(flattenedResult.getEntryCount() + " entries, ");
                summaryLine = summaryLine.concat(flattenedResult.getFailedEntryCount() + " failed entries, ");
                summaryLine = summaryLine
                        .concat((flattenedResult.getErrorCount() + parseErrorCount) + " errors, ");
                summaryLine = summaryLine.concat(flattenedResult.getFixCount() + " fixes, ");
                summaryLine = summaryLine.concat(flattenedResult.getWarningInfoCount() + " warnings & info");
                summaryLine = summaryLine.concat("\n");
            }
        }

        summaryLine = summaryLine.concat("\n*** SUMMARY***\n");

        summaryLine = summaryLine.concat("Fixed Entries:" + fixCount + "\n");
        summaryLine = summaryLine.concat("Failed Entries:" + failCount + "\n");
        summaryLine = summaryLine.concat("Checked Entries:" + totalEntryCount + "\n");
        summaryLine = summaryLine.concat("Unchanged Entries:" + unchangedCount + "\n");
        long timeOut = System.currentTimeMillis();

        long timeToRun = (timeOut - timeIn) / 1000;

        summaryLine = summaryLine
                .concat("\n\nProcessed " + totalEntryCount + " entries in " + timeToRun + " seconds.\n\n");
        printMessage(summaryLine, LOG_LEVEL_SUMMARY);

        summaryWriter.write(summaryLine);
        summaryWriter.flush();
        summaryWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.xmlcalabash.library.HttpRequest.java

private void doPutOrPostSinglepart(EntityEnclosingMethod method, XdmNode body) {
    // ATTENTION: This doesn't handle multipart, that's done entirely separately

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Check for consistency of content-type
    contentType = body.getAttributeValue(_content_type);
    if (contentType == null) {
        throw new XProcException(step.getNode(), "Content-type on c:body is required.");
    }//ww w .  jav  a2  s  .com

    if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) {
        throw XProcException.stepError(20);
    }

    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    String postContent = null;
    String encoding = body.getAttributeValue(_encoding);
    try {
        if ("base64".equals(encoding)) {
            String charset = body.getAttributeValue(_charset);
            // FIXME: is utf-8 the right default?
            if (charset == null) {
                charset = "utf-8";
            }
            String escapedContent = decodeBase64(body, charset);
            StringWriter writer = new StringWriter();
            writer.write(escapedContent);
            writer.close();
            postContent = writer.toString();
        } else {
            if (jsonContentType(contentType)) {
                postContent = XMLtoJSON.convert(body);
            } else if (xmlContentType(contentType)) {
                Serializer serializer = makeSerializer();

                if (!S9apiUtils.isDocumentContent(body.axisIterator(Axis.CHILD))) {
                    throw XProcException.stepError(22);
                }

                Vector<XdmNode> content = new Vector<XdmNode>();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    content.add(node);
                }

                // FIXME: set serializer properties appropriately!
                StringWriter writer = new StringWriter();
                serializer.setOutputWriter(writer);
                S9apiUtils.serialize(runtime, content, serializer);
                writer.close();
                postContent = writer.toString();
            } else {
                StringWriter writer = new StringWriter();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    if (node.getNodeKind() != XdmNodeKind.TEXT) {
                        throw XProcException.stepError(28);
                    }
                    writer.write(node.getStringValue());
                }
                writer.close();
                postContent = writer.toString();
            }
        }

        StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8");
        method.setRequestEntity(requestEntity);

    } catch (IOException ioe) {
        throw new XProcException(ioe);
    } catch (SaxonApiException sae) {
        throw new XProcException(sae);
    }
}

From source file:org.apache.axiom.om.impl.llom.OMSourcedElementImpl.java

public String toString() {
    if (isExpanded) {
        return super.toString();
    } else if (isDestructiveWrite()) {
        forceExpand();/* ww w .  jav a2s.  c  om*/
        return super.toString();
    } else {
        try {
            StringWriter writer = new StringWriter();
            OMOutputFormat format = new OMOutputFormat();
            dataSource.serialize(writer, format);
            String text = writer.toString();
            writer.close();
            return text;
        } catch (XMLStreamException e) {
            throw new RuntimeException("Cannot serialize OM Element " + this.getLocalName(), e);
        } catch (IOException e) {
            throw new RuntimeException("Cannot serialize OM Element " + this.getLocalName(), e);
        }
    }
}

From source file:org.opcfoundation.ua.stacktest.io.TestSequenceWriter.java

public String write(TestSequence testSequence) {
    try {/*  w ww .j  ava 2  s .  co m*/
        // 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:TDS.Shared.Messages.MessageJson.java

public String create() throws ReturnStatusException {
    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator jsonWriter;//from  w  ww.ja  v a2s  .co m

    try {
        if (_messageSystem == null)
            return "{}";

        jsonWriter = jsonFactory.createGenerator(sw);
        jsonWriter.writeStartObject();

        jsonWriter.writeStringField("c_l", _language); // "c_l": _language
        jsonWriter.writeFieldName("c_a"); // "c_a" :
        jsonWriter.writeStartArray(); // [

        // get all the message contexts across all the context types
        List<MessageContext> messageContexts = new ArrayList<MessageContext>();
        for (MessageContextType contextType : _messageSystem.getContextTypes()) {
            messageContexts.addAll(contextType.getContexts());
        }

        for (MessageContext messageContext : messageContexts) {
            writeContextElement(messageContext, jsonWriter);
        }

        jsonWriter.writeEndArray(); // ]
        jsonWriter.writeEndObject(); // }

        jsonWriter.close();
        sw.close();
    } catch (IOException e) {
        ReturnStatus rs = new ReturnStatus("failed", "Serialization failed: " + e.getMessage());
        throw new ReturnStatusException(rs);
    }

    return sw.getBuffer().toString();
}

From source file:org.sakaiproject.search.component.service.impl.BaseSearchServiceImpl.java

public String searchXML(Map parameterMap) {
    String userid = null;//  w  ww. j a v  a 2  s.c om
    String searchTerms = null;
    String checksum = null;
    String contexts = null;
    String ss = null;
    String se = null;
    try {
        if (!searchServer) {
            throw new Exception(Messages.getString("SearchServiceImpl.49")); //$NON-NLS-1$
        }
        String[] useridA = (String[]) parameterMap.get(REST_USERID);
        String[] searchTermsA = (String[]) parameterMap.get(REST_TERMS);
        String[] checksumA = (String[]) parameterMap.get(REST_CHECKSUM);
        String[] contextsA = (String[]) parameterMap.get(REST_CONTEXTS);
        String[] ssA = (String[]) parameterMap.get(REST_START);
        String[] seA = (String[]) parameterMap.get(REST_END);

        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\"?>"); //$NON-NLS-1$

        boolean requestError = false;
        if (useridA == null || useridA.length != 1) {
            requestError = true;
        } else {
            userid = useridA[0];
        }
        if (searchTermsA == null || searchTermsA.length != 1) {
            requestError = true;
        } else {
            searchTerms = searchTermsA[0];
        }
        if (checksumA == null || checksumA.length != 1) {
            requestError = true;
        } else {
            checksum = checksumA[0];
        }
        if (contextsA == null || contextsA.length != 1) {
            requestError = true;
        } else {
            contexts = contextsA[0];
        }
        if (ssA == null || ssA.length != 1) {
            requestError = true;
        } else {
            ss = ssA[0];
        }
        if (seA == null || seA.length != 1) {
            requestError = true;
        } else {
            se = seA[0];
        }

        if (requestError) {
            throw new Exception(Messages.getString("SearchServiceImpl.34")); //$NON-NLS-1$

        }

        int searchStart = Integer.parseInt(ss);
        int searchEnd = Integer.parseInt(se);
        String[] ctxa = contexts.split(";"); //$NON-NLS-1$
        List<String> ctx = new ArrayList<String>(ctxa.length);
        for (int i = 0; i < ctxa.length; i++) {
            ctx.add(ctxa[i]);
        }

        if (sharedKey != null && sharedKey.length() > 0) {
            String check = digestCheck(userid, searchTerms);
            if (!check.equals(checksum)) {
                throw new Exception(Messages.getString("SearchServiceImpl.53")); //$NON-NLS-1$
            }
        }

        org.sakaiproject.tool.api.Session s = sessionManager.startSession();
        User u = userDirectoryService.getUser("admin"); //$NON-NLS-1$
        s.setUserId(u.getId());
        sessionManager.setCurrentSession(s);
        localSearch.set("localsearch"); //$NON-NLS-1$
        try {

            SearchList sl = search(searchTerms, ctx, searchStart, searchEnd);
            sb.append("<results "); //$NON-NLS-1$
            sb.append(" fullsize=\"").append(sl.getFullSize()) //$NON-NLS-1$
                    .append("\" "); //$NON-NLS-1$
            sb.append(" start=\"").append(sl.getStart()).append("\" "); //$NON-NLS-1$ //$NON-NLS-2$
            sb.append(" size=\"").append(sl.size()).append("\" "); //$NON-NLS-1$ //$NON-NLS-2$
            sb.append(" >"); //$NON-NLS-1$
            for (Iterator<SearchResult> si = sl.iterator(); si.hasNext();) {
                SearchResult sr = (SearchResult) si.next();
                sr.toXMLString(sb);
            }
            sb.append("</results>"); //$NON-NLS-1$
            return sb.toString();
        } finally {
            sessionManager.setCurrentSession(null);
            localSearch.set(null);
        }
    } catch (Exception ex) {
        log.error("Search Service XML response failed ", ex);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\"?>"); //$NON-NLS-1$
        sb.append("<fault>"); //$NON-NLS-1$
        sb.append("<request>"); //$NON-NLS-1$
        sb.append("<![CDATA["); //$NON-NLS-1$
        sb.append(" userid = ").append(StringEscapeUtils.escapeXml(userid)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" searchTerms = ").append(StringEscapeUtils.escapeXml(searchTerms)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" checksum = ").append(StringEscapeUtils.escapeXml(checksum)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" contexts = ").append(StringEscapeUtils.escapeXml(contexts)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" ss = ").append(StringEscapeUtils.escapeXml(ss)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(" se = ").append(StringEscapeUtils.escapeXml(se)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append("]]>"); //$NON-NLS-1$
        sb.append("</request>"); //$NON-NLS-1$
        sb.append("<error>"); //$NON-NLS-1$
        sb.append("<![CDATA["); //$NON-NLS-1$
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            sb.append(sw.toString());
            pw.close();
            sw.close();
        } catch (Exception ex2) {
            sb.append("Failed to serialize exception " + ex.getMessage()) //$NON-NLS-1$
                    .append("\n"); //$NON-NLS-1$
            sb.append("Case:  " + ex2.getMessage()); //$NON-NLS-1$

        }
        sb.append("]]>"); //$NON-NLS-1$
        sb.append("</error>"); //$NON-NLS-1$
        sb.append("</fault>"); //$NON-NLS-1$
        return sb.toString();
    }
}

From source file:org.wso2.carbon.apimgt.tracing.TracingReporter.java

/**
 * Get the structured log message format
 *
 * @param timeStamp timeStamp Instant//from  w  w  w  .  j  a va 2 s  .c o m
 * @param span      opentracing SpanData
 * @return structured log message format String
 * */
private String toStructuredMessage(Instant timeStamp, SpanData span) {
    try {
        StringWriter writer = new StringWriter();
        JsonGenerator generator = this.jsonFactory.createGenerator(writer);
        generator.writeStartObject();
        generator.writeNumberField(TracingConstants.LATENCY,
                Duration.between(span.startAt, timeStamp).toMillis());
        generator.writeStringField(TracingConstants.OPERATION_NAME, span.operationName);
        generator.writeObjectFieldStart(TracingConstants.TAGS);
        Iterator itr = span.tags.entrySet().iterator();

        Map.Entry map;
        Object value;
        while (itr.hasNext()) {
            map = (Map.Entry) itr.next();
            value = map.getValue();
            if (value instanceof String) {
                generator.writeStringField((String) map.getKey(), (String) value);
            } else if (value instanceof Number) {
                generator.writeNumberField((String) map.getKey(), ((Number) value).doubleValue());
            } else if (value instanceof Boolean) {
                generator.writeBooleanField((String) map.getKey(), (Boolean) value);
            }
        }
        generator.writeEndObject();
        generator.close();
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        log.error("Error in structured message", e);
        return null;
    }
}