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.chromium.sdk.internal.v8native.value.ValueMirror.java

/**
 * Tries to construct the full {@link ValueMirror} from V8 debugger display data (preview)
 * if it's possible./*from ww  w  .ja  va 2 s  . co m*/
 */
public static ValueMirror createIfSure(final RefWithDisplayData refWithDisplayData) {
    long ref = refWithDisplayData.ref();
    final Type type = V8Helper.calculateType(refWithDisplayData.type(), refWithDisplayData.className(), false);

    if (!TYPES_WITH_ACCURATE_DISPLAY.contains(type)) {
        return null;
    }

    return new ValueMirror(ref) {
        @Override
        public Type getType() {
            return type;
        }

        @Override
        public String getClassName() {
            return refWithDisplayData.className();
        }

        @Override
        public LoadableString getStringValue() {
            // try another format
            Object valueObj = refWithDisplayData.value();
            String valueStr;
            if (valueObj == null) {
                valueStr = refWithDisplayData.type(); // e.g. "undefined"
            } else {
                // Works poorly for strings, but we do not allow strings here.
                valueStr = JSONValue.toJSONString(valueObj);
                if (type == Type.TYPE_NUMBER && valueStr.lastIndexOf('E') != -1) {
                    // Make accurate rendering of what V8 does.
                    valueStr = valueStr.toLowerCase();
                }
            }
            return new LoadableString.Immutable(valueStr);
        }

        @Override
        public boolean hasProperties() {
            return false;
        }

        @Override
        public SubpropertiesMirror getProperties() {
            return null;
        }
    };
}

From source file:org.codice.ddf.status.CpuService.java

static String toJSON() {
    return JSONValue.toJSONString(getCpuStatus());
}

From source file:org.codice.ddf.status.DiskService.java

static String toJSON() {
    return JSONValue.toJSONString(getDiskStatus());
}

From source file:org.codice.ddf.status.MemoryService.java

static String toJSON() {
    return JSONValue.toJSONString(getMemoryStatus());
}

From source file:org.codice.ddf.status.Status.java

static String toJSON() {
    Map<String, Object> obj = new LinkedHashMap<String, Object>();
    try {//w w w.  ja  v a2s  .c om
        obj.put("hostname", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        obj.put("hostname", "unresolved");
    }
    try {
        obj.put("ip", InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException e) {
        obj.put("ip", "unresolved");
    }
    obj.put("cpu", CpuService.getCpuStatus());
    obj.put("disk", DiskService.getDiskStatus());
    obj.put("mem", MemoryService.getMemoryStatus());
    obj.put("jvm", JvmService.getJvmStatus());
    return JSONValue.toJSONString(obj);
}

From source file:org.countandra.utils.CountandraUtils.java

public static String runQuery(String category, String subTree, String timeDimension, String timePeriod,
        String countType) throws CountandraException {

    TimeDimension td = hshReverseSupportedTimeDimensions.get(timeDimension);
    if (td != null) {

        CountandraUtils cu = new CountandraUtils();
        ResultStatus result = cu.executeQuery(category, subTree, td.getSCode(), timePeriod, "Pacific",
                countType);/*from  w  ww. j  av  a  2 s .  c  o m*/

        if (result instanceof QueryResult) {

            Map<String, Object> classificationMap = new LinkedHashMap<String, Object>();
            classificationMap.put("Category", category);
            classificationMap.put("SubTree", subTree);
            classificationMap.put("Time Dimension", timeDimension);
            classificationMap.put("Time Period", timePeriod);

            Map<Object, Long> dataMap = new LinkedHashMap<Object, Long>();
            QueryResult<?> qr = (QueryResult) result;
            if (qr.get() instanceof CounterSlice) {
                List<HCounterColumn<DynamicComposite>> lCols = ((CounterSlice) qr.get()).getColumns();
                for (int i = 0; i < lCols.size(); i++) {
                    me.prettyprint.cassandra.model.HCounterColumnImpl hcc = (me.prettyprint.cassandra.model.HCounterColumnImpl) lCols
                            .get(i);
                    DynamicComposite nameHcc = (DynamicComposite) hcc.getName();
                    dataMap.put(hcc.getName(), hcc.getValue());
                }
            }
            classificationMap.put("Data", dataMap);

            Map resultMap = new LinkedHashMap();
            resultMap.put("Results", classificationMap);
            return JSONValue.toJSONString(resultMap);

        } else {
            throw new CountandraException(CountandraException.Reason.UNKNOWNERROR);
        }
    } else {
        throw new CountandraException(CountandraException.Reason.TIMEDIMENSIONNOTSUPPORTED);
    }
}

From source file:org.cru.godtools.api.notifications.Sender.java

/**
 * Sends a message without retrying in case of service unavailability. See
 * {@link #send(Message, List, int)} for more info.
 *
 * @return multicast results if the message was sent successfully,
 * {@literal null} if it failed but could be retried.
 * @throws IllegalArgumentException if registrationIds is {@literal null} or
 *                                  empty.
 * @throws InvalidRequestException  if GCM didn't returned a 200 status.
 * @throws IOException              if there was a JSON parsing error
 *//*from  w ww. j  a va2  s. c o  m*/
public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException {
    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }
    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
    setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
    jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }
    String requestBody = JSONValue.toJSONString(jsonRequest);
    log.info("JSON request: " + requestBody);
    HttpURLConnection conn;
    int status;
    try {
        conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
        status = conn.getResponseCode();
    } catch (IOException e) {
        log.info("IOException posting to GCM", e);
        return null;
    }
    String responseBody;
    if (status != 200) {
        try {
            responseBody = getAndClose(conn.getErrorStream());
            log.info("JSON error response: " + responseBody);
        } catch (IOException e) {
            // ignore the exception since it will thrown an InvalidRequestException
            // anyways
            responseBody = "N/A";
            log.info("Exception reading response: ", e);
        }
        throw new InvalidRequestException(status, responseBody);
    }
    try {
        responseBody = getAndClose(conn.getInputStream());
    } catch (IOException e) {
        log.warn("IOException reading response", e);
        return null;
    }
    log.info("JSON response: " + responseBody);
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse;
    try {
        jsonResponse = (JSONObject) parser.parse(responseBody);
        int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
        if (results != null) {
            for (Map<String, Object> jsonResult : results) {
                String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
                String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
                String error = (String) jsonResult.get(JSON_ERROR);
                Result result = new Result.Builder().messageId(messageId)
                        .canonicalRegistrationId(canonicalRegId).errorCode(error).build();
                builder.addResult(result);
            }
        }
        MulticastResult multicastResult = builder.build();
        return multicastResult;
    } catch (ParseException e) {
        throw newIoException(responseBody, e);
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:org.daxplore.producer.daxplorelib.raw.RawMeta.java

protected static String categoriesToJSON(Map<String, SPSSVariableCategory> categories) {
    Set<String> keyset = categories.keySet();
    Map<Object, String> catObj = new LinkedHashMap<>();
    for (String key : keyset) {
        //if(categories.get(key).value != Double.NaN){
        //   catObj.put(new Double(categories.get(key).value), categories.get(key).label);
        //} else {
        catObj.put(categories.get(key).strValue, categories.get(key).label);
        //}//w  w w .  j ava 2 s  .c om
    }
    return JSONValue.toJSONString(catObj);
}

From source file:org.dia.kafka.labkey.producer.LabkeyKafkaProducer.java

/**
 * Generates a JSON object from a study/*from ww w .j  av a 2 s .co m*/
 * @param study
 * @return
 */
public JSONObject generateStudyJSON(Map<String, Object> study) {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put(Constants.SOURCE_TAG, LABKEY_SOURCE_VAL);
    String[] keySet = study.keySet().toArray(new String[] {});
    for (int j = 0; j < keySet.length; j++) {
        String key = keySet[j];
        Object val = StringEscapeUtils.escapeJson(String.valueOf(study.get(keySet[j])));
        if (key.equals("Container")) {
            key = "id";
        } else if (key.equals("Description")) {
            key = "Study_Description";
        } else if (key.equals("_labkeyurl_Container")) {
            key = "Labkeyurl_Container";
        } else if (key.equals("_labkeyurl_Label")) {
            key = "Labkeyurl_Label";
        } else if (key.equals("Grant")) {
            key = "Study_Grant_Number";
        } else if (key.equals("Investigator")) {
            val = JSONValue.toJSONString(Lists
                    .newArrayList(StringUtils.split(val.toString().replace(" ", "").replace(",", "-"), ";"))
                    .toString());
        } else {
            key = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(key), "_");
        }
        jsonObj.put(key, val);
    }
    return jsonObj;
}

From source file:org.eclairjs.nashorn.Utils.java

public static Object jsToJava(Object o) {
    if (o != null && !(o instanceof Undefined)) {
        logger.debug("jsToJava" + o.getClass().getName());
    } else {//from   w  w  w  .j a  va 2 s .  c  o m
        return o;
    }
    if (o instanceof jdk.nashorn.internal.objects.NativeArray) {
        Object array[] = ((NativeArray) o).asObjectArray();
        ArrayList al = new ArrayList();
        for (int i = 0; i < array.length; i++) {
            al.add(jsToJava(array[i]));
        }
        return al.toArray();
    }
    if (o.getClass().isPrimitive())
        return o;

    String packageName = o.getClass().getCanonicalName();

    switch (packageName) {
    case "java.lang.String":
    case "java.lang.Integer":
    case "java.lang.Float":
    case "java.lang.Double":
    case "java.lang.Boolean":
    case "java.lang.Long":
    case "org.json.simple.JSONObject":
    case "java.lang.Object[]":
    case "java.lang.String[]":
    case "scala.Tuple2":
    case "scala.Tuple3":
    case "scala.Tuple4":
        return o;
    }
    if (packageName.startsWith("org.apache.spark"))
        return o;

    if (o instanceof WrappedClass)
        return ((WrappedClass) o).getJavaObject();

    if (o instanceof ScriptObjectMirror) {
        ScriptObjectMirror m = (ScriptObjectMirror) o;
        if (m.hasMember("getJavaObject")) {
            return m.callMember("getJavaObject");
        }
        if (m.isArray()) {
            try {
                if (m.containsKey("0")) {
                    Object v = m.get("0");
                    if (v instanceof Double) {
                        double[] doubleArray = (double[]) ScriptUtils.convert(m, double[].class);
                        return doubleArray;
                    } else if (v instanceof Integer) {
                        int[] intArray = (int[]) ScriptUtils.convert(m, int[].class);
                        return intArray;
                    } else {
                        Object[] objectArray = (Object[]) ScriptUtils.convert(m, Object[].class);
                        return objectArray;
                    }
                }
            } catch (ClassCastException e) {
                /*
                If the array contains ScriptObjectMirror the above conversions throws exception
                so we have to convert the contents of the array as well.
                 */
                ArrayList list = new ArrayList();
                for (Object item : m.values()) {
                    list.add(jsToJava(item));
                }
                Object x = list.toArray();
                return x;
            }

        } else {
            //               throw new RuntimeException("js2java IMPLEMENT"+o);
            Object obj = ScriptObjectMirror.wrapAsJSONCompatible(o, null);
            String j = JSONValue.toJSONString(obj);
            return JSONValue.parse(j);
        }
    } else if (o instanceof jdk.nashorn.internal.runtime.ScriptObject) {
        ScriptObjectMirror jsObj = ScriptUtils.wrap((jdk.nashorn.internal.runtime.ScriptObject) o);
        if (jsObj.hasMember("getJavaObject")) {
            return jsObj.callMember("getJavaObject");
        }
    } else if (o instanceof java.util.ArrayList) {

        ArrayList list = (ArrayList) o;
        int size = list.size();
        for (int i = 0; i < size; i++)
            list.set(i, jsToJava(list.get(i)));
        return list;
    } else if (o instanceof StaticClass) {
        return o;
    }
    logger.warn("js2java NOT HANDLED " + packageName);
    return o; // Just return the Java object, it might user created like java.net.Socket
    //new RuntimeException().printStackTrace();
    //throw new RuntimeException("js2java NOT HANDLED "+packageName);

}