Example usage for org.apache.commons.lang3 StringEscapeUtils escapeJson

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeJson

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeJson.

Prototype

public static final String escapeJson(final String input) 

Source Link

Document

Escapes the characters in a String using Json String rules.

Escapes any values it finds into their Json String form.

Usage

From source file:com.streamsets.datacollector.execution.alerts.WebHookNotifier.java

@Override
public void onStateChange(PipelineState fromState, PipelineState toState, String toStateJson,
        ThreadUsage threadUsage, Map<String, String> offset) throws PipelineRuntimeException {
    //should not be active in slave mode
    if (toState.getExecutionMode() != ExecutionMode.SLAVE && pipelineId.equals(toState.getPipelineId())) {
        if (pipelineStates != null && pipelineStates.contains(toState.getStatus().name())) {
            for (PipelineWebhookConfig webhookConfig : pipelineConfigBean.webhookConfigs) {
                if (!StringUtils.isEmpty(webhookConfig.webhookUrl)) {
                    Response response = null;
                    try {
                        DateFormat dateTimeFormat = new SimpleDateFormat(EmailConstants.DATE_MASK,
                                Locale.ENGLISH);
                        String payload = webhookConfig.payload
                                .replace(WebhookConstants.PIPELINE_TITLE_KEY,
                                        Strings.nullToEmpty(pipelineTitle))
                                .replace(WebhookConstants.PIPELINE_URL_KEY,
                                        Strings.nullToEmpty(
                                                runtimeInfo.getBaseHttpUrl() + EmailConstants.PIPELINE_URL
                                                        + toState.getPipelineId().replaceAll(" ", "%20")))
                                .replace(WebhookConstants.PIPELINE_STATE_KEY,
                                        Strings.nullToEmpty(toState.getStatus().toString()))
                                .replace(WebhookConstants.TIME_KEY,
                                        dateTimeFormat.format(new Date(toState.getTimeStamp())))
                                .replace(WebhookConstants.PIPELINE_STATE_MESSAGE_KEY,
                                        Strings.nullToEmpty(toState.getMessage()))
                                .replace(WebhookConstants.PIPELINE_RUNTIME_PARAMETERS_KEY,
                                        Strings.nullToEmpty(StringEscapeUtils.escapeJson(ObjectMapperFactory
                                                .get().writeValueAsString(runtimeParameters))))
                                .replace(WebhookConstants.PIPELINE_METRICS_KEY, Strings
                                        .nullToEmpty(StringEscapeUtils.escapeJson(toState.getMetrics())));

                        if (payload.contains(WebhookConstants.PIPELINE_INPUT_RECORDS_COUNT_KEY)
                                || payload.contains(WebhookConstants.PIPELINE_OUTPUT_RECORDS_COUNT_KEY)
                                || payload.contains(WebhookConstants.PIPELINE_ERROR_RECORDS_COUNT_KEY)
                                || payload.contains(WebhookConstants.PIPELINE_ERROR_MESSAGES_COUNT_KEY)) {
                            long inputRecordsCount = 0;
                            long outputRecordsCount = 0;
                            long errorRecordsCount = 0;
                            long errorMessagesCount = 0;

                            if (toState.getMetrics() != null) {
                                MetricRegistryJson metricRegistryJson = ObjectMapperFactory.get()
                                        .readValue(toState.getMetrics(), MetricRegistryJson.class);

                                if (metricRegistryJson != null && metricRegistryJson.getMeters() != null) {
                                    MeterJson batchInputRecords = metricRegistryJson.getMeters().get(
                                            "pipeline.batchInputRecords" + MetricsConfigurator.METER_SUFFIX);
                                    if (batchInputRecords != null) {
                                        inputRecordsCount = batchInputRecords.getCount();
                                    }//from   w  w  w . ja  v a 2  s . c o  m

                                    MeterJson batchOutputRecords = metricRegistryJson.getMeters().get(
                                            "pipeline.batchOutputRecords" + MetricsConfigurator.METER_SUFFIX);
                                    if (batchOutputRecords != null) {
                                        outputRecordsCount = batchOutputRecords.getCount();
                                    }

                                    MeterJson batchErrorRecords = metricRegistryJson.getMeters().get(
                                            "pipeline.batchErrorRecords" + MetricsConfigurator.METER_SUFFIX);
                                    if (batchErrorRecords != null) {
                                        errorRecordsCount = batchErrorRecords.getCount();
                                    }

                                    MeterJson batchErrorMessagesRecords = metricRegistryJson.getMeters().get(
                                            "pipeline.batchErrorMessages" + MetricsConfigurator.METER_SUFFIX);
                                    if (batchErrorMessagesRecords != null) {
                                        errorMessagesCount = batchErrorMessagesRecords.getCount();
                                    }
                                }
                            }

                            payload = payload
                                    .replace(WebhookConstants.PIPELINE_INPUT_RECORDS_COUNT_KEY,
                                            inputRecordsCount + "")
                                    .replace(WebhookConstants.PIPELINE_OUTPUT_RECORDS_COUNT_KEY,
                                            outputRecordsCount + "")
                                    .replace(WebhookConstants.PIPELINE_ERROR_RECORDS_COUNT_KEY,
                                            errorRecordsCount + "")
                                    .replace(WebhookConstants.PIPELINE_ERROR_MESSAGES_COUNT_KEY,
                                            errorMessagesCount + "");
                        }

                        WebTarget webTarget = ClientBuilder.newClient().target(webhookConfig.webhookUrl);
                        configurePasswordAuth(webhookConfig, webTarget);
                        Invocation.Builder builder = webTarget.request();
                        for (String headerKey : webhookConfig.headers.keySet()) {
                            builder.header(headerKey, webhookConfig.headers.get(headerKey));
                        }
                        response = builder.post(Entity.entity(payload, webhookConfig.contentType));

                        if (response.getStatus() != Response.Status.OK.getStatusCode()) {
                            LOG.error("Error calling Webhook URL, status code '{}': {}", response.getStatus(),
                                    response.readEntity(String.class));
                        }
                    } catch (Exception e) {
                        LOG.error("Error calling Webhook URL : {}", e.toString(), e);
                    } finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                }
            }
        }
    }
}

From source file:com.jkoolcloud.tnt4j.format.JSONFormatter.java

/**
 * Format a given {@link TrackingEvent} into JSON format
 *
 * @param event/*  w ww  . j  av a 2 s  .co  m*/
 *            tracking event instance to be formatted
 * @see TrackingEvent
 */
@Override
public String format(TrackingEvent event) {
    StringBuilder jsonString = new StringBuilder(1024);

    jsonString.append(START_JSON);
    if (!Utils.isEmpty(event.getTrackingId())) {
        jsonString.append(JSON_TRACK_ID_LABEL).append(ATTR_SEP).append(Utils.quote(event.getTrackingId()))
                .append(ATTR_JSON);
    }
    if (!Utils.isEmpty(event.getSignature())) {
        jsonString.append(JSON_TRACK_SIGN_LABEL).append(ATTR_SEP).append(Utils.quote(event.getSignature()))
                .append(ATTR_JSON);
    }
    if (!Utils.isEmpty(event.getParentId())) {
        jsonString.append(JSON_PARENT_TRACK_ID_LABEL).append(ATTR_SEP).append(Utils.quote(event.getParentId()))
                .append(ATTR_JSON);
    }
    jsonString.append(JSON_SOURCE_LABEL).append(ATTR_SEP)
            .append(Utils.quote(StringEscapeUtils.escapeJson(event.getSource().getName()))).append(ATTR_JSON);
    String ssn = event.getSource().getSourceFactory().getSSN();
    if (!Utils.isEmpty(ssn)) {
        String escaped = StringEscapeUtils.escapeJson(ssn); // escape double quote chars
        jsonString.append(JSON_SOURCE_SSN_LABEL).append(ATTR_SEP).append(Utils.quote(escaped))
                .append(ATTR_JSON);
    }
    jsonString.append(JSON_SOURCE_FQN_LABEL).append(ATTR_SEP)
            .append(Utils.quote(StringEscapeUtils.escapeJson(event.getSource().getFQName()))).append(ATTR_JSON);
    if (!Utils.isEmpty(event.getSource().getUrl())) {
        String escaped = StringEscapeUtils.escapeJson(event.getSource().getUrl()); // escape double quote chars
        jsonString.append(JSON_SOURCE_URL_LABEL).append(ATTR_SEP).append(Utils.quote(escaped))
                .append(ATTR_JSON);
    }
    if (event.get2(TrackingEvent.OBJ_ONE) != null) {
        // we have a relation
        jsonString.append(JSON_RELATE_TYPE_LABEL).append(ATTR_SEP).append(Utils.quote(event.get2Type()))
                .append(ATTR_JSON);
        jsonString.append(JSON_RELATE_FQN_A_LABEL).append(ATTR_SEP)
                .append(Utils.quote(event.get2(TrackingEvent.OBJ_ONE).getFQName())).append(ATTR_JSON);
        jsonString.append(JSON_RELATE_FQN_B_LABEL).append(ATTR_SEP)
                .append(Utils.quote(event.get2(TrackingEvent.OBJ_TWO).getFQName())).append(ATTR_JSON);
    }
    jsonString.append(JSON_SEVERITY_LABEL).append(ATTR_SEP).append(Utils.quote(event.getSeverity()))
            .append(ATTR_JSON);
    jsonString.append(JSON_SEVERITY_NO_LABEL).append(ATTR_SEP).append(event.getSeverity().ordinal())
            .append(ATTR_JSON);
    jsonString.append(JSON_TYPE_LABEL).append(ATTR_SEP).append(Utils.quote(event.getOperation().getType()))
            .append(ATTR_JSON);
    jsonString.append(JSON_TYPE_NO_LABEL).append(ATTR_SEP).append(event.getOperation().getType().ordinal())
            .append(ATTR_JSON);
    jsonString.append(JSON_PID_LABEL).append(ATTR_SEP).append(event.getOperation().getPID()).append(ATTR_JSON);
    jsonString.append(JSON_TID_LABEL).append(ATTR_SEP).append(event.getOperation().getTID()).append(ATTR_JSON);
    jsonString.append(JSON_COMP_CODE_LABEL).append(ATTR_SEP)
            .append(Utils.quote(event.getOperation().getCompCode())).append(ATTR_JSON);
    jsonString.append(JSON_COMP_CODE_NO_LABEL).append(ATTR_SEP)
            .append(event.getOperation().getCompCode().ordinal()).append(ATTR_JSON);
    jsonString.append(JSON_REASON_CODE_LABEL).append(ATTR_SEP).append(event.getOperation().getReasonCode())
            .append(ATTR_JSON);
    jsonString.append(JSON_TTL_SEC_LABEL).append(ATTR_SEP).append(event.getTTL()).append(ATTR_JSON);

    if (!Utils.isEmpty(event.getLocation())) {
        String escaped = StringEscapeUtils.escapeJson(event.getLocation()); // escape double quote chars
        jsonString.append(JSON_LOCATION_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(event.getOperation().getResolvedName())) {
        String escaped = StringEscapeUtils.escapeJson(event.getOperation().getResolvedName()); // escape double quote chars
        jsonString.append(JSON_OPERATION_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(event.getOperation().getResource())) {
        String escaped = StringEscapeUtils.escapeJson(event.getOperation().getResource()); // escape double quote chars
        jsonString.append(JSON_RESOURCE_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(event.getOperation().getUser())) {
        String escaped = StringEscapeUtils.escapeJson(event.getOperation().getUser()); // escape double quote chars
        jsonString.append(JSON_USER_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    jsonString.append(JSON_TIME_USEC_LABEL).append(ATTR_SEP).append(Useconds.CURRENT.get()).append(ATTR_JSON);
    if (event.getOperation().getStartTime() != null) {
        jsonString.append(JSON_START_TIME_USEC_LABEL).append(ATTR_SEP)
                .append(event.getOperation().getStartTime().getTimeUsec()).append(ATTR_JSON);
    }
    if (event.getOperation().getEndTime() != null) {
        jsonString.append(JSON_END_TIME_USEC_LABEL).append(ATTR_SEP)
                .append(event.getOperation().getEndTime().getTimeUsec()).append(ATTR_JSON);
        jsonString.append(JSON_ELAPSED_TIME_USEC_LABEL).append(ATTR_SEP)
                .append(event.getOperation().getElapsedTimeUsec()).append(ATTR_JSON);
        if (event.getOperation().getWaitTimeUsec() > 0) {
            jsonString.append(JSON_WAIT_TIME_USEC_LABEL).append(ATTR_SEP)
                    .append(event.getOperation().getWaitTimeUsec()).append(ATTR_JSON);
        }
        if (event.getMessageAge() > 0) {
            jsonString.append(JSON_MSG_AGE_USEC_LABEL).append(ATTR_SEP).append(event.getMessageAge())
                    .append(ATTR_JSON);
        }
    }
    int snapCount = event.getOperation().getSnapshotCount();
    int propCount = event.getOperation().getPropertyCount();
    jsonString.append(JSON_SNAPSHOT_COUNT_LABEL).append(ATTR_SEP).append(snapCount).append(ATTR_JSON);
    jsonString.append(JSON_PROPERTY_COUNT_LABEL).append(ATTR_SEP).append(propCount).append(ATTR_JSON);
    jsonString.append(JSON_MSG_SIZE_LABEL).append(ATTR_SEP).append(event.getSize()).append(ATTR_JSON);
    jsonString.append(JSON_MSG_MIME_LABEL).append(ATTR_SEP).append(Utils.quote(event.getMimeType()))
            .append(ATTR_JSON);
    jsonString.append(JSON_MSG_ENC_LABEL).append(ATTR_SEP).append(Utils.quote(event.getEncoding()))
            .append(ATTR_JSON);
    jsonString.append(JSON_MSG_CHARSET_LABEL).append(ATTR_SEP).append(Utils.quote(event.getCharset()));

    String msgText = event.getMessage();
    if (!Utils.isEmpty(msgText)) {
        jsonString.append(ATTR_JSON);
        msgText = StringEscapeUtils.escapeJson(msgText); // escape double quote chars
        jsonString.append(JSON_MSG_TEXT_LABEL).append(ATTR_SEP).append(Utils.quote(msgText));
    }

    String exStr = event.getOperation().getExceptionString();
    if (!Utils.isEmpty(exStr)) {
        jsonString.append(ATTR_JSON);
        String excText = StringEscapeUtils.escapeJson(exStr); // escape double quote chars
        jsonString.append(JSON_EXCEPTION_LABEL).append(ATTR_SEP).append(Utils.quote(excText));
    }
    if (!Utils.isEmpty(event.getCorrelator())) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_CORR_ID_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(event.getCorrelator())).append(ARRAY_END);
    }
    if (!Utils.isEmpty(event.getTag())) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_MSG_TAG_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(event.getTag())).append(ARRAY_END);
    }
    if (propCount > 0) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_PROPERTIES_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(event.getOperation().getProperties())).append(ARRAY_END);
    }
    if (snapCount > 0) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_SNAPSHOTS_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(event.getOperation().getSnapshots())).append(ARRAY_END);
    }
    jsonString.append(END_JSON);
    return jsonString.toString();
}

From source file:alluxio.util.FormatUtils.java

/**
 * Encodes the given string as a JSON object.
 *
 * @param input the string to encode//  w  w  w .  j a  v  a2  s .c  o  m
 * @return the JSON-encoded version of the input string
 */
public static String encodeJson(String input) {
    return "\"" + StringEscapeUtils.escapeJson(input) + "\"";
}

From source file:com.simiacryptus.util.io.MarkdownNotebookOutput.java

@Override
public void close() throws IOException {
    if (null != primaryOut) {
        primaryOut.close();// ww  w  .j a  v a2  s. c o  m
        try (@javax.annotation.Nonnull
        PrintWriter out = new PrintWriter(new FileOutputStream(fileName))) {
            if (!frontMatter.isEmpty()) {
                out.println("---");

                frontMatter.forEach((key, value) -> {
                    String escaped = StringEscapeUtils.escapeJson(value).replaceAll("\n", " ")
                            .replaceAll(":", "&#58;").replaceAll("\\{", "\\{").replaceAll("\\}", "\\}");
                    out.println(String.format("%s: %s", key, escaped));
                });
                out.println("---");
            }
            toc.forEach(out::println);
            out.print("\n\n");
            buffer.forEach(out::println);
        }
    }
}

From source file:com.wxxr.nirvana.json.JSONValidationInterceptor.java

private String buildArray(Collection<String> values) {
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (String value : values) {
        sb.append("\"");
        sb.append(StringEscapeUtils.escapeJson(value));
        sb.append("\",");
    }// w  w w .jav a 2s.  c  o  m
    if (values.size() > 0)
        sb.deleteCharAt(sb.length() - 1);
    sb.append("]");
    return sb.toString();
}

From source file:jongo.filter.DefaultFormatFilter.java

private String formatSuccessJSONResponse(final JongoSuccess response) {
    final StringBuilder b = new StringBuilder("{");
    b.append("\"success\":");
    b.append(response.isSuccess());/*w ww.j  a v a 2  s  .  c  o  m*/
    b.append(",\"cells\":[ "); //this last space is important!
    for (Row r : response.getRows()) {
        List<String> args = new ArrayList<String>();
        for (String key : r.getCells().keySet()) {
            String val = StringEscapeUtils.escapeJson(r.getCells().get(key));
            if (StringUtils.isNumeric(val)) {
                if (StringUtils.isWhitespace(val)) {
                    args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"\"");
                } else {
                    args.add("\"" + key.toLowerCase() + "\"" + ":" + val);
                }
            } else {
                args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"" + val + "\"");
            }
        }

        b.append("{");
        b.append(StringUtils.join(args, ","));
        b.append("}");
        b.append(",");
    }
    b.deleteCharAt(b.length() - 1);
    b.append("]}");
    return b.toString();
}

From source file:in.andres.kandroid.kanboard.KanboardRequest.java

@NonNull
public static KanboardRequest createComment(int taskid, int userid, @NonNull String comment) {
    return new KanboardRequest("createComment",
            new String[] { String.format(
                    "" + "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"createComment\",\n"
                            + "    \"id\": 1580417921,\n" + "    \"params\": {\n" + "        \"task_id\": %d,\n"
                            + "        \"user_id\": %d,\n" + "        \"content\": \"%s\"\n" + "    }\n" + "}",
                    taskid, userid, StringEscapeUtils.escapeJson(comment)) });
}

From source file:com.yahoo.parsec.filters.RequestResponeLoggingFilterTest.java

private String createLogStringPatternForError(String requestMethod, String url, String queryString,
        Map<String, Collection<String>> reqHeaders, String reqBodyJson, Object error)
        throws JsonProcessingException {

    Map<String, String> headers = reqHeaders.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> String.join(",", e.getValue())));

    String reqHeaderString = _OBJECT_MAPPER.writeValueAsString(headers);
    String pattern = String.format(
            "{" + "\"time\":\"${json-unit.any-number}\"," + "\"request\": {" + "\"method\": \"%s\","
                    + "\"uri\": \"%s\"," + "\"query\": \"%s\"," + "\"headers\": %s," + "\"payload\": \"%s\""
                    + "}," + "\"response\": {}," + "\"response-error\": \"${json-unit.ignore}\", "
                    + "\"progress\": {" + "\"namelookup_time\": \"${json-unit.any-number}\","
                    + "\"connect_time\": \"${json-unit.any-number}\","
                    + "\"pretransfer_time\": \"${json-unit.any-number}\","
                    + "\"starttransfer_time\": \"${json-unit.any-number}\","
                    + "\"total_time\":\"${json-unit.any-number}\"" + "}" + "}",
            requestMethod, url, queryString, reqHeaderString, StringEscapeUtils.escapeJson(reqBodyJson));

    return pattern;

}

From source file:in.andres.kandroid.kanboard.KanboardRequest.java

@NonNull
public static KanboardRequest updateComment(int commentid, @NonNull String comment) {
    return new KanboardRequest("updateComment",
            new String[] { String.format(
                    "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"updateComment\",\n"
                            + "    \"id\": 496470023,\n" + "    \"params\": {\n" + "        \"id\": %d,\n"
                            + "        \"content\": \"%s\"\n" + "    }\n" + "}",
                    commentid, StringEscapeUtils.escapeJson(comment)) });
}

From source file:com.yahoo.parsec.filters.RequestResponeLoggingFilterTest.java

private String createLogStringPattern(String requestMethod, String url, String queryString,
        Map<String, Collection<String>> reqHeaders, String reqBodyJson, int responseCode,
        Map<String, Collection<String>> respHeaders, String respBodyJson) throws JsonProcessingException {

    Map<String, String> headers = reqHeaders.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> String.join(",", e.getValue())));

    String reqHeaderString = _OBJECT_MAPPER.writeValueAsString(headers);

    headers = respHeaders.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> String.join(",", e.getValue())));

    String respHeaderString = _OBJECT_MAPPER.writeValueAsString(headers);

    String pattern = String.format(
            "{" + "\"time\":\"${json-unit.any-number}\"," + "\"request\": {" + "\"method\": \"%s\","
                    + "\"uri\": \"%s\"," + "\"query\": \"%s\"," + "\"headers\": %s," + "\"payload\": \"%s\""
                    + "}," + "\"response\": {" + "\"status\": %d," + "\"headers\": %s," + "\"payload\": \"%s\""
                    + "}," + "\"progress\": {" + "\"namelookup_time\": \"${json-unit.any-number}\","
                    + "\"connect_time\": \"${json-unit.any-number}\","
                    + "\"pretransfer_time\": \"${json-unit.any-number}\","
                    + "\"starttransfer_time\": \"${json-unit.any-number}\","
                    + "\"total_time\":\"${json-unit.any-number}\"" + "}" + "}",
            requestMethod, url, queryString, reqHeaderString, StringEscapeUtils.escapeJson(reqBodyJson),
            responseCode, respHeaderString, StringEscapeUtils.escapeJson(respBodyJson));

    return pattern;
}