Example usage for org.json.simple JSONValue toJSONString

List of usage examples for org.json.simple JSONValue toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONValue toJSONString.

Prototype

public static String toJSONString(Object value) 

Source Link

Usage

From source file:org.imsglobal.lti.toolProvider.ContentItem.java

/**
 * Wrap the content items to form a complete application/vnd.ims.lti.v1.contentitems+json media type instance.
 *
 * @param mixed items An array of content items or a single item
 * @return string// ww  w .ja v a 2  s  . co  m
 */

public static String toJson(ContentItem item) {
    Map<String, String> wrapper = new HashMap<String, String>();
    wrapper.put("@context", "http://purl.imsglobal.org/ctx/lti/v1/ContentItem");
    wrapper.put("@graph", item.toJSONString());
    return JSONValue.toJSONString(wrapper);

}

From source file:org.imsglobal.lti.toolProvider.ContentItem.java

public String toJSONString() {
    Map<String, String> obj = new HashMap<String, String>();
    if (type != null)
        obj.put("type", type);
    if (id != null)
        obj.put("id", id);
    if (mediaType != null)
        obj.put("mediaType", mediaType);
    if (title != null)
        obj.put("title", title);
    if (text != null)
        obj.put("text", text);
    if (url != null)
        obj.put("url", url.toExternalForm());
    if (placementAdvice != null)
        obj.put("placementAdvice", placementAdvice.toJSONString());
    return JSONValue.toJSONString(obj);
}

From source file:org.imsglobal.lti.toolProvider.ContentItemPlacement.java

public String toJSONString() {
    Map<String, String> obj = new HashMap<String, String>();
    obj.put("displayWidth", "" + displayWidth);
    obj.put("displayHeight", "" + displayHeight);
    if (documentTarget != null)
        obj.put("documentTarget", documentTarget);
    if (windowTarget != null)
        obj.put("windowTarget", windowTarget);
    return JSONValue.toJSONString(obj);
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    // Normally we would look up the deployment descriptor
    if (!TEST_KEY.equals(profile_id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*www. j ava  2 s  . c om*/
    }

    String key = TEST_KEY;
    String secret = TEST_SECRET;

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }

    System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    System.out.println("shared_secret=" + shared_secret);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Pass the profile to the launch process
    PERSIST.put("profile", providerProfile.toString());

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.log(Level.FINE, jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleResultRequest(HttpServletRequest request, HttpServletResponse response, String sourcedid)
        throws java.io.IOException {
    IMSJSONRequest jsonRequest = null;/*from   w ww .  j av  a  2s  . c o  m*/
    String retval = null;
    if ("GET".equals(request.getMethod())) {
        String grade = PERSIST.get("grade");
        String comment = PERSIST.get("comment");

        Map jsonResponse = new TreeMap();
        Map resultScore = new TreeMap();

        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.RESULT_CONTEXT);
        jsonResponse.put(LTI2Constants.TYPE, StandardServices.RESULT_TYPE);
        resultScore.put(LTI2Constants.TYPE, LTI2Constants.GRADE_TYPE_DECIMAL);
        jsonResponse.put(LTI2Constants.COMMENT, grade);
        resultScore.put(LTI2Constants.VALUE, comment);
        jsonResponse.put(LTI2Constants.RESULTSCORE, resultScore);
        response.setContentType(StandardServices.RESULT_FORMAT);
        response.setStatus(HttpServletResponse.SC_OK);
        String jsonText = JSONValue.toJSONString(jsonResponse);
        M_log.log(Level.FINE, jsonText);
        PrintWriter out = response.getWriter();
        out.println(jsonText);
        return;
    } else if ("PUT".equals(request.getMethod())) {
        retval = "Error parsing input data";
        try {
            jsonRequest = new IMSJSONRequest(request);
            // System.out.println(jsonRequest.getPostBody());
            JSONObject requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
            String comment = (String) requestData.get(LTI2Constants.COMMENT);
            JSONObject resultScore = (JSONObject) requestData.get(LTI2Constants.RESULTSCORE);
            String sGrade = (String) resultScore.get(LTI2Constants.VALUE);
            Double dGrade = new Double(sGrade);

            PERSIST.put("comment", comment);
            PERSIST.put("grade", dGrade + "");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            retval = "Error: " + e.getMessage();
        }
    } else {
        retval = "Unsupported operation:" + request.getMethod();
    }

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    doErrorJSON(request, response, jsonRequest, (String) retval, null);
}

From source file:org.jboss.aerogear.sync.server.gcm.GcmMessages.java

/**
 * Creates a JSON encoded GCM message.// ww w.j  ava  2 s.c o  m
 *
 * @param to RegistrationId of the target device (Required).
 * @param messageId Unique messageId for which CCS will send an "ack/nack"
 * (Required).
 * @param payload Message content intended for the application. (Optional).
 * @param collapseKey GCM collapse_key parameter (Optional).
 * @param timeToLive GCM time_to_live parameter (Optional).
 * @param delayWhileIdle GCM delay_while_idle parameter (Optional).
 * @return JSON encoded GCM message.
 */
public static String createJsonMessage(String to, String messageId, String payload, String collapseKey,
        Long timeToLive, Boolean delayWhileIdle) {
    Map<String, Object> message = new HashMap<String, Object>();
    message.put("to", to);
    if (collapseKey != null) {
        message.put("collapse_key", collapseKey);
    }
    if (timeToLive != null) {
        message.put("time_to_live", timeToLive);
    }
    if (delayWhileIdle != null && delayWhileIdle) {
        message.put("delay_while_idle", true);
    }
    message.put("message_id", messageId);
    message.put("data", payloadToMap(payload));
    return JSONValue.toJSONString(message);
}

From source file:org.jitsi.videobridge.simulcast.messages.SimulcastMessagesMapper.java

private void toJson(StringBuilder b, EndpointSimulcastStream endpointSimulcastStream) {
    if (b == null || endpointSimulcastStream == null) {
        return;/*from w ww  .j a v  a 2  s.c  o m*/
    }

    b.append("{\"endpoint\":");
    // NOTE(gp) do not change this to JSONValue.escape()! It breaks JSON
    // parsing at the client!
    b.append(JSONValue.toJSONString(endpointSimulcastStream.endpoint));
    b.append(",\"simulcastStream\":");
    toJson(b, endpointSimulcastStream.simulcastStream);
    b.append("}");
}

From source file:org.kawanfw.commons.json.ListOfStringTransport.java

/**
 * Format for JSON String a list of strings
 * //from w w w  .j  a  v  a  2 s .  com
 * @param list
 *            a list of strings
 * 
 * @return the formated JSON string ready for transport
 */

public static String toJson(List<String> list) {

    if (list == null) {
        throw new IllegalArgumentException("list is null!");
    }

    String jsonString = JSONValue.toJSONString(list);
    // free resultSetLine
    list = null;
    return jsonString;

}

From source file:org.kawanfw.sql.json.IntArrayTransport.java

/**
 * Format to JSON a int array/*w  w  w  .j  a  v a 2s  .co m*/
 * 
 * @param intArray
 *            the in array to format
 * @return the JSON string
 */
public static String toJson(int[] intArray) {
    if (intArray == null) {
        throw new IllegalArgumentException("batchResults is null!");
    }

    List<Integer> list = new Vector<Integer>();
    for (int i = 0; i < intArray.length; i++) {
        list.add(intArray[i]);
    }

    // NO!
    // List list = Arrays.asList(intArray);

    String jsonString = JSONValue.toJSONString(list);
    debug(jsonString);
    return jsonString;

}

From source file:org.kawanfw.sql.json.JsonColPosition.java

/**
 * Format for JSON String the Map<String, Integer> of (column name, column
 * position) of a result set/*from www .j a va  2s. co m*/
 * 
 * @param columnPositions
 *            the Map<String, Integer> of (column name, column position) of
 *            a result set
 * @return the formated JSON string ready for transport
 */

public static String toJson(Map<String, Integer> columnPositions) {
    if (columnPositions == null) {
        throw new IllegalArgumentException("columsAndValues is null!");
    }

    String jsonString = JSONValue.toJSONString(columnPositions);

    jsonString = HtmlConverter.toHtml(jsonString);

    debug(" toJson(Map<String, Integer> columnPositions) jsonString: " + jsonString);
    return jsonString;
}