Java Code Examples for org.json.simple.JSONValue#toJSONString()

The following examples show how to use org.json.simple.JSONValue#toJSONString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Properties.java    From spf with GNU General Public License v2.0 6 votes vote down vote up
public static String toString(Map<String, String> properties,
		boolean useOldVersion) {
	if (useOldVersion) {
		final StringBuilder sb = new StringBuilder();
		final Iterator<Entry<String, String>> iterator = properties
				.entrySet().iterator();
		while (iterator.hasNext()) {
			final Entry<String, String> property = iterator.next();
			sb.append(property.getKey());
			sb.append(OLD_KEY_VALUE_SEPARATOR);
			sb.append(property.getValue());
			if (iterator.hasNext()) {
				sb.append(OLD_PROPERTY_SEPARATOR_CHAR);
			}
		}
		return sb.toString();
	} else {
		return JSON_PREFIX + JSONValue.toJSONString(properties);
	}
}
 
Example 2
Source File: TestJson.java    From hangout with MIT License 6 votes vote down vote up
@Test
public void testJsonDump() {
    HashMap event = new HashMap<String, Object>() {
        {
            put("message", "hello json");
            put("@timestamp", DateTime.parse("2017-03-02T11:15:54+0800"));
        }
    };

    String rst = JSONValue.toJSONString(event);
    Assert.assertEquals(rst, "{\"@timestamp\":\"2017-03-02T11:15:54.000+08:00\",\"message\":\"hello json\"}");

    event.clear();
    event.put("message", "this is \"hello\" world");
    rst = JSONValue.toJSONString(event);
    Assert.assertEquals(rst, "{\"message\":\"this is \\\"hello\\\" world\"}");
}
 
Example 3
Source File: URITemplate.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public String getResourceMap(){
    Map verbs = new LinkedHashMap();
    int i = 0;
    for (String method : httpVerbs) {
        Map verb = new LinkedHashMap();
        verb.put("auth_type",authTypes.get(i));
        verb.put("throttling_tier",throttlingTiers.get(i));
        //Following parameter is not required as it not need to reflect UI level. If need please enable it.
        // /verb.put("throttling_conditions", throttlingConditions.get(i));
        try{
            Scope tmpScope = scopes.get(i);
            if(tmpScope != null){
                verb.put("scope",tmpScope.getKey());
            }
        }catch(IndexOutOfBoundsException e){
            //todo need to rewrite to prevent this type of exceptions
        }
        verbs.put(method,verb);
        i++;
    }
    //todo this is a hack to make key validation service stub from braking need to rewrite.
    return JSONValue.toJSONString(verbs);
}
 
Example 4
Source File: SmackGcmSenderChannel.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a JSON encoded GCM message.
 *
 * @param to
 *            RegistrationId of the target device (Required).
 * @param messageId
 *            Unique messageId for which CCS sends an "ack/nack" (Required).
 * @param payload
 *            Message content intended for the application. (Optional).
 * @return JSON encoded GCM message.
 */
protected static String createJsonMessage(String to, String messageId, Map<String, Object> payload) {
    Map<String, Object> message = new HashMap<String, Object>();
    message.put("to", to);
    message.put("message_id", messageId);
    message.put("delivery_receipt_requested", true);
    for (String key : payload.keySet()) {
    	message.put(key, payload.get(key));
    }

    return JSONValue.toJSONString(message);
}
 
Example 5
Source File: Cypher.java    From knowbi-pentaho-pdi-neo4j-output with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the given record value to String.
 * For complex data types it's a conversion to JSON.
 *
 * @param recordValue
 * @param sourceType
 * @return the JSON string
 */
private String convertToString( Value recordValue, GraphPropertyDataType sourceType ) {
  if (recordValue==null) {
    return null;
  }
  if (sourceType==null) {
    return JSONValue.toJSONString( recordValue.asObject() );
  }
  switch(sourceType){
    case String: return recordValue.asString();
    default: return JSONValue.toJSONString( recordValue.asObject() );
  }
}
 
Example 6
Source File: IMSJSONRequest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
public static String doErrorJSON(HttpServletRequest request,HttpServletResponse response, 
		IMSJSONRequest json, String message, Exception e) 
	throws java.io.IOException 
{
	response.setContentType(APPLICATION_JSON);
	response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
	Map<String, Object> jsonResponse = new TreeMap<String, Object>();

	Map<String, String> status = null;
	if ( json == null ) {
		status = IMSJSONRequest.getStatusFailure(message);
	} else {
		status = json.getStatusFailure(message);
		if ( json.base_string != null ) {
			jsonResponse.put("base_string", json.base_string);
		}
		if ( json.errorMessage != null ) {
			jsonResponse.put("error_message", json.errorMessage);
		}
	}
	jsonResponse.put(IMSJSONRequest.STATUS, status);
	if ( e != null ) {
		jsonResponse.put("exception", e.getLocalizedMessage());
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			log.error("{}", pw);
			pw.flush();
			sw.flush();
			jsonResponse.put("traceback", sw.toString() );
		} catch ( Exception f ) {
			jsonResponse.put("traceback", f.getLocalizedMessage());
		}
	}
	String jsonText = JSONValue.toJSONString(jsonResponse);
	PrintWriter out = response.getWriter();
	out.println(jsonText);
	return jsonText;
}
 
Example 7
Source File: Op.java    From ethereumj with MIT License 5 votes vote down vote up
public String toString(){

        Map<Object, Object> jsonData = new LinkedHashMap<>();

        jsonData.put("op", OpCode.code(op).name());
        jsonData.put("pc", Long.toString(pc));
        jsonData.put("gas", gas.value().toString());
        jsonData.put("stack", stack);
        jsonData.put("memory", memory == null ? "" : Hex.toHexString(memory));
        jsonData.put("storage", new JSONObject(storage)  );

        return JSONValue.toJSONString(jsonData);
    }
 
Example 8
Source File: RequestProcessor.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    RequestProcessor.LOG.debug("Creation of the json request body...");

    final String className =
        exchange.getIn().getHeader(ApplicationBusConstants.CLASS_NAME.toString(), String.class);
    final String operationName =
        exchange.getIn().getHeader(ApplicationBusConstants.OPERATION_NAME.toString(), String.class);

    final LinkedHashMap<String, Object> params = exchange.getIn().getBody(LinkedHashMap.class);

    // JSON body creation
    final JSONObject infoJSON = new JSONObject();
    infoJSON.put("class", className);
    infoJSON.put("operation", operationName);

    final LinkedHashMap<String, Object> finalJSON = new LinkedHashMap<>();
    finalJSON.put("invocation-information", infoJSON);
    if (params != null) {
        finalJSON.put("params", params);
    }

    final String finalJSONString = JSONValue.toJSONString(finalJSON);

    RequestProcessor.LOG.debug("Created json request body: {}", finalJSONString);

    exchange.getIn().setBody(finalJSONString);
}
 
Example 9
Source File: IMSJSONRequest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
public static String doErrorJSON(HttpServletRequest request,HttpServletResponse response, 
		IMSJSONRequest json, String message, Exception e) 
	throws java.io.IOException 
{
	response.setContentType(APPLICATION_JSON);
	Map<String, Object> jsonResponse = new TreeMap<String, Object>();

	Map<String, String> status = null;
	if ( json == null ) {
		status = IMSJSONRequest.getStatusFailure(message);
	} else {
		status = json.getStatusFailure(message);
		if ( json.base_string != null ) {
			jsonResponse.put("base_string", json.base_string);
		}
	}
	jsonResponse.put(IMSJSONRequest.STATUS, status);
	if ( e != null ) {
		jsonResponse.put("exception", e.getLocalizedMessage());
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			e.printStackTrace(pw);
			pw.flush();
			sw.flush();
			jsonResponse.put("traceback", sw.toString() );
		} catch ( Exception f ) {
			jsonResponse.put("traceback", f.getLocalizedMessage());
		}
	}
	String jsonText = JSONValue.toJSONString(jsonResponse);
	PrintWriter out = response.getWriter();
	out.println(jsonText);
	return jsonText;
}
 
Example 10
Source File: jcoSon.java    From jcoSon with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param destination A valid JCo Destination
 * @return json Representation of the JCo Function call
 * @throws JCoException
 */
public String execute(JCoDestination destination) throws JCoException
{
    LinkedHashMap resultList = new LinkedHashMap();
    try
    {
        function.execute(destination);
    }
    catch(AbapException e)
    {
       resultList.put(e.getKey(),e);
    }
    catch (JCoException ex)
    {
        resultList.put(ex.getKey(),ex);
    }
    //Export Parameters
    if(function.getExportParameterList()!= null)
    {
        getFields(function.getExportParameterList().getFieldIterator(),resultList);
    }
    //Changing parameters
    if(function.getChangingParameterList()!= null)
    {
        getFields(function.getChangingParameterList().getFieldIterator(),resultList);
    }
    //Table Parameters
    if(function.getTableParameterList()!= null)
    {
        getFields(function.getTableParameterList().getFieldIterator(),resultList);
    }
    return JSONValue.toJSONString(resultList);
}
 
Example 11
Source File: IMSJSONRequest.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
public static String doErrorJSON(HttpServletRequest request,HttpServletResponse response, 
		IMSJSONRequest json, String message, Exception e) 
	throws java.io.IOException 
{
	response.setContentType(APPLICATION_JSON);
	response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
	Map<String, Object> jsonResponse = new TreeMap<String, Object>();

	Map<String, String> status = null;
	if ( json == null ) {
		status = IMSJSONRequest.getStatusFailure(message);
	} else {
		status = json.getStatusFailure(message);
		if ( json.base_string != null ) {
			jsonResponse.put("base_string", json.base_string);
		}
		if ( json.errorMessage != null ) {
			jsonResponse.put("error_message", json.errorMessage);
		}
	}
	jsonResponse.put(IMSJSONRequest.STATUS, status);
	if ( e != null ) {
		jsonResponse.put("exception", e.getLocalizedMessage());
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw, true);
			log.error("{}", pw);
			pw.flush();
			sw.flush();
			jsonResponse.put("traceback", sw.toString() );
		} catch ( Exception f ) {
			jsonResponse.put("traceback", f.getLocalizedMessage());
		}
	}
	String jsonText = JSONValue.toJSONString(jsonResponse);
	PrintWriter out = response.getWriter();
	out.println(jsonText);
	return jsonText;
}
 
Example 12
Source File: PrettyProtobuf.java    From storm with Apache License 2.0 5 votes vote down vote up
/**
 * Pretty-print mesos protobuf TaskStatus.
 */
public static String taskStatusToString(TaskStatus taskStatus) {
  Map<String, String> map = new LinkedHashMap<>();
  map.put("task_id", taskStatus.getTaskId().getValue());
  map.put("slave_id", taskStatus.getSlaveId().getValue());
  map.put("state", taskStatus.getState().toString());
  if (taskStatus.hasMessage()) {
    map.put("message", taskStatus.getMessage());
  }
  return JSONValue.toJSONString(map);
}
 
Example 13
Source File: PrettyProtobuf.java    From storm with Apache License 2.0 5 votes vote down vote up
/**
 * Pretty-print mesos protobuf TaskInfo.
 * <p/>
 * XXX(erikdw): not including command, container (+data), nor health_check.
 */
public static String taskInfoToString(TaskInfo task) {
  Map<String, String> map = new LinkedHashMap<>();
  map.put("task_id", task.getTaskId().getValue());
  map.put("slave_id", task.getSlaveId().getValue());
  map.putAll(resourcesToOrderedMap(task.getResourcesList()));
  map.put("executor_id", task.getExecutor().getExecutorId().getValue());
  return JSONValue.toJSONString(map);
}
 
Example 14
Source File: PrettyProtobuf.java    From storm with Apache License 2.0 5 votes vote down vote up
/**
 * Pretty-print mesos protobuf Offer.
 * <p/>
 * XXX(erikdw): not including slave_id, attributes, executor_ids, nor framework_id.
 */
public static String offerToString(Offer offer) {
  Map<String, String> map = new LinkedHashMap<>();
  map.put("offer_id", offer.getId().getValue());
  map.put("hostname", offer.getHostname());
  map.putAll(resourcesToOrderedMap(offer.getResourcesList()));
  return JSONValue.toJSONString(map);
}
 
Example 15
Source File: ReturnResultsReducer.java    From jstorm with Apache License 2.0 5 votes vote down vote up
@Override
public void complete(ReturnResultsState state, TridentCollector collector) {
    // only one of the multireducers will receive the tuples
    if (state.returnInfo != null) {
        String result = JSONValue.toJSONString(state.results);
        Map retMap = (Map) JSONValue.parse(state.returnInfo);
        final String host = (String) retMap.get("host");
        final int port = Utils.getInt(retMap.get("port"));
        String id = (String) retMap.get("id");
        DistributedRPCInvocations.Iface client;
        if (local) {
            client = (DistributedRPCInvocations.Iface) ServiceRegistry.getService(host);
        } else {
            List server = new ArrayList() {
                {
                    add(host);
                    add(port);
                }
            };

            if (!_clients.containsKey(server)) {
                try {
                    _clients.put(server, new DRPCInvocationsClient(conf, host, port));
                } catch (TTransportException ex) {
                    throw new RuntimeException(ex);
                }
            }
            client = _clients.get(server);
        }

        try {
            client.result(id, result);
        } catch (AuthorizationException aze) {
            collector.reportError(aze);
        } catch (TException e) {
            collector.reportError(e);
        }
    }
}
 
Example 16
Source File: Utils.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public static String to_json(Object m) {
    // return JSON.toJSONString(m);
    return JSONValue.toJSONString(m);
}
 
Example 17
Source File: JStormUtils.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public static String mergeIntoJson(Map into, Map newMap) {
    Map res = new HashMap(into);
    if (newMap != null)
        res.putAll(newMap);
    return JSONValue.toJSONString(res);
}
 
Example 18
Source File: JsonSimpleConfigParser.java    From java-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public String toJson(Object src) {
    return JSONValue.toJSONString(src);
}