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:org.ow2.proactive_grid_cloud_portal.rm.RMRest.java

@Deprecated
@Override//from  w ww.j  a va  2 s .  c  o m
@POST
@Path("nodesource/create/recovery")
@Produces("application/json")
public NSState createNodeSource(@HeaderParam("sessionid") String sessionId,
        @FormParam("nodeSourceName") String nodeSourceName,
        @FormParam("infrastructureType") String infrastructureType,
        @FormParam("infrastructureParameters") String[] infrastructureParameters,
        @FormParam("infrastructureFileParameters") String[] infrastructureFileParameters,
        @FormParam("policyType") String policyType, @FormParam("policyParameters") String[] policyParameters,
        @FormParam("policyFileParameters") String[] policyFileParameters,
        @FormParam("nodesRecoverable") String nodesRecoverable) throws NotConnectedException {
    ResourceManager rm = checkAccess(sessionId);
    NSState nsState = new NSState();

    Object[] allInfrastructureParameters = this.getAllInfrastructureParameters(infrastructureType,
            infrastructureParameters, infrastructureFileParameters, rm);

    Object[] allPolicyParameters = this.getAllPolicyParameters(policyType, policyParameters,
            policyFileParameters, rm);

    try {
        nsState.setResult(rm.createNodeSource(nodeSourceName, infrastructureType, allInfrastructureParameters,
                policyType, allPolicyParameters, Boolean.parseBoolean(nodesRecoverable)).getBooleanValue());
    } catch (RuntimeException ex) {
        nsState.setResult(false);
        nsState.setErrorMessage(cleanDisplayedErrorMessage(ex.getMessage()));
        nsState.setStackTrace(StringEscapeUtils.escapeJson(getStackTrace(ex)));

    } finally {
        return nsState;
    }

}

From source file:org.ow2.proactive_grid_cloud_portal.rm.RMRest.java

@Override
@PUT/*www .  java 2s .com*/
@Path("nodesource/deploy")
@Produces("application/json")
public NSState deployNodeSource(@HeaderParam("sessionid") String sessionId,
        @FormParam("nodeSourceName") String nodeSourceName) throws NotConnectedException {
    ResourceManager rm = checkAccess(sessionId);
    NSState nsState = new NSState();
    try {
        nsState.setResult(rm.deployNodeSource(nodeSourceName).getBooleanValue());
    } catch (RuntimeException ex) {
        nsState.setResult(false);
        nsState.setErrorMessage(cleanDisplayedErrorMessage(ex.getMessage()));
        nsState.setStackTrace(StringEscapeUtils.escapeJson(getStackTrace(ex)));
    }
    return nsState;
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.RMRest.java

@Override
@PUT/* w  w w . ja v a 2s  .com*/
@Path("nodesource/undeploy")
@Produces("application/json")
public NSState undeployNodeSource(@HeaderParam("sessionid") String sessionId,
        @FormParam("nodeSourceName") String nodeSourceName, @FormParam("preempt") boolean preempt)
        throws NotConnectedException {
    ResourceManager rm = checkAccess(sessionId);
    NSState nsState = new NSState();
    try {
        nsState.setResult(rm.undeployNodeSource(nodeSourceName, preempt).getBooleanValue());
    } catch (RuntimeException ex) {
        nsState.setResult(false);
        nsState.setErrorMessage(cleanDisplayedErrorMessage(ex.getMessage()));
        nsState.setStackTrace(StringEscapeUtils.escapeJson(getStackTrace(ex)));
    }
    return nsState;
}

From source file:org.owasp.webgoat.assignments.AttackResult.java

public AttackResult(boolean lessonCompleted, String feedback, String output) {
    this.lessonCompleted = lessonCompleted;
    this.feedback = StringEscapeUtils.escapeJson(feedback);
    this.output = StringEscapeUtils.escapeJson(output);
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

private String createCriterionJsonPayload(HashMap<String, String> formPostParameters,
        Resource<ToolItemRubricAssociation> association) throws Exception {

    Map<String, Map<String, String>> criterionDataMap = extractCriterionDataFromParams(formPostParameters);

    String criterionJsonData = "";
    int index = 0;
    boolean pointsAdjusted = false;
    String points = null;// ww w  .jav  a2 s .  c om
    String selectedRatingId = null;

    String inlineRubricUri = String.format("%s?%s", association.getLink("rubric").getHref(),
            "projection=inlineRubric");

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization",
            String.format("Bearer %s", generateJsonWebToken(association.getContent().getToolId())));
    HttpEntity<?> requestEntity = new HttpEntity<>(headers);
    ResponseEntity<Rubric> rubricEntity = restTemplate.exchange(inlineRubricUri, HttpMethod.GET, requestEntity,
            Rubric.class);

    Map<String, Criterion> criterions = new HashMap<>();
    for (Criterion criterion : rubricEntity.getBody().getCriterions()) {
        criterions.put(String.valueOf(criterion.getId()), criterion);
    }

    for (Map.Entry<String, Map<String, String>> criterionData : criterionDataMap.entrySet()) {
        if (index > 0) {
            criterionJsonData += ", ";
        }
        index++;

        final String selectedRatingPoints = criterionData.getValue().get("rbcs-criterion");

        if (StringUtils.isNotBlank(criterionData.getValue().get("rbcs-criterion-override"))) {
            pointsAdjusted = true;
            points = criterionData.getValue().get("rbcs-criterion-override");
        } else {
            pointsAdjusted = false;
            points = selectedRatingPoints;
        }

        Criterion criterion = criterions.get(criterionData.getKey());
        Optional<Rating> rating = criterion.getRatings().stream()
                .filter(c -> String.valueOf(c.getPoints()).equals(selectedRatingPoints)).findFirst();

        if (rating.isPresent()) {
            selectedRatingId = String.valueOf(rating.get().getId());
        }

        if (StringUtils.isEmpty(points)) {
            points = "0";
        }

        criterionJsonData += String.format(
                "{ \"criterionId\" : \"%s\", \"points\" : \"%s\", "
                        + "\"comments\" : \"%s\", \"pointsAdjusted\" : %b, \"selectedRatingId\" : \"%s\"  }",
                criterionData.getKey(), points,
                StringEscapeUtils.escapeJson(criterionData.getValue().get("rbcs-criterion-comment")),
                pointsAdjusted, selectedRatingId);
    }

    return criterionJsonData;
}

From source file:org.structr.core.function.EscapeJsonFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    try {//from   ww w  .  j  a  v a2 s .c o m
        if (!arrayHasMinLengthAndAllElementsNotNull(sources, 1)) {

            return null;
        }

        return StringEscapeUtils.escapeJson(sources[0].toString());

    } catch (final IllegalArgumentException e) {

        logParameterError(entity, sources, ctx.isJavaScriptContext());

        return usage(ctx.isJavaScriptContext());

    }

}

From source file:org.structr.core.parser.function.EscapeJsonFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    return (arrayHasMinLengthAndAllElementsNotNull(sources, 1))
            ? StringEscapeUtils.escapeJson(sources[0].toString())
            : "";
}

From source file:org.teiid.olingo.web.ODataFilter.java

static void writeError(ServletRequest request, TeiidProcessingException e, HttpServletResponse httpResponse,
        int statusCode) throws IOException {
    httpResponse.setStatus(statusCode);/*from   ww  w .j  av  a2  s . c o m*/
    ContentType contentType = ContentType.parse(request.getContentType());
    PrintWriter writer = httpResponse.getWriter();
    String code = e.getCode() == null ? "" : e.getCode(); //$NON-NLS-1$
    String message = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$
    if (contentType == null || contentType.isCompatible(ContentType.APPLICATION_JSON)) {
        httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON.toContentTypeString());
        writer.write("{ \"error\": { \"code\": \"" + StringEscapeUtils.escapeJson(code) + "\", \"message\": \"" //$NON-NLS-1$//$NON-NLS-2$
                + StringEscapeUtils.escapeJson(message) + "\" } }"); //$NON-NLS-1$
    } else {
        httpResponse.setHeader(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_XML.toContentTypeString());
        writer.write("<m:error xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\"><m:code>" //$NON-NLS-1$
                + StringEscapeUtils.escapeXml10(code) + "</m:code><m:message>" //$NON-NLS-1$
                + StringEscapeUtils.escapeXml10(message) + "</m:message></m:error>"); //$NON-NLS-1$
    }
    writer.close();
}

From source file:org.xwiki.velocity.tools.EscapeTool.java

/**
 * Escapes the characters in a <code>String</code> using JSON String rules: escapes with backslash double quotes,
 * back and forward slashes, newlines, the control characters {@code \b}, {@code \t} and {@code \f}, and with
 * {@code \}{@code uXXXX} any non-ASCII characters. Unlike {@link #javascript(Object)}, it does not escape {@code '}
 * , which is not a special character in JSON, and it would be a syntax error to do so.
 *
 * @param string the string to escape, may be {@code null}; any non-string object will be converted to a string
 *            first, using {@code String.valueOf(obj)}
 * @return String with escaped values, {@code null} if {@code null} input
 * @since 6.1M1//from   ww  w  .jav a  2  s .  c  o  m
 */
public String json(Object string) {
    if (string == null) {
        return null;
    }
    return StringEscapeUtils.escapeJson(String.valueOf(string));
}

From source file:serposcope.controllers.google.GoogleGroupController.java

public Result jsonSearches(Context context) {
    List<GoogleSearch> searches = context.getAttribute("searches", List.class);
    if (searches.isEmpty()) {
        return Results.json().renderRaw("[]");
    }/*  ww w .j  a va2 s  . co m*/

    return Results.ok().json().render((Context context0, Result result) -> {
        PrintWriter writer = null;
        OutputStream os = null;
        try {

            String acceptEncoding = context0.getHeader("Accept-Encoding");
            if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                result.addHeader("Content-Encoding", "gzip");
            }

            ResponseStreams response = context0.finalizeHeaders(result);
            os = response.getOutputStream();
            if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                os = new GZIPOutputStream(os);
            }

            writer = new PrintWriter(os);
            writer.append("[");
            for (int i = 0; i < searches.size(); i++) {
                GoogleSearch search = searches.get(i);
                writer.append("{");
                writer.append("\"id\":").append(Integer.toString(search.getId())).append(",");
                writer.append("\"keyword\":\"").append(StringEscapeUtils.escapeJson(search.getKeyword()))
                        .append("\",");
                writer.append("\"tld\":\"")
                        .append(search.getTld() == null ? "" : StringEscapeUtils.escapeJson(search.getTld()))
                        .append("\",");
                writer.append("\"device\":\"").append(SMARTPHONE.equals(search.getDevice()) ? 'M' : 'D')
                        .append("\",");
                writer.append("\"local\":\"").append(
                        search.getLocal() == null ? "" : StringEscapeUtils.escapeJson(search.getLocal()))
                        .append("\",");
                writer.append("\"datacenter\":\"").append(search.getDatacenter() == null ? ""
                        : StringEscapeUtils.escapeJson(search.getDatacenter())).append("\",");
                writer.append("\"custom\":\"").append(search.getCustomParameters() == null ? ""
                        : StringEscapeUtils.escapeJson(search.getCustomParameters())).append("\"");
                writer.append("}");
                if (i != searches.size() - 1) {
                    writer.append(",");
                }
            }
            writer.append("]");

        } catch (Exception ex) {
            LOG.warn("HTTP error", ex);
        } finally {
            if (os != null) {
                try {
                    writer.close();
                    os.close();
                } catch (Exception ex) {
                }
            }
        }
    });

}