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:in.andres.kandroid.kanboard.KanboardRequest.java

@NonNull
public static KanboardRequest createTask(@NonNull String title, int projectid, @Nullable String colorid,
        @Nullable Integer columnid, @Nullable Integer ownerid, @Nullable Integer creatorid,
        @Nullable Date duedate, @Nullable String description, @Nullable Integer categoryid,
        @Nullable Integer score, @Nullable Integer swimlaneid, @Nullable Integer priority,
        @Nullable Integer recurrencestatus, @Nullable Integer recurrencetrigger,
        @Nullable Integer recurrencefactor, @Nullable Integer recurrencetimeframe,
        @Nullable Integer recurrencebasedate, @Nullable String[] tags, @Nullable Date starteddate) {
    String content = String.format("" + "   \"title\": \"%s\",\n" + "   \"project_id\": %d",
            StringEscapeUtils.escapeJson(title), projectid);
    if (colorid != null)
        content += String.format(", \n \"color_id\": \"%s\"", colorid);
    if (columnid != null)
        content += String.format(", \n \"column_id\": %d", columnid);
    if (ownerid != null)
        content += String.format(", \n \"owner_id\": %d", ownerid);
    if (creatorid != null)
        content += String.format(", \n \"creator_id\": %d", creatorid);
    if (duedate != null)
        content += String.format(", \n \"date_due\": \"%tF\"", duedate);
    if (description != null)
        content += String.format(", \n \"description\": \"%s\"", StringEscapeUtils.escapeJson(description));
    if (categoryid != null)
        content += String.format(", \n \"category_id\": %d", categoryid);
    if (score != null)
        content += String.format(", \n \"score\": %d", score);
    if (swimlaneid != null)
        content += String.format(", \n \"swimlane_id\": %d", swimlaneid);
    if (priority != null)
        content += String.format(", \n \"priority\": %d", priority);
    if (recurrencestatus != null)
        content += String.format(", \n \"recurrence_status\": %d", recurrencestatus);
    if (recurrencetrigger != null)
        content += String.format(", \n \"recurrence_trigger\": %d", recurrencetrigger);
    if (recurrencefactor != null)
        content += String.format(", \n \"recurrence_factor\": %d", recurrencefactor);
    if (recurrencetimeframe != null)
        content += String.format(", \n \"recurrence_timeframe\": %d", recurrencetimeframe);
    if (recurrencebasedate != null)
        content += String.format(", \n \"recurrence_basedate\": %d", recurrencebasedate);
    if (starteddate != null)
        content += String.format(", \n \"date_started\": \"%1$tF %1$tH:%1$tM\"", starteddate);
    //TODO: Add tags
    return new KanboardRequest("createTask",
            new String[] { String.format(
                    "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"createTask\",\n"
                            + "    \"id\": 1406803059,\n" + "    \"params\": {\n" + "%s\n" + "    }\n" + "}",
                    content) });//from  w  ww.j ava2  s. c  o  m
}

From source file:dk.nodes.webservice.parser.NJSONObject.java

/**
 * Maps {@code name} to {@code value}, clobbering any existing name/value
 * mapping with the same name. If the value is {@code null}, any existing
 * mapping for {@code name} is removed.//  ww w .  j a  va  2  s .  c o  m
 *
 * @param value a {@link NJSONObject}, {@link NJSONArray}, String, Boolean,
 *     Integer, Long, Double, {@link #NULL}, or {@code null}. May not be
 *     {@link Double#isNaN() NaNs} or {@link Double#isInfinite()
 *     infinities}.
 * @return this object.
 */
public NJSONObject put(String name, Object value) throws JSONException {
    if (value == null) {
        nameValuePairs.remove(name);
        return this;
    }
    if (value instanceof String) {
        String escapedString = StringEscapeUtils.escapeJson((String) value);
        nameValuePairs.put(checkName(name), escapedString);
        return this;
    }
    if (value instanceof Number) {
        // deviate from the original by checking all Numbers, not just floats & doubles
        NJSON.checkDouble(((Number) value).doubleValue());
    }
    nameValuePairs.put(checkName(name), value);
    return this;
}

From source file:jongo.filter.DefaultFormatFilter.java

private String formatErrorJSONResponse(final JongoError response) {
    StringBuilder b = new StringBuilder("{").append("\"success\":").append(response.isSuccess())
            .append(",\"message\":\"").append(StringEscapeUtils.escapeJson(response.getMessage()));
    if (response.getSqlCode() != null && response.getSqlState() != null) {
        b.append("\",\"SQLState\":\"").append(response.getSqlState());
        b.append("\",\"SQLCode\":\"").append(response.getSqlCode());
    }/*from  w  w  w  .ja  v a 2s .  com*/
    b.append("\"}");
    return b.toString();
}

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

@NonNull
public static KanboardRequest updateTask(int taskid, @NonNull String title, @Nullable String colorid,
        @Nullable Integer ownerid, @Nullable Date duedate, @Nullable String description,
        @Nullable Integer categoryid, @Nullable Integer score, @Nullable Integer priority,
        @Nullable Integer recurrencestatus, @Nullable Integer recurrencetrigger,
        @Nullable Integer recurrencefactor, @Nullable Integer recurrencetimeframe,
        @Nullable Integer recurrencebasedate, @Nullable String[] tags, @Nullable Date starteddate) {
    String content = String.format("" + "   \"title\": \"%s\",\n" + "   \"id\": %d",
            StringEscapeUtils.escapeJson(title), taskid);
    if (colorid != null)
        content += String.format(", \n \"color_id\": \"%s\"", colorid);
    if (ownerid != null)
        content += String.format(", \n \"owner_id\": %d", ownerid);
    if (duedate != null)
        content += String.format(", \n \"date_due\": \"%tF\"", duedate);
    if (description != null)
        content += String.format(", \n \"description\": \"%s\"", StringEscapeUtils.escapeJson(description));
    if (categoryid != null)
        content += String.format(", \n \"category_id\": %d", categoryid);
    if (score != null)
        content += String.format(", \n \"score\": %d", score);
    if (priority != null)
        content += String.format(", \n \"priority\": %d", priority);
    if (recurrencestatus != null)
        content += String.format(", \n \"recurrence_status\": %d", recurrencestatus);
    if (recurrencetrigger != null)
        content += String.format(", \n \"recurrence_trigger\": %d", recurrencetrigger);
    if (recurrencefactor != null)
        content += String.format(", \n \"recurrence_factor\": %d", recurrencefactor);
    if (recurrencetimeframe != null)
        content += String.format(", \n \"recurrence_timeframe\": %d", recurrencetimeframe);
    if (recurrencebasedate != null)
        content += String.format(", \n \"recurrence_basedate\": %d", recurrencebasedate);
    if (starteddate != null)
        content += String.format(", \n \"date_started\": \"%1$tF %1$tH:%1$tM\"", starteddate);
    //TODO: Add tags
    return new KanboardRequest("updateTask",
            new String[] { String.format(
                    "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"updateTask\",\n"
                            + "    \"id\": 1406803059,\n" + "    \"params\": {\n" + "%s\n" + "    }\n" + "}",
                    content) });/*from  w w  w.  j ava 2  s .c om*/
}

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

/**
 * Format a given {@link TrackingActivity} into JSON format
 *
 * @param activity//from w  ww  . jav a 2s  . co  m
 *            tracking activity instance to be formatted
 * @see TrackingActivity
 */
@Override
public String format(TrackingActivity activity) {
    StringBuilder jsonString = new StringBuilder(1024);
    String START_JSON = newLineFormat ? START_LINE : START;
    String END_JSON = newLineFormat ? END_LINE : END;
    String ATTR_JSON = newLineFormat ? ATTR_END_LINE : ATTR_END;

    jsonString.append(START_JSON);
    if (!Utils.isEmpty(activity.getTrackingId())) {
        jsonString.append(JSON_TRACK_ID_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getTrackingId()))
                .append(ATTR_JSON);
    }
    if (!Utils.isEmpty(activity.getSignature())) {
        jsonString.append(JSON_TRACK_SIGN_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getSignature()))
                .append(ATTR_JSON);
    }
    if (!Utils.isEmpty(activity.getParentId())) {
        jsonString.append(JSON_PARENT_TRACK_ID_LABEL).append(ATTR_SEP)
                .append(Utils.quote(activity.getParentId())).append(ATTR_JSON);
    }
    jsonString.append(JSON_SOURCE_LABEL).append(ATTR_SEP)
            .append(Utils.quote(StringEscapeUtils.escapeJson(activity.getSource().getName())))
            .append(ATTR_JSON);
    String ssn = activity.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(activity.getSource().getFQName())))
            .append(ATTR_JSON);

    if (!Utils.isEmpty(activity.getSource().getUrl())) {
        String escaped = StringEscapeUtils.escapeJson(activity.getSource().getUrl()); // escape double quote chars
        jsonString.append(JSON_SOURCE_URL_LABEL).append(ATTR_SEP).append(Utils.quote(escaped))
                .append(ATTR_JSON);
    }
    jsonString.append(JSON_STATUS_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getStatus()))
            .append(ATTR_JSON);
    jsonString.append(JSON_SEVERITY_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getSeverity()))
            .append(ATTR_JSON);
    jsonString.append(JSON_SEVERITY_NO_LABEL).append(ATTR_SEP).append(activity.getSeverity().ordinal())
            .append(ATTR_JSON);
    jsonString.append(JSON_TYPE_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getType()))
            .append(ATTR_JSON);
    jsonString.append(JSON_TYPE_NO_LABEL).append(ATTR_SEP).append(activity.getType().ordinal())
            .append(ATTR_JSON);
    jsonString.append(JSON_PID_LABEL).append(ATTR_SEP).append(activity.getPID()).append(ATTR_JSON);
    jsonString.append(JSON_TID_LABEL).append(ATTR_SEP).append(activity.getTID()).append(ATTR_JSON);
    jsonString.append(JSON_COMP_CODE_LABEL).append(ATTR_SEP).append(Utils.quote(activity.getCompCode()))
            .append(ATTR_JSON);
    jsonString.append(JSON_COMP_CODE_NO_LABEL).append(ATTR_SEP).append(activity.getCompCode().ordinal())
            .append(ATTR_JSON);
    jsonString.append(JSON_REASON_CODE_LABEL).append(ATTR_SEP).append(activity.getReasonCode())
            .append(ATTR_JSON);
    jsonString.append(JSON_TTL_SEC_LABEL).append(ATTR_SEP).append(activity.getTTL()).append(ATTR_JSON);
    if (!Utils.isEmpty(activity.getLocation())) {
        String escaped = StringEscapeUtils.escapeJson(activity.getLocation()); // escape double quote chars
        jsonString.append(JSON_LOCATION_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(activity.getResolvedName())) {
        String escaped = StringEscapeUtils.escapeJson(activity.getResolvedName()); // escape double quote chars
        jsonString.append(JSON_OPERATION_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(activity.getResource())) {
        String escaped = StringEscapeUtils.escapeJson(activity.getResource()); // escape double quote chars
        jsonString.append(JSON_RESOURCE_LABEL).append(ATTR_SEP).append(Utils.quote(escaped)).append(ATTR_JSON);
    }
    if (!Utils.isEmpty(activity.getSource().getUser())) {
        String escaped = StringEscapeUtils.escapeJson(activity.getSource().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 (activity.getStartTime() != null) {
        jsonString.append(JSON_START_TIME_USEC_LABEL).append(ATTR_SEP)
                .append(activity.getStartTime().getTimeUsec()).append(ATTR_JSON);
    }
    if (activity.getEndTime() != null) {
        jsonString.append(JSON_END_TIME_USEC_LABEL).append(ATTR_SEP).append(activity.getEndTime().getTimeUsec())
                .append(ATTR_JSON);
        jsonString.append(JSON_ELAPSED_TIME_USEC_LABEL).append(ATTR_SEP).append(activity.getElapsedTimeUsec())
                .append(ATTR_JSON);
        if (activity.getWaitTimeUsec() > 0) {
            jsonString.append(JSON_WAIT_TIME_USEC_LABEL).append(ATTR_SEP).append(activity.getWaitTimeUsec())
                    .append(ATTR_JSON);
        }
    }
    jsonString.append(JSON_ID_COUNT_LABEL).append(ATTR_SEP).append(activity.getIdCount()).append(ATTR_JSON);
    jsonString.append(JSON_SNAPSHOT_COUNT_LABEL).append(ATTR_SEP).append(activity.getSnapshotCount())
            .append(ATTR_JSON);
    jsonString.append(JSON_PROPERTY_COUNT_LABEL).append(ATTR_SEP).append(activity.getPropertyCount());

    String exStr = activity.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(activity.getCorrelator())) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_CORR_ID_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(activity.getCorrelator())).append(ARRAY_END);
    }
    if (activity.getIdCount() > 0) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_ID_SET_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(activity.getIds())).append(ARRAY_END);
    }
    if (activity.getPropertyCount() > 0) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_PROPERTIES_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(activity.getProperties())).append(ARRAY_END);
    }
    if (activity.getSnapshotCount() > 0) {
        jsonString.append(ATTR_JSON);
        jsonString.append(JSON_SNAPSHOTS_LABEL).append(ATTR_SEP).append(ARRAY_START_JSON)
                .append(itemsToJSON(activity.getSnapshots())).append(ARRAY_END);
    }
    jsonString.append(END_JSON);
    return jsonString.toString();
}

From source file:com.hygenics.parser.getDAOTemplate.java

public ResultSetExtractor<ArrayList<String>> getJsonwithQuotesExtractor() {
    return (new ResultSetExtractor<ArrayList<String>>() {

        @Override//from   w  ww  . j av a  2 s  .co  m
        public ArrayList<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
            // TODO Auto-generated method stub
            int j = 0;
            ArrayList<String> results = new ArrayList<String>();
            JsonObject obj = null;
            int columns = 0;

            while (rs.next()) {
                if (columns == 0) {
                    columns = rs.getMetaData().getColumnCount();
                    if (columns == 0) {
                        return results;
                    }
                }

                obj = null;
                obj = new JsonObject();
                for (int i = 1; i <= columns; i++) {
                    obj.add(rs.getMetaData().getColumnName(i),
                            StringEscapeUtils.escapeJson(rs.getString(i).replaceAll("\t|\r|\n|\r\n|", "")));
                }
                if (obj != null) {
                    results.add(obj.toString());
                }

                j++;
            }

            if (rs.getFetchSize() <= j) {
                rs.close();
            }

            return results;
        }

    });
}

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

@Nullable
public static KanboardRequest createSubtask(int taskid, @NonNull String title, @Nullable Integer userid,
        @Nullable Integer timeestimated, @Nullable Integer timespent, @Nullable Integer status) {
    String content = String.format("" + "        \"task_id\": %d,\n" + "        \"title\": \"%s\"", taskid,
            StringEscapeUtils.escapeJson(title));
    if (userid != null)
        content += String.format("" + ",\n" + "        \"user_id\": %d", userid);
    if (timeestimated != null)
        content += String.format("" + ",\n" + "        \"time_estimated\": %d", timeestimated);
    if (timespent != null)
        content += String.format("" + ",\n" + "        \"time_spent\": %d", timespent);
    if (status != null)
        content += String.format("" + ",\n" + "        \"status\": %d", status);
    return new KanboardRequest("createSubtask",
            new String[] { String.format(
                    "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"createSubtask\",\n"
                            + "    \"id\": 2041554661,\n" + "    \"params\": {\n" + "%s\n" + "    }\n" + "}",
                    content) });/*from w w  w.j a v a  2  s.  c  om*/
}

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

@NonNull
public static KanboardRequest updateSubtask(int subtaskid, int taskid, @Nullable String title,
        @Nullable Integer userid, @Nullable Integer timeestimated, @Nullable Integer timespent,
        @Nullable Integer status) {
    String content = String.format("" + "        \"id\": %d,\n" + "        \"task_id\": %d", subtaskid, taskid);
    if (title != null)
        content += String.format("" + ",\n" + "        \"title\": \"%s\"", StringEscapeUtils.escapeJson(title));
    if (userid != null)
        content += String.format("" + ",\n" + "        \"user_id\": %d", userid);
    if (timeestimated != null)
        content += String.format("" + ",\n" + "        \"time_estimated\": %d", timeestimated);
    if (timespent != null)
        content += String.format("" + ",\n" + "        \"time_spent\": %d", timespent);
    if (status != null)
        content += String.format("" + ",\n" + "        \"status\": %d", status);
    return new KanboardRequest("updateSubtask",
            new String[] { String.format(
                    "{\n" + "    \"jsonrpc\": \"2.0\",\n" + "    \"method\": \"updateSubtask\",\n"
                            + "    \"id\": 191749979,\n" + "    \"params\": {\n" + "%s\n" + "    }\n" + "}",
                    content) });/*from   w  w  w .j a  v  a2  s .  c  o  m*/
}

From source file:com.yahoo.ycsb.db.PostgreSQLJsonbClient.java

@Override
public Status update(String tableName, String key, HashMap<String, ByteIterator> values) {
    try {/*  w w  w .  j  a  v  a 2s .c o m*/
        int numFields = values.size();
        OrderedFieldInfo fieldInfo = getFieldInfo(values);
        StatementType type = new StatementType(StatementType.Type.UPDATE, tableName, 1, "fields",
                getShardIndexByKey(key));
        PreparedStatement updateStatement = cachedStatements.get(type);
        if (updateStatement == null) {
            updateStatement = createAndCacheUpdateStatement(type, key);
        }
        for (Map.Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) {
            updateStatement.setString(1, "{0, " + entry.getKey() + "}");
            updateStatement.setString(2, "\"" + StringEscapeUtils.escapeJson(entry.getValue()) + "\"");
        }
        updateStatement.setString(3, key);
        int result = updateStatement.executeUpdate();
        if (result == 1) {
            return Status.OK;
        }
        return Status.UNEXPECTED_STATE;
    } catch (SQLException e) {
        System.err.println("Error in processing update to table: " + tableName + e);
        return Status.ERROR;
    }
}

From source file:com.blazemeter.bamboo.plugin.api.ApiV3Impl.java

@Override
public boolean notes(String note, String masterId) throws Exception {
    if (StringUtils.isBlank(userKey) & StringUtils.isBlank(masterId))
        return false;
    String noteEsc = StringEscapeUtils.escapeJson("{'" + JsonConstants.NOTE + "':'" + note + "'}");
    JSONObject noteJson = new JSONObject(noteEsc);
    String url = this.urlManager.masterId(APP_KEY, userKey, masterId);
    JSONObject jo = this.http.response(url, noteJson, Method.PATCH, JSONObject.class, JSONObject.class);
    try {//w w w  . j a  v  a2 s  .c  o m
        if (!jo.get(JsonConstants.ERROR).equals(JSONObject.NULL)) {
            return false;
        }
    } catch (Exception e) {
        throw new Exception("Failed to submit report notest to masterId=" + masterId, e);
    }
    return true;
}