Example usage for org.json.simple JSONObject toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.bloomberglp.blpapi.securitysearch.SecuritySearchApiConnection.java

private void parseRequest(JSONObject request) {
    System.out.println("req" + request.toJSONString());
    if (!request.containsKey("request")) {
        //spit error
        return;/*from ww  w  .j a va  2  s. co m*/
    }

    JSONObject params = (JSONObject) request.get("request");

    if (params.containsKey("query_string")) {
        String queryString = (String) params.get("query_string");
        if (!queryString.isEmpty()) {
            d_queryString = queryString;
        }
    }

    if (params.containsKey("max_results")) {
        long maxResults = (long) params.get("max_results");
        if (maxResults > 0 && maxResults < 65535) {
            d_maxResults = (int) maxResults;
        }
    }

    if (params.containsKey("yk_filter")) {
        String ykFilter = (String) params.get("yk_filter");
        if (!ykFilter.isEmpty()) {
            d_ykFilter = ykFilter;
        }
    }

    System.out.println("Params: " + d_queryString);
}

From source file:net.bashtech.geobot.JSONUtil.java

public static String getRace(String channel) {
    String raceID = "";

    Set<String> entrantSet = new HashSet<String>();
    try {// w  w w .  j av  a 2s . c o m
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(BotManager.getRemoteContent("http://api.speedrunslive.com:81/races"));

        JSONObject jsonObject = (JSONObject) obj;
        int count = Integer.parseInt((String) jsonObject.get("count"));
        JSONArray raceList = (JSONArray) jsonObject.get("races");

        for (int i = 0; i < count; i++) {
            JSONObject races = (JSONObject) raceList.get(i);
            String id = (String) races.get("id");

            JSONObject entrants = (JSONObject) races.get("entrants");
            Set<String> entrantNames = entrants.keySet();
            String entrantsString = entrants.toJSONString();
            if (entrantsString.contains(channel)) {
                raceID = id;
                entrantSet.add(channel);
                for (String s : entrantNames) {

                    JSONObject entrant = (JSONObject) entrants.get(s);
                    String entranttwitch = (String) entrant.get("twitch");
                    if (entrantSet.size() < 5) {
                        entrantSet.add(entranttwitch);
                    }

                }
            }

        }
        if (entrantSet.size() > 0) {
            String raceLink = "http://speedrun.tv/race:" + raceID;
            for (String s : entrantSet) {
                raceLink = raceLink + "/" + s;
            }
            return raceLink;
        } else {
            return null;
        }

    } catch (Exception ex) {
        System.out.println("Failed to get races.");
        return null;
    }
}

From source file:de.tobiyas.racesandclasses.chat.channels.container.ChannelSaveContainer.java

@SuppressWarnings("unchecked")
private String parseMapToString(Map<String, Integer> map) {
    JSONObject tempObject = new JSONObject();
    for (Entry<String, Integer> player : map.entrySet()) {
        tempObject.put(player.getKey(), player.getValue());
    }/*from  w ww  . ja va2 s. co m*/

    return tempObject.toJSONString();
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

@Override
public JSONObject sendLowPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;// w ww  .  j a v  a 2 s .co  m
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyLowPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelLowPriority.basicPublish("", requestLowPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerLowPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

@Override
public JSONObject sendHighPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;/*from   ww w .ja  v  a2s  .c om*/
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyHighPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelHighPriority.basicPublish("", requestHighPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerHighPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}

From source file:bhl.pages.database.MongoConnection.java

/**
 * Make a subset of the documents by a given subkey and value, 
 * then retrieve all the values of the field
 * @param collection the collection to search
 * @param subKey the subKey to make the initial choice
 * @param subValue the value of the subKey to search for
 * @param fields the field names to retrieve
 * @return and array of field values as JSON object strings
 * @throws DbException // w  w w . j  a  va 2  s  .co  m
 */
@Override
public String[] listCollectionBySubKey(String collection, String subKey, String subValue, String[] fields)
        throws DbException {
    try {
        connect();
        DBCollection coll = getCollectionFromName(collection);
        DBObject query = new BasicDBObject(subKey, subValue);
        BasicDBObject keys = new BasicDBObject();
        for (int i = 0; i < fields.length; i++)
            keys.put(fields[i], 1);
        DBCursor cursor = coll.find(query, keys);
        if (cursor.length() > 0) {
            String[] array = new String[cursor.length()];
            Iterator iter = cursor.iterator();
            int i = 0;
            while (iter.hasNext()) {
                DBObject bson = (DBObject) iter.next();
                JSONObject jobj = new JSONObject();
                for (int j = 0; j < fields.length; j++)
                    jobj.put(fields[j], bson.get(fields[j]));
                array[i++] = jobj.toJSONString();
            }
            return array;
        } else
            return new String[0];
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:com.conwet.silbops.model.ConstraintTest.java

@Test
@SuppressWarnings("unchecked")
public void shouldJSONise() {

    // Exist constraint
    JSONObject json = new JSONObject();
    json.put(EXISTS.toJSON(), "");

    assertThat(Constraint.EXIST.toJSON()).isEqualTo(json);
    assertThat(Constraint.EXIST.toJSONString()).isEqualTo(json.toJSONString());

    // verify Exist constraint is instantiated only once
    assertThat(Constraint.fromJSON(json)).isSameAs(Constraint.EXIST);

    // all others
    EnumSet<Operator> remaining = EnumSet.allOf(Operator.class);
    remaining.remove(EXISTS);//w  w  w.  ja  v  a2 s  .com

    for (Operator operator : remaining) {

        json = new JSONObject();
        json.put(operator.toJSON(), oneString.toJSON());

        Constraint cons = new Constraint(operator, oneString);
        assertThat(cons.toJSON()).isEqualTo(json);
        assertThat(cons.toJSONString()).isEqualTo(json.toJSONString());
        assertThat(Constraint.fromJSON(json)).isEqualTo(cons);
    }
}

From source file:com.happyblueduck.lembas.datastore.LembasEntity.java

private void writeObject(java.io.ObjectOutputStream out) throws IOException {

    try {/*  w ww . j  a va 2 s.  co m*/
        org.json.simple.JSONObject result = LembasUtil.serialize(this, false);
        String jsonString = result.toJSONString();
        out.write(jsonString.getBytes());
        //logger.info("> serializing"+ this.getClassName() +":"+ jsonString);
    } catch (UtilSerializeException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        throw new IOException();

    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static boolean setVar(String channel, String varName, String newValue) {
    JSONObject postData = new JSONObject();
    postData.put("value", newValue);
    try {//from  w  w w .  j a v  a2s . c o m

        JSONParser parser = new JSONParser();
        String resp = BotManager.postCoebotVars(postData.toJSONString(),
                "http://coebot.tv/api/v1/vars/set/" + varName + "/" + channel);
        if (!resp.equals("")) {
            Object obj = parser.parse(resp);

            JSONObject jsonObject = (JSONObject) obj;

            String status = (String) (jsonObject.get("status"));
            return status.equals("ok");

        } else
            return false;

    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskIdsByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/LOOP-T2-1");
    JSONObject jsonObject = toJsonObject(response);
    JSONArray taskIds = (JSONArray) jsonObject.get("list");

    System.out.println(jsonObject.toJSONString());
    assertTrue(taskIds.contains("T1#1"));
    assertTrue(taskIds.contains("Print1#1"));
    assertTrue(taskIds.contains("Print2#1"));
    assertTrue(taskIds.contains("T2#1"));
    assertEquals("4", jsonObject.get("size").toString());
}