Java Code Examples for org.apache.commons.text.StringEscapeUtils#escapeJson()

The following examples show how to use org.apache.commons.text.StringEscapeUtils#escapeJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JSONFormatter.java    From TNT4J with Apache License 2.0 6 votes vote down vote up
@Override
public String format(Object obj, Object... args) {
	if (obj instanceof TrackingActivity) {
		return format((TrackingActivity) obj);
	} else if (obj instanceof TrackingEvent) {
		return format((TrackingEvent) obj);
	} else if (obj instanceof Snapshot) {
		return format((Snapshot) obj);
	} else if (obj instanceof Property) {
		return format((Property) obj);
	} else {
		StringBuilder jsonString = new StringBuilder(1024);
		jsonString.append(START_JSON);
		jsonString.append(JSON_TIME_USEC_LABEL).append(ATTR_SEP).append(Useconds.CURRENT.get()).append(ATTR_JSON);

		String msgText = StringEscapeUtils.escapeJson(Utils.format(Utils.toString(obj), args)); // escape double
																								// quote chars
		jsonString.append(JSON_MSG_TEXT_LABEL).append(ATTR_SEP);
		Utils.quote(msgText, jsonString);
		jsonString.append(END_JSON);
		return jsonString.toString();
	}
}
 
Example 2
Source File: TestActor.java    From opentest with MIT License 5 votes vote down vote up
/**
 * Parse JSON data using the JS engine and return the corresponding JS
 * native value.
 */
public Object parseJsonToNativeJsType(String jsonData) {
    try {
        String escapedJson = StringEscapeUtils.escapeJson(jsonData);
        String jsCode = String.format("JSON.parse(\"%s\")", escapedJson);
        Object jsNativeType = this.scriptEngine.eval(jsCode);
        return jsNativeType;
    } catch (Exception ex) {
        throw new RuntimeException(String.format(
                "An error was encountered while parsing JSON data. The JSON data was: %s",
                jsonData), ex);
    }
}
 
Example 3
Source File: HandlebarsEscapeHelper.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Map<String, Object> context, Options options) throws IOException {
	Object model = context.get(REQUEST_MODEL_NAME);
	if (model instanceof TestSideRequestTemplateModel) {
		return StringEscapeUtils.escapeJson(returnObjectForTest(model).toString());
	}
	else if (model instanceof RequestTemplateModel) {
		return StringEscapeUtils.escapeJson(returnObjectForStub(model).toString());
	}

	throw new IllegalArgumentException("Unsupported model");
}
 
Example 4
Source File: QueryCassandra.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected static String getJsonElement(Object value) {
    if (value instanceof Number) {
        return value.toString();
    } else if (value instanceof Date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return "\"" + dateFormat.format((Date) value) + "\"";
    } else if (value instanceof String) {
        return "\"" + StringEscapeUtils.escapeJson((String) value) + "\"";
    } else {
        return "\"" + value.toString() + "\"";
    }
}
 
Example 5
Source File: PingResponse.java    From fess with Apache License 2.0 5 votes vote down vote up
public PingResponse(final ClusterHealthResponse response) {
    status = response.getStatus() == ClusterHealthStatus.RED ? 1 : 0;
    clusterName = response.getClusterName();
    clusterStatus = response.getStatus().toString();
    try (OutputStream out = EsUtil.getXContentBuilderOutputStream((builder, params) -> {
        builder.startObject();
        builder.field(CLUSTER_NAME, response.getClusterName());
        builder.field(STATUS, response.getStatus().name().toLowerCase(Locale.ROOT));
        builder.field(TIMED_OUT, response.isTimedOut());
        builder.field(NUMBER_OF_NODES, response.getNumberOfNodes());
        builder.field(NUMBER_OF_DATA_NODES, response.getNumberOfDataNodes());
        builder.field(ACTIVE_PRIMARY_SHARDS, response.getActivePrimaryShards());
        builder.field(ACTIVE_SHARDS, response.getActiveShards());
        builder.field(RELOCATING_SHARDS, response.getRelocatingShards());
        builder.field(INITIALIZING_SHARDS, response.getInitializingShards());
        builder.field(UNASSIGNED_SHARDS, response.getUnassignedShards());
        builder.field(DELAYED_UNASSIGNED_SHARDS, response.getDelayedUnassignedShards());
        builder.field(NUMBER_OF_PENDING_TASKS, response.getNumberOfPendingTasks());
        builder.field(NUMBER_OF_IN_FLIGHT_FETCH, response.getNumberOfInFlightFetch());
        builder.field(TASK_MAX_WAIT_TIME_IN_QUEUE_IN_MILLIS, response.getTaskMaxWaitingTime().getMillis());
        builder.field(ACTIVE_SHARDS_PERCENT_AS_NUMBER, response.getActiveShardsPercent());
        builder.endObject();
        return builder;
    }, XContentType.JSON)) {
        message = ((ByteArrayOutputStream) out).toString(Constants.UTF_8);
        if (StringUtil.isBlank(message)) {
            message = "{}";
        }
    } catch (final IOException e) {
        message = "{ \"error\" : \"" + StringEscapeUtils.escapeJson(e.getMessage()) + "\"}";
    }
}
 
Example 6
Source File: JsonLikeConverterTest.java    From conf4j with MIT License 4 votes vote down vote up
private static String escapeJson(String text, boolean appendDoubleQuotes) {
    return appendDoubleQuotes
            ? '"' + StringEscapeUtils.escapeJson(text) + '"'
            : StringEscapeUtils.escapeJson(text);
}
 
Example 7
Source File: Helper.java    From StatsAgg with Apache License 2.0 4 votes vote down vote up
public static String createSimpleJsonResponse(String message) {
    return "{\"Message\":\"" + StringEscapeUtils.escapeJson(message) + "\"}";
}
 
Example 8
Source File: Helper.java    From StatsAgg with Apache License 2.0 4 votes vote down vote up
public static String createSimpleJsonErrorResponse(String errorMessage) {
    return "{\"Error\":\"" + StringEscapeUtils.escapeJson(errorMessage) + "\"}";
}
 
Example 9
Source File: JsonEscapeTransformer.java    From LoggerPlusPlus with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String transform(String string) {
    return StringEscapeUtils.escapeJson(string);
}
 
Example 10
Source File: ExecuteSparkInteractive.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException {

    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final ComponentLog log = getLogger();
    final LivySessionService livySessionService = context.getProperty(LIVY_CONTROLLER_SERVICE).asControllerService(LivySessionService.class);
    final Map<String, String> livyController;
    try {
        livyController = livySessionService.getSession();
        if (livyController == null || livyController.isEmpty()) {
            log.debug("No Spark session available (yet), routing flowfile to wait");
            session.transfer(flowFile, REL_WAIT);
            context.yield();
            return;
        }
    } catch (SessionManagerException sme) {
        log.error("Error opening spark session, routing flowfile to wait", sme);
        session.transfer(flowFile, REL_WAIT);
        context.yield();
        return;
    }
    final long statusCheckInterval = context.getProperty(STATUS_CHECK_INTERVAL).evaluateAttributeExpressions(flowFile).asTimePeriod(TimeUnit.MILLISECONDS);
    Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());

    String sessionId = livyController.get("sessionId");
    String livyUrl = livyController.get("livyUrl");
    String code = context.getProperty(CODE).evaluateAttributeExpressions(flowFile).getValue();
    if (StringUtils.isEmpty(code)) {
        try (InputStream inputStream = session.read(flowFile)) {
            // If no code was provided, assume it is in the content of the incoming flow file
            code = IOUtils.toString(inputStream, charset);
        } catch (IOException ioe) {
            log.error("Error reading input flowfile, penalizing and routing to failure", new Object[]{flowFile, ioe.getMessage()}, ioe);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            return;
        }
    }

    code = StringEscapeUtils.escapeJson(code);
    String payload = "{\"code\":\"" + code + "\"}";
    try {
        final JSONObject result = submitAndHandleJob(livyUrl, livySessionService, sessionId, payload, statusCheckInterval);
        log.debug("ExecuteSparkInteractive Result of Job Submit: " + result);
        if (result == null) {
            session.transfer(flowFile, REL_FAILURE);
        } else {
            try {
                final JSONObject output = result.getJSONObject("data");
                flowFile = session.write(flowFile, out -> out.write(output.toString().getBytes(charset)));
                flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), LivySessionService.APPLICATION_JSON);
                session.transfer(flowFile, REL_SUCCESS);
            } catch (JSONException je) {
                // The result doesn't contain the data, just send the output object as the flow file content to failure (after penalizing)
                log.error("Spark Session returned an error, sending the output JSON object as the flow file content to failure (after penalizing)");
                flowFile = session.write(flowFile, out -> out.write(result.toString().getBytes(charset)));
                flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), LivySessionService.APPLICATION_JSON);
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
        }
    } catch (IOException | SessionManagerException e) {
        log.error("Failure processing flowfile {} due to {}, penalizing and routing to failure", new Object[]{flowFile, e.getMessage()}, e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }
}
 
Example 11
Source File: JsonUtility.java    From jstarcraft-core with Apache License 2.0 2 votes vote down vote up
/**
 * 对字符串执行JSON加密
 * 
 * @param string
 * @return
 */
public static final String escapeJson(String string) {
    return StringEscapeUtils.escapeJson(string);
}