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.exoplatform.chat.services.mongodb.ChatServiceImpl.java

public String read(String room, UserService userService, boolean isTextOnly, Long fromTimestamp,
        Long toTimestamp) {/*from   w w w.  ja  va2  s . co m*/
    StringBuilder sb = new StringBuilder();

    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm aaa");
    SimpleDateFormat formatterDate = new SimpleDateFormat("dd/MM/yyyy hh:mm aaa");
    // formatter.format();
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Date today = calendar.getTime();

    DBCollection coll = db().getCollection(M_ROOM_PREFIX + room);

    BasicDBObject query = new BasicDBObject();
    long from = (fromTimestamp != null) ? fromTimestamp : System.currentTimeMillis() - readMillis;
    BasicDBObject tsobj = new BasicDBObject("$gt", from);
    if (toTimestamp != null) {
        tsobj.append("$lt", toTimestamp);
    }
    query.put("timestamp", tsobj);

    BasicDBObject sort = new BasicDBObject();
    sort.put("timestamp", -1);
    int limit = (isTextOnly) ? readTotalTxt : readTotalJson;
    DBCursor cursor = coll.find(query).sort(sort).limit(limit);
    if (!cursor.hasNext()) {
        if (isTextOnly)
            sb.append("no messages");
        else
            sb.append("{\"messages\": []}");
    } else {
        Map<String, UserBean> users = new HashMap<String, UserBean>();

        String timestamp, user, fullname, email, msgId, date;
        boolean first = true;

        while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            timestamp = dbo.get("timestamp").toString();
            if (first) //first element (most recent one)
            {
                if (!isTextOnly) {
                    sb.append("{\"room\": \"").append(room).append("\",");
                    sb.append("\"timestamp\": \"").append(timestamp).append("\",");
                    sb.append("\"messages\": [");
                }
            }

            user = dbo.get("user").toString();
            msgId = dbo.get("_id").toString();
            UserBean userBean = users.get(user);
            if (userBean == null) {
                userBean = userService.getUser(user);
                users.put(user, userBean);
            }
            fullname = userBean.getFullname();
            email = userBean.getEmail();

            date = "";
            try {
                if (dbo.containsField("time")) {
                    Date date1 = (Date) dbo.get("time");
                    if (date1.before(today) || isTextOnly)
                        date = formatterDate.format(date1);
                    else
                        date = formatter.format(date1);

                }
            } catch (Exception e) {
                LOG.info("Message Date Format Error : " + e.getMessage());
            }

            if (isTextOnly) {
                StringBuilder line = new StringBuilder();
                line.append("[").append(date).append("] ");
                String message = dbo.get("message").toString();
                if (TYPE_DELETED.equals(message))
                    message = TYPE_DELETED;
                if ("true".equals(dbo.get("isSystem"))) {
                    line.append("System Message: ");
                    if (message.endsWith("<br/>"))
                        message = message.substring(0, message.length() - 5);
                    line.append(message).append("\n");
                } else {
                    line.append(fullname).append(": ");
                    message = message.replaceAll("<br/>", "\n");
                    line.append(message).append("\n");
                }
                sb.insert(0, line);
            } else {
                if (!first)
                    sb.append(",");
                sb.append("{\"id\": \"").append(msgId).append("\",");
                sb.append("\"timestamp\": ").append(timestamp).append(",");
                if (dbo.containsField("lastUpdatedTimestamp")) {
                    sb.append("\"lastUpdatedTimestamp\": ").append(dbo.get("lastUpdatedTimestamp").toString())
                            .append(",");
                }
                sb.append("\"user\": \"").append(user).append("\",");
                sb.append("\"fullname\": \"").append(fullname).append("\",");
                sb.append("\"email\": \"").append(email).append("\",");
                sb.append("\"date\": \"").append(date).append("\",");
                sb.append("\"message\": \"").append(StringEscapeUtils.escapeJson(dbo.get("message").toString()))
                        .append("\",");
                if (dbo.containsField("options")) {
                    String options = dbo.get("options").toString();
                    if (options.startsWith("{"))
                        sb.append("\"options\": ").append(options).append(",");
                    else
                        sb.append("\"options\": \"").append(options).append("\",");
                } else {
                    sb.append("\"options\": \"\",");
                }
                sb.append("\"type\": \"").append(dbo.get("type")).append("\",");
                sb.append("\"isSystem\": \"").append(dbo.get("isSystem")).append("\"}");
            }

            first = false;
        }

        if (!isTextOnly) {
            sb.append("]}");
        }
    }

    return sb.toString();

}

From source file:org.flockdata.search.helper.QueryGenerator.java

public static String getSimpleQuery(QueryInterface params, Boolean highlightEnabled) {
    if (params.getFilter() != null)
        return getFilteredQuery(params, highlightEnabled);
    String queryString = params.getSearchText();
    if (queryString == null)
        queryString = "*";

    logger.debug("getSearchText {}", queryString);
    StringBuilder simpleQuery = new StringBuilder();
    if (queryString.contains("\"")) {
        queryString = StringEscapeUtils.escapeJson(queryString);
    }//  w ww. ja v  a 2  s  .  c  o  m

    simpleQuery.append("{ \"query\": {" + "        \"query_string\": { " + "            \"query\": " + '"')
            .append(queryString.toLowerCase()).append('"').append("          }").append("  }");

    if (highlightEnabled) {
        simpleQuery.append(",\n" + "  \"highlight\": { " + "\"pre_tags\" : [\"<strong>\"],"
                + "\"post_tags\" : [\"</strong>\"]," + "\"order\": \"score\", "
                + "\"require_field_match\": false, " +

                "\"encoder\" : \"html\"," + "    \"fields\": { " + "      \"*\": {} " + "    } " + "  }");
    }
    simpleQuery.append(" }");
    return simpleQuery.toString();
}

From source file:org.flockdata.search.helper.QueryGenerator.java

public static String getFilteredQuery(QueryInterface queryParams, Boolean highlightEnabled) {
    String queryString = queryParams.getSearchText();
    if (queryString == null)
        queryString = "*";

    logger.debug("getSearchText {}", queryString);
    StringBuilder simpleQuery = new StringBuilder();
    if (queryString.contains("\"")) {
        queryString = StringEscapeUtils.escapeJson(queryString);
    }//from   w w  w. j  a  v  a2 s.  c o m
    if (queryString.equals(""))
        queryString = "*";
    String filter = getRelationshipFilter(queryParams);
    simpleQuery.append("\n" + " {\"query\": {\n" + "    \"filtered\": {\n" + "       \"query\": {\n"
            + "           \"query_string\": {\"query\":\"" + queryString.toLowerCase() + "\"}\n" + "   "
            + (!filter.equals("") ? "}," + filter : "}") +
            //                filter +
            "  }\n" + "}");

    if (highlightEnabled) {
        simpleQuery.append(",\n" + "  \"highlight\": { " + "\"pre_tags\" : [\"<strong>\"],"
                + "\"post_tags\" : [\"</strong>\"]," + "\"encoder\" : \"html\"," + "    \"fields\": { "
                + "      \"*\": {} " + "    } " + "  }");
    }
    simpleQuery.append(" }");
    return simpleQuery.toString();
}

From source file:org.jasig.cas.web.report.InternalConfigStateController.java

/**
 * Handle request./*  w ww.jav a2 s.  c  o m*/
 *
 * @param request the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {

    final Map<String, Object> list = getBeans(this.applicationContext);
    LOGGER.debug("Found [{}] beans to report", list.size());

    final JsonSerializer<Object> serializer = new BeanObjectJsonSerializer();
    final StringBuilder builder = new StringBuilder();
    builder.append('[');

    final Set<Map.Entry<String, Object>> entries = list.entrySet();
    final Iterator<Map.Entry<String, Object>> it = entries.iterator();

    while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final Object obj = entry.getValue();

        final StringWriter writer = new StringWriter();
        writer.append('{');
        writer.append('\"' + entry.getKey() + "\":");
        serializer.toJson(writer, obj);
        writer.append('}');
        builder.append(writer);

        if (it.hasNext()) {
            builder.append(',');
        }
    }
    builder.append(']');
    final ModelAndView mv = new ModelAndView(VIEW_CONFIG);
    final String jsonData = StringEscapeUtils.escapeJson(builder.toString());

    mv.addObject("jsonData", jsonData);
    mv.addObject("properties", casProperties.entrySet());
    return mv;
}

From source file:org.jsweet.transpiler.Java2TypeScriptTranslator.java

private void printBlockStatements(List<JCStatement> statements) {
    for (JCStatement statement : statements) {
        if (context.options.isDebugMode()) {
            JCMethodDecl methodDecl = getParent(JCMethodDecl.class);
            if (isDebugMode(methodDecl)) {
                int s = statement.getStartPosition();
                int e = statement.getEndPosition(diagnosticSource.getEndPosTable());
                if (e == -1) {
                    e = s;//from  w  w w  .  ja va2 s.  c o  m
                }
                printIndent().print("yield { row: ").print("" + diagnosticSource.getLineNumber(s))
                        .print(", column: " + diagnosticSource.getColumnNumber(s, false))
                        .print(", statement: \"");
                print(StringEscapeUtils.escapeJson(statement.toString())).print("\"");

                final Stack<List<String>> locals = new Stack<>();
                try {
                    new TreeScanner() {
                        public void scan(JCTree tree) {
                            if (tree == statement) {
                                throw new RuntimeException();
                            }
                            boolean contextChange = false;
                            if (tree instanceof JCBlock || tree instanceof JCEnhancedForLoop
                                    || tree instanceof JCLambda || tree instanceof JCForLoop
                                    || tree instanceof JCDoWhileLoop) {
                                locals.push(new ArrayList<>());
                                contextChange = true;
                            }
                            if (tree instanceof JCVariableDecl) {
                                locals.peek().add(((JCVariableDecl) tree).name.toString());
                            }
                            super.scan(tree);
                            if (contextChange) {
                                locals.pop();
                            }
                        }

                    }.scan(methodDecl.body);
                } catch (Exception end) {
                    // swallow
                }
                List<String> accessibleLocals = new ArrayList<>();
                for (List<String> l : locals) {
                    accessibleLocals.addAll(l);
                }
                if (!accessibleLocals.isEmpty()) {
                    print(", locals: ");
                    print("{");
                    for (String local : accessibleLocals) {
                        print("" + local + ": " + local + ", ");
                    }
                    removeLastChars(2);
                    print("}");
                }
                print(" };").println();
            }
        }
        printBlockStatement(statement);
    }
}

From source file:org.onosproject.codec.impl.ApplicationCodec.java

@Override
public ObjectNode encode(Application app, CodecContext context) {
    checkNotNull(app, "Application cannot be null");
    ApplicationService service = context.getService(ApplicationService.class);

    ArrayNode permissions = context.mapper().createArrayNode();
    ArrayNode features = context.mapper().createArrayNode();
    ArrayNode requiredApps = context.mapper().createArrayNode();

    app.permissions().forEach(p -> permissions.add(p.toString()));
    app.features().forEach(f -> features.add(f));
    app.requiredApps().forEach(a -> requiredApps.add(a));

    ObjectNode result = context.mapper().createObjectNode().put("name", app.id().name())
            .put("id", app.id().id()).put("version", app.version().toString()).put("category", app.category())
            .put("description", StringEscapeUtils.escapeJson(app.description()))
            .put("readme", StringEscapeUtils.escapeJson(app.readme())).put("origin", app.origin())
            .put("url", app.url()).put("featuresRepo", app.featuresRepo().map(URI::toString).orElse(""))
            .put("state", service.getState(app.id()).toString());

    result.set("features", features);
    result.set("permissions", permissions);
    result.set("requiredApps", requiredApps);

    return result;
}

From source file:org.openrepose.commons.utils.logging.apache.format.stock.ResponseMessageHandler.java

@Override
public String handle(HttpServletRequest request, HttpServletResponse response) {
    String message = MutableHttpServletResponse.wrap(request, response).getMessage();
    if (message == null) {
        message = "";
    } else {/* ww  w.  ja  va  2  s .c o m*/
        switch (state) {
        case JSON:
            message = StringEscapeUtils.escapeJson(message);
            break;
        case XML:
            message = StringEscapeUtils.escapeXml10(message);
            break;
        }
    }
    return message;
}

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

@Override
@POST/*from   w  w  w. j  a  va2s  .c  o m*/
@Path("nodesource")
@Produces("application/json")
public NSState defineNodeSource(@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[] infraParams = this.getAllInfrastructureParameters(infrastructureType, infrastructureParameters,
            infrastructureFileParameters, rm);
    Object[] policyParams = this.getAllPolicyParameters(policyType, policyParameters, policyFileParameters, rm);

    try {
        nsState.setResult(rm.defineNodeSource(nodeSourceName, infrastructureType, infraParams, policyType,
                policyParams, Boolean.parseBoolean(nodesRecoverable)).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/*from   w  w  w.  j  av  a2s  .  com*/
@Path("nodesource/edit")
@Produces("application/json")
public NSState editNodeSource(@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[] infraParams = this.getAllInfrastructureParameters(infrastructureType, infrastructureParameters,
            infrastructureFileParameters, rm);
    Object[] policyParams = this.getAllPolicyParameters(policyType, policyParameters, policyFileParameters, rm);

    try {
        nsState.setResult(rm.editNodeSource(nodeSourceName, infrastructureType, infraParams, policyType,
                policyParams, Boolean.parseBoolean(nodesRecoverable)).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/*from  w w w. j  av a 2  s  .  c o m*/
@Path("nodesource/parameter")
@Produces("application/json")
public NSState updateDynamicParameters(@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) throws NotConnectedException {

    ResourceManager rm = checkAccess(sessionId);
    NSState nsState = new NSState();

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

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

    try {
        nsState.setResult(rm.updateDynamicParameters(nodeSourceName, infrastructureType, infraParams,
                policyType, policyParams).getBooleanValue());
    } catch (RuntimeException ex) {
        nsState.setResult(false);
        nsState.setErrorMessage(cleanDisplayedErrorMessage(ex.getMessage()));
        nsState.setStackTrace(StringEscapeUtils.escapeJson(getStackTrace(ex)));
    }

    return nsState;
}