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:mensajes.SmackCcsClient.java

/**
 * Creates a JSON encoded ACK message for an upstream message received
 * from an application./*w  w w  .  j  a va  2 s. c  o m*/
 *
 * @param to RegistrationId of the device who sent the upstream message.
 * @param messageId messageId of the upstream message to be acknowledged to CCS.
 * @return JSON encoded ack.
 */
protected static String createJsonAck(String to, String messageId) {
    Map<String, Object> message = new HashMap<String, Object>();
    message.put("message_type", "ack");
    message.put("to", to);
    message.put("message_id", messageId);
    return JSONValue.toJSONString(message);
}

From source file:com.apexxs.neonblack.dao.FinalLocation.java

public String toJson() {
    Map<String, Object> detectionMap = new LinkedHashMap<>();
    List<Object> alternateList = new LinkedList<>();
    try {//from   www .j  a  v  a2  s  .com
        detectionMap.put("Detection", this.name);
        detectionMap.put("Gazetteer name", this.topCandidate.name);
        detectionMap.put("LonLat", this.topCandidate.lonLat);
        detectionMap.put("Country", this.topCandidate.countryCode);
        detectionMap.put("Feature code", this.topCandidate.featureCode);
        detectionMap.put("Admin1", this.topCandidate.admin1);
        detectionMap.put("Admin2", this.topCandidate.admin2);
        detectionMap.put("Num Occurrences", this.startPositions.size());

        if (this.geoNamesEntries.size() > 1) {
            Integer minimum = 0;
            String altLabel = StringUtils.EMPTY;

            if (StringUtils.equals(this.detectedBy, "NER")) {
                if (geoNamesEntries.size() > 1) {
                    minimum = Math.min(geoNamesEntries.size(), config.getNumAlternates());
                }
                altLabel = "Alternates";
            } else if (StringUtils.equals(this.detectedBy, "RGX")) {
                minimum = Math.min(config.getNumProximalHits(), geoNamesEntries.size());
                altLabel = "Within " + config.getProximalDistance() + " Km";
            }
            for (int i = 0; i < minimum; i++) {
                Map<String, String> alternateMap = new LinkedHashMap<>();
                GeoNamesEntry entry = this.geoNamesEntries.get(i);
                alternateMap.put("Name", entry.name);
                alternateMap.put("LonLat", entry.lonLat);
                alternateMap.put("Country", entry.countryCode);
                alternateMap.put("Feature code", entry.featureCode);
                alternateMap.put("Admin1", entry.admin1);
                alternateMap.put("Admin2", entry.admin2);
                alternateList.add(alternateMap);
            }
            detectionMap.put(altLabel, alternateList);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return JSONValue.toJSONString(detectionMap);
}

From source file:de.instantouch.model.io.SnakeJSONWriter.java

private String createValueString(Object obj) throws SnakeWrongTypeException, SnakeNotInitializedException {
    String jsonString = null;/* w ww. ja  v a 2s.  c  om*/

    if (obj instanceof SnakeType) {
        SnakeType type = (SnakeType) obj;

        if (type instanceof SnakeDate) {
            jsonString = JSONValue.toJSONString(type.toString());
        } else if (!type.handleAsBasic()) {
            throw new SnakeWrongTypeException("not supported type: " + type.getClass().getName());
        } else if (type instanceof SnakeBoolean) {
            jsonString = JSONValue.toJSONString(type.toString());
        } else if (type instanceof SnakeInteger) {
            jsonString = JSONValue.toJSONString(type.toString());
        } else if (type instanceof SnakeLong) {
            jsonString = JSONValue.toJSONString(type.toString());
        } else if (type instanceof SnakeDouble) {
            jsonString = JSONValue.toJSONString(type.toString());
        } else if (type instanceof SnakeString) {
            jsonString = JSONValue.toJSONString(type.toString());
        }
    } else {
        jsonString = JSONValue.toJSONString(obj);
    }

    return jsonString;
}

From source file:au.org.paperminer.main.LocationFilter.java

/**
 * Returns JSON struct for a specific location id, or blank.
 * @param req/*from   w  w  w  .ja  v  a  2s  .c o m*/
 * @param resp
 */
private void getGSDetails(HttpServletRequest req, HttpServletResponse resp) {
    HashMap<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();
    try {
        String arg = req.getParameter("lst");
        if ((arg != null) && (arg.length() > 0)) {
            String[] ids = arg.split(",");
            m_logger.debug("locationFilter getGSDetails: " + arg + " length:" + ids.length);
            for (int i = 0; i < ids.length; i++) {
                HashMap<String, String> tmp = m_helper.getLocationInfo(ids[i]);
                map.put(ids[i], tmp);
                m_logger.debug("  getGSDetails fetched: " + tmp.get("name") + " (" + ids[i] + ")");
            }
        }
        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        String jsonStr = "";
        if (map.size() > 0) {
            jsonStr = "{\"locns\":" + JSONValue.toJSONString(map) + "}";
        }
        pm.write(jsonStr);
        pm.close();
    } catch (PaperMinerException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e302");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:com.opengamma.web.WebResourceTestUtils.java

@SuppressWarnings("rawtypes")
public static void assertJSONObjectEquals(final JSONObject expectedJson, final JSONObject actualJson)
        throws Exception {
    assertNotNull(expectedJson);/*  w w  w .ja  va  2  s  .  c  o  m*/
    assertNotNull(actualJson);
    String expectedSorted = JSONValue
            .toJSONString((Map) new JSONParser().parse(expectedJson.toString(), s_sortedJSONObjectFactory));
    String actualSorted = JSONValue
            .toJSONString((Map) new JSONParser().parse(actualJson.toString(), s_sortedJSONObjectFactory));
    assertEquals(expectedSorted, actualSorted);
}

From source file:com.github.nukesparrow.htmlunit.DebuggingWebConnection.java

public void writeHtml(PrintStream out) {
    int i = TEMPLATE.indexOf(TEMPLATE_MARK);

    if (i == -1) {
        throw new IllegalStateException();
    }//w ww.  j  av  a  2 s.  c  o m

    out.print(TEMPLATE.substring(0, i));

    for (final Object element : events.toArray()) {
        synchronized (element) {
            String content = JSONValue.toJSONString(element);
            String encoding = null;

            String cc = content.toLowerCase();
            if (cc.contains("</script>") || cc.contains("<!--")) {
                encoding = "base64";
                try {
                    content = Base64.encodeBase64String(content.getBytes("UTF-8"));
                } catch (UnsupportedEncodingException ex) {
                    throw new RuntimeException(ex);
                }
            }

            out.append("<script type=\"text/x-event-json\""
                    + (encoding == null ? "" : " encoding=\"" + encoding + "\"") + ">" + content
                    + "</script>\n");
        }
    }

    out.print(TEMPLATE.substring(i + TEMPLATE_MARK.length()));
}

From source file:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }//w w  w  . j  a  v  a  2s  .co m
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:br.com.ulife.googlexmpp.SmackCcsClient.java

/**
 * Creates a JSON encoded ACK message for an upstream message received from
 * an application.//from w w w. j  a  v  a  2  s.  c o  m
 *
 * @param to RegistrationId of the device who sent the upstream message.
 * @param messageId messageId of the upstream message to be acknowledged to
 * CCS.
 * @return JSON encoded ack.
 */
public static String createJsonAck(String to, String messageId) {
    Map message = new HashMap();
    message.put("message_type", "ack");
    message.put("to", to);
    message.put("message_id", messageId);
    return JSONValue.toJSONString(message);
}

From source file:cprasmu.rascam.camera.RazCamServerImpl.java

public synchronized String parseCommand(String jsonData) throws IllegalArgumentException {

    String subject = "";
    String value = "";

    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        public List creatArrayContainer() {
            return new LinkedList();
        }//  w  w  w  . j a  v a 2s  . c  om

        public Map createObjectContainer() {
            return new LinkedHashMap();
        }

    };

    jsonData = jsonData.trim();

    try {
        Map json = (Map) parser.parse(jsonData, containerFactory);
        Iterator iter = json.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            // System.out.println(entry.getKey() + "=>" + entry.getValue());
            if (entry.getKey().equals("subject")) {
                subject = (String) entry.getValue();
            }
            if (entry.getKey().equals("value")) {
                value = (String) entry.getValue();
            }

        }
        System.out.println(JSONValue.toJSONString(json));
    } catch (ParseException pe) {
        throw new IllegalArgumentException("Invalid JSON Data");
    }

    if (subject.equals(JSON_DATA_CAMERA_AWB)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextAwbMode();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousAwbMode();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetAwbMode();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_EFFECT)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextImageEffect();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousImageEffect();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetImageEffect();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_VIDEO_RES)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextVideoResolution();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousVideoResolution();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetVideoResolution();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_STILL_RES)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextStillResolution();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousStillResolution();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetStillResolution();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_EXPOSURE)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextExposureMode();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousExposureMode();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetExposureMode();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_METERING)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextMeteringMode();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousMeteringMode();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetMeteringMode();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_EV)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getEv().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getEv().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetEv();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_BRIGHTNESS)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getBrightness().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getBrightness().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetBrightness();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_SATURATION)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getSaturation().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getSaturation().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetSaturation();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_SHARPNESS)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getSharpness().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getSharpness().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetSharpness();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_CONTRAST)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getContrast().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getContrast().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetContrast();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_HFLIP)) {

        rcm.setHFlip(!rcm.isHFlip());

    } else if (subject.equals(JSON_DATA_CAMERA_VFLIP)) {

        rcm.setVFlip(!rcm.isVFlip());

    } else if (subject.equals(JSON_DATA_CAMERA_VSTAB)) {

        rcm.setVStab(!rcm.isVStab());

    } else if (subject.equals(JSON_DATA_CAMERA_TIMELAPSE_DELAY)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getTimelapseDelay().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getTimelapseDelay().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetTimelapseDelay();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_QUALITY)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getQuality().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getQuality().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetQuality();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_SHUTTER_SPEED)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getShutterSpeed().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getShutterSpeed().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetShutterSpeed();
        } else if (value.equals(CAMERA_CMD_ENABLE)) {
            rcm.enableShutterSpeed();
        } else if (value.equals(CAMERA_CMD_DISABLE)) {
            rcm.disableShutterSpeed();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_ISO)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getIso().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getIso().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetIso();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_ROTATION)) {
        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextRotation();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.nextRotation();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetRotation();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_FPS)) {

        if (value.equals(CAMERA_CMD_PLUS)) {
            rcm.getFps().increment();
        } else if (value.equals(CAMERA_CMD_MINUS)) {
            rcm.getFps().decrement();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetFps();
        }

    } else if (subject.equals(JSON_DATA_CAMERA_MODE)) {

        if (value.equals(CAMERA_CMD_NEXT)) {
            rcm.nextCameraMode();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            rcm.previousCameraMode();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.resetCameraMode();
        }
    } else if (subject.equals(JSON_DATA_DCIM_FILE)) {
        if (value.equals(CAMERA_CMD_NEXT)) {
            //rcm.nextCameraMode();
        } else if (value.equals(CAMERA_CMD_PREVIOUS)) {
            //rcm.previousCameraMode();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            //rcm.resetCameraMode();
        }

    } else if (subject.equals(CAMERA_CMD_STATUS)) {

        if (value.equals(CAMERA_CMD_START)) {
            if (!rcm.isRecording()) {
                if (rcm.getCameraMode().equals(Mode.SINGLE_SHOT.displayName)) {
                    rcm.singleShotPhoto();

                } else if (rcm.getCameraMode().equals(Mode.TIME_LAPSE.displayName)) {
                    rcm.timelapsePhoto();

                } else if (rcm.getCameraMode().equals(Mode.VIDEO.displayName)) {
                    rcm.video();

                } else {
                    // // sendMessage("ERROR:" + subject);
                }
            }
        } else if (value.equals(CAMERA_CMD_STOP)) {
            rcm.stop();
        } else if (value.equals(CAMERA_CMD_RESET)) {
            rcm.reset();

        } else if (value.equals(CAMERA_CMD_SHUTDOWN)) {
            rcm.stop();
            SystemUtilities.shutdownOS();
        } else if (value.equals(CAMERA_CMD_REBOOT)) {
            rcm.stop();
            SystemUtilities.rebootOS();

        } else if (value.equals(CAMERA_CMD_QUIT)) {
            rcm.stop();
            System.exit(0);

        } else if (value.equals("DIRS")) {

            JSONObject result = new JSONObject();
            JSONArray jsonDirs = new JSONArray();
            File[] dirs = DCIMHelper.dcimDirectory.listFiles();

            Arrays.sort(dirs, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
                }
            });

            for (File dir : dirs) {
                if (dir.isDirectory()) {
                    JSONObject folder = new JSONObject();
                    folder.put("Folder", dir.getName());
                    File[] tmp = dir.listFiles();
                    long count = 0;

                    for (File t : tmp) {
                        if (!t.getName().endsWith(".thm")) {
                            count++;
                        }
                    }
                    folder.put("Count", count);
                    jsonDirs.add(folder);
                }
            }

            result.put("dirs", jsonDirs);

            return result.toString();

        } else if (value.equals("FILES")) {
            JSONObject obj = new JSONObject();
            obj.put("fileSystemModel", fsm.toJSON(DCIMHelper.getCurrentDirectory()));
            return obj.toString();
        } else {

        }

    } else if (subject.equals(CAMERA_CMD_DELETE)) {
        if (!DCIMHelper.getCurrentDirectory().equals(DCIMHelper.dcimDirectory + "/" + value)) {
            fsm.delete(DCIMHelper.dcimDirectory + "/" + value);
            System.out.println("DELETED: " + value);
        } else {

        }

    } else if (subject.equals("FOLDER")) {
        JSONObject obj = new JSONObject();
        obj.put("fileSystemModel", fsm.toJSON(DCIMHelper.dcimDirectory + "/" + value));
        return obj.toString();
    }
    return this.toJSON().toString();
}

From source file:de.fhg.fokus.odp.portal.uploaddata.service.Worker.java

/**
 * returns JSONArray from List of Strings.
 * /*from w ww.  j  ava  2  s. c  o m*/
 * @param values
 *            List of strings
 * @return JSONArray
 */
private String buildJSONArray(List<String> values) {
    return JSONValue.toJSONString(values);
}