Example usage for org.json JSONObject quote

List of usage examples for org.json JSONObject quote

Introduction

In this page you can find the example usage for org.json JSONObject quote.

Prototype

public static String quote(String string) 

Source Link

Document

Produce a string in double quotes with backslash sequences in all the right places.

Usage

From source file:com.phonegap.FileUploadResult.java

public JSONObject toJSONObject() throws JSONException {
    return new JSONObject("{bytesSent:" + bytesSent + ",responseCode:" + responseCode + ",response:"
            + JSONObject.quote(response) + "}");
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model/*w  w  w  .  ja  v a2s. co  m*/
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}

From source file:org.skt.runtime.api.PluginResult.java

public PluginResult(Status status, String message) {
    this.status = status.ordinal();
    this.message = JSONObject.quote(message);
}

From source file:com.footprint.cordova.plugin.localnotification.LocalNotification.java

/**
 * Fires the given event./*from   w w w.j  a  va 2s. c  om*/
 *
 * @param {String} event The Name of the event
 * @param {String} id    The ID of the notification
 * @param {String} json  A custom (JSON) string
 */
public static void fireEvent(String event, String id, String json) {
    String state = getApplicationState();
    String params = "\"" + id + "\",\"" + state + "\",\\'" + JSONObject.quote(json)
            + "\\'.replace(/(^\"|\"$)/g, \\'\\')";
    String js = "setTimeout('plugin.notification.local.on" + event + "(" + params + ")',0)";

    // webview may available, but callbacks needs to be executed
    // after deviceready
    if (deviceready == false) {
        eventQueue.add(js);
    } else {
        webView.sendJavascript(js);
    }
}

From source file:org.apache.cordova.filetransfer.FileUploadResult.java

public JSONObject toJSONObject() throws JSONException {
    return new JSONObject("{bytesSent:" + bytesSent + ",responseCode:" + responseCode + ",response:"
            + JSONObject.quote(response) + ",objectId:" + JSONObject.quote(objectId) + "}");
}

From source file:com.urbtek.phonegap.SpeechRecognizer.java

private void ReturnSpeechResults(int requestCode, ArrayList<String> matches) {
    boolean firstValue = true;
    StringBuilder sb = new StringBuilder();
    sb.append("{\"speechMatches\": {");
    sb.append("\"requestCode\": ");
    sb.append(Integer.toString(requestCode));
    sb.append(", \"speechMatch\": [");

    Iterator<String> iterator = matches.iterator();
    while (iterator.hasNext()) {
        String match = iterator.next();

        if (firstValue == false)
            sb.append(", ");
        firstValue = false;//from ww  w  .  ja  v  a  2s  .com
        sb.append(JSONObject.quote(match));
    }
    sb.append("]}}");

    PluginResult result = new PluginResult(PluginResult.Status.OK, sb.toString());
    result.setKeepCallback(false);
    this.success(result, this.speechRecognizerCallbackId);
    this.speechRecognizerCallbackId = "";
}

From source file:org.cosmo.common.util.JSONList.java

public static byte[] valueToBytes(Object value) throws JSONException, IOException {
    if (value == null || value.equals(null)) {
        return Constants.NullByteMarker;
    }/*from  w  w  w.java 2  s .  c  om*/
    // return raw bytes is value is byte[] - else use normal json string conversion
    if (value instanceof byte[]) {
        return (byte[]) value;
    }

    if (value instanceof long[]) {
        return Util.UTF8(longArrayString((long[]) value));
    }

    if (value instanceof JSONString) {
        Object o;
        try {
            o = ((JSONString) value).toJSONString();
        } catch (Exception e) {
            throw new JSONException(e);
        }
        if (o instanceof String) {
            return Util.UTF8(o);
        }
        throw new JSONException("Bad value from toJSONString: " + o);
    }
    if (value instanceof Number) {
        return Util.UTF8(JSONObject.numberToString((Number) value));
    }
    if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) {
        return Util.UTF8(value);
    }
    if (value instanceof Map) {
        return Util.UTF8(new JSONObject((Map) value));
    }
    if (value instanceof JSONList) {
        return ((JSONList) value).getBytes().makeExact().bytes();
    }
    if (value instanceof List) {
        return new JSONList((List) value).getBytes().makeExact().bytes();
    }
    if (value instanceof Collection) {
        return Util.UTF8(new JSONArray((Collection) value));
    }
    if (value.getClass().isArray()) {
        return Util.UTF8(new JSONArray(value));
    }
    return Util.UTF8(JSONObject.quote(value.toString()));
}

From source file:com.dz0ny.mopidy.shim.WebSocket.java

/**
 * Builds text for javascript engine to invoke proper event method with
 * proper data.//from w  w w .  j a  v a2s. c o  m
 *
 * @param event websocket event (onOpen, onMessage etc.)
 * @param msg   Text message received from websocket server
 * @return
 */
private String buildJavaScriptData(String event, String msg) {

    String json = "javascript:WebSocket." + event + "({\"_target\":\"" + this.id + "\",\"data\":%s})";
    return String.format(json, JSONObject.quote(msg));
}

From source file:org.cosmo.common.util.Util.java

public static byte[] jsonQuoteBytes(Object o) {
    return Util.UTF8(JSONObject.quote(o.toString()));
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.ClusterController.java

/**
 * Cluster documentsToCluster retrieved by search
 * @param clusteringAlgo the type of cluster to create - flat (0), hierarchical (1)
 * @param service the service the user has chosen to execute query in
 * @param icwservice underlying ICWSearcher service to be used when searching
 * @param query query to be executed/*from  w  ww  .jav  a  2s . c o  m*/
 * @param numResults number of results to be retrieved
 * @param start first result to be retrieved
 * @param model
 * @return
 * @throws Exception
 */
@RequestMapping("/clusterJson/{clusteringAlgo}/{service}/{icwservice}/{query}/{numResults}/{start}/{includeEdits}")
public void clusterJson(@PathVariable("clusteringAlgo") String clusteringAlgo,
        @PathVariable("service") String service, @PathVariable("icwservice") String icwservice,
        @PathVariable("query") String query, @PathVariable("numResults") String numResults,
        @PathVariable("start") String start, @PathVariable("includeEdits") String inclEdits,
        HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

    int includeEdits = 0;
    try {
        includeEdits = Integer.parseInt(inclEdits);
    } catch (NumberFormatException e) {
        /* do nothing */ }

    executionTimersId = ExecutionTimes.initiateTimers();
    ExecutionTimes.startTimer(executionTimersId, "total");

    //Execute search
    ICWSearchResultCol search = null;
    query = query.trim().toLowerCase();
    try {
        ExecutionTimes.startTimer(executionTimersId, "search");
        search = doSearch(service, icwservice, query, numResults, start);

        //if topic query, remove topic id from query string - not important for clustering
        if (query.indexOf("topic:") > -1) {
            final int p = query.indexOf("topic:");
            int s = query.indexOf(" ", p + 1);
            if (s < 0) {
                query = URLDecoder.decode(query, "UTF-8");
                s = query.indexOf(" ", p + 1);
            }
            if (s > 0)
                query = query.substring(s + 1);
        }

        ExecutionTimes.stopTimer(executionTimersId, "search");
        ExecutionTimes.startTimer(executionTimersId, "cluster");

        //identify user id for aggregated user
        if (allUserId == null) {
            User u = applicationUser.getUserDao().selectUserByEmail("all");
            if (u == null) {
                sendOutput(response, "{\"error\":\"The agregated user 'all' does not exist.\"}");
                return;
            }
            allUserId = u.getId();
        }

        //analyze query text
        //the cluster root
        ICluster root = clusterResults(search, query, clusteringAlgo);

        ExecutionTimes.stopTimer(executionTimersId, "cluster");

        //analyze and save query if necessary
        ICollectionContext ctx = root.getContext();
        String analyzedQuery = ctx.getAnalyzedQuery();

        int queryId = -1;
        int allQueryId = -1;

        //create JSON versions of cluster and results
        JSONObject cluster = null;
        JSONObject results = search.toJSON();

        //if initial search, store query updates and include edits in the cluster
        if (includeEdits == 1) {

            ExecutionTimes.startTimer(executionTimersId, "preferences");

            //identify or store query in database
            Integer userId = applicationUser.getUserId();
            Query q = findBestMatchingQuery(query, analyzedQuery, userId, allUserId, search, icwservice,
                    Integer.valueOf(numResults), Integer.valueOf(clusteringAlgo));
            Query qAll = queryDao.selectExistingUserQuery(allUserId, icwservice, Integer.valueOf(numResults),
                    query);

            if (applicationUser.isLoggedIn()) {
                //save query for user 'all'
                if (qAll == null) {
                    List<String> urls = search.getTopKResponseUrls(ApplicationSettings.getTopKQueryUrls());
                    qAll = new Query(allUserId, icwservice, Integer.valueOf(numResults), query, null, urls);
                    qAll.setParsedText(analyzedQuery);
                    queryDao.saveQuery(qAll);
                } else {
                    long now = System.currentTimeMillis() - MILLISECS_PER_DAY;
                    long then = qAll.getExecutedOn() != null ? qAll.getExecutedOn().getTime() : now;
                    if (Long.valueOf(now).compareTo(then) > 0) {
                        //update query responses if they have not been updated in more than k days, k=1
                        List<String> urls = search.getTopKResponseUrls(ApplicationSettings.getTopKQueryUrls());
                        qAll.setExecutedOn(new Date());
                        qAll.updateResponses(urls);
                        qAll.setParsedText(analyzedQuery);
                        queryDao.saveQuery(qAll);
                    }
                }
            }
            List<ClusterEdit> edits = null;

            if (qAll != null)
                allQueryId = qAll.getId();

            //retrieve preferences to be applied to cluster
            if (q != null) {
                queryId = q.getId();
                edits = clusterEditDao.selectClusterEditsForUserQuery(queryId, Integer.valueOf(clusteringAlgo),
                        q.getUserId().equals(allUserId));
            }
            if (edits != null && edits.size() > 0) {
                //apply preferences to cluster
                IClusterEditor clusterEditor = new ClusterEditor(root, edits, ctx);
                cluster = clusterEditor.applyUserEdits();
            } else {
                cluster = root.toJSON();
            }

            ExecutionTimes.stopTimer(executionTimersId, "preferences");
        } else {
            cluster = root.toJSON();
        }

        //Recursively sort cluster labels in each level
        ExecutionTimes.startTimer(executionTimersId, "sort");
        if (cluster.get("children") != null && cluster.get("children") instanceof JSONArray) {
            final JSONArray children = cluster.getJSONArray("children");
            if (children.length() > 0) {
                final MinDocIndexJSONClusterQueue sortQueue = new MinDocIndexJSONClusterQueue(children.length(),
                        cluster);
                cluster = sortChildren(cluster, sortQueue.clusterPages);
            }
        }
        ExecutionTimes.stopTimer(executionTimersId, "sort");

        //attach custom result label map
        cluster.put("customResultLabels", ctx.getCustomResultLabels());

        ExecutionTimes.stopTimer(executionTimersId, "total");

        JSONObject timers = ExecutionTimes.toJSON(executionTimersId);

        //no more need for these timers
        ExecutionTimes.clear(executionTimersId);

        sendOutput(response,
                "{\"success\":true,\"cluster\":" + cluster + ",\"results\":" + results + ",\"query_id\":"
                        + queryId + ",\"all_query_id\":" + allQueryId + ",\"timers\":" + timers + "}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}