Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:fr.bmartel.bboxapi.BboxApi.java

/**
 * Voip data/*from   ww w.  j a  v a  2 s .c om*/
 * 
 * @param voipDataListener
 *            listener called when voip data result has been received
 * @return true if request has been successfully initiated
 */
@Override
public boolean voipData(final IVoipDataListener voipDataListener) {

    ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80);

    clientSocket.addClientSocketEventListener(new IHttpClientListener() {

        @Override
        public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) {

            if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) {

                // this is data coming from the server
                if (frame.getStatusCode() == 200) {

                    String data = new String(frame.getBody().getBytes());

                    JSONArray obj = (JSONArray) JSONValue.parse(data);

                    if (obj.size() > 0) {

                        JSONObject item = (JSONObject) obj.get(0);
                        if (item.containsKey("voip")) {

                            JSONArray sub_item = (JSONArray) item.get("voip");
                            if (sub_item.size() > 0) {

                                JSONObject sub_item_first_element = (JSONObject) sub_item.get(0);

                                if (sub_item_first_element.containsKey("id")
                                        && sub_item_first_element.containsKey("status")
                                        && sub_item_first_element.containsKey("callstate")
                                        && sub_item_first_element.containsKey("uri")
                                        && sub_item_first_element.containsKey("blockstate")
                                        && sub_item_first_element.containsKey("anoncallstate")
                                        && sub_item_first_element.containsKey("mwi")
                                        && sub_item_first_element.containsKey("message_count")
                                        && sub_item_first_element.containsKey("notanswered")) {

                                    int id = Integer.parseInt(sub_item_first_element.get("id").toString());
                                    String status = sub_item_first_element.get("status").toString();
                                    String callState = sub_item_first_element.get("callstate").toString();
                                    String uri = sub_item_first_element.get("uri").toString();
                                    int blockState = Integer
                                            .parseInt(sub_item_first_element.get("blockstate").toString());
                                    int anoncallState = Integer
                                            .parseInt(sub_item_first_element.get("anoncallstate").toString());
                                    int mwi = Integer.parseInt(sub_item_first_element.get("mwi").toString());
                                    int messageCount = Integer
                                            .parseInt(sub_item_first_element.get("message_count").toString());
                                    int notanswered = Integer
                                            .parseInt(sub_item_first_element.get("notanswered").toString());

                                    Voip voip = new Voip(id, status, CallState.getValue(callState), uri,
                                            blockState, anoncallState, mwi, messageCount, notanswered);

                                    voipDataListener.onVoipDataReceived(voip);
                                    clientSocket.closeSocket();
                                    return;
                                }
                            }
                        }
                    }
                }
                voipDataListener.onVoipDataFailure();
                clientSocket.closeSocket();
            }
        }

        @Override
        public void onSocketError() {

            voipDataListener.onVoipDataFailure();
        }
    });

    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("Accept", "*/*");
    headers.put("Host", "gestionbbox.lan");
    headers.put("Cookie", token_header);
    HttpFrame frameRequest = new HttpFrame(HttpMethod.GET_REQUEST, new HttpVersion(1, 1), headers,
            "/api/v1/voip", new ListOfBytes(""));

    clientSocket.write(frameRequest.toString().getBytes());

    return false;
}

From source file:eu.hansolo.accs.RestClient.java

private JSONArray getAll(final DbCollection COLLECTION) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("api.mlab.com").setPort(80).setPath(COLLECTION.REST_URL)
                .setParameter("apiKey", MLAB_API_KEY);
        HttpGet get = new HttpGet(builder.build());
        get.setHeader("accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
            return new JSONArray();
        }/*from  w w  w  .  j a  v  a  2 s. com*/

        String output = getFromResponse(response);
        JSONArray jsonArray = (JSONArray) JSONValue.parse(output);
        return jsonArray;
    } catch (URISyntaxException | IOException e) {
        return new JSONArray();
    }
}

From source file:mml.handler.get.MMLGetHandler.java

/**
 * Try to retrieve the CorTex/CorCode version specified by the path
 * @param db the database to fetch from//  ww w .j  ava 2 s  .  com
 * @param docID the document ID
 * @param vPath the groups/version path to get
 * @return the CorTex/CorCode version contents or null if not found
 * @throws MMLException if the resource couldn't be found for some reason
 */
protected EcdosisVersion doGetResourceVersion(String db, String docID, String vPath) throws MMLException {
    EcdosisVersion version = new EcdosisVersion();
    JSONObject doc = null;
    JSONObject md = null;
    char[] data = null;
    String res = null;
    String metadata;
    //System.out.println("fetching version "+vPath );
    try {
        res = Connector.getConnection().getFromDb(db, docID);
        metadata = Connector.getConnection().getFromDb(Database.METADATA, docID);
    } catch (Exception e) {
        throw new MMLException(e);
    }
    if (res != null)
        doc = (JSONObject) JSONValue.parse(res);
    if (metadata != null)
        md = (JSONObject) JSONValue.parse(metadata);
    if (doc != null) {
        String format = (String) doc.get(JSONKeys.FORMAT);
        if (format == null)
            throw new MMLException("doc missing format");
        version.setFormat(format);
        // first resolve the link, if any
        if (version.getFormat().equals(Formats.MVD)) {
            MVD mvd = MVDFile.internalise((String) doc.get(JSONKeys.BODY));
            //vPath = getBestString(JSONKeys.VERSION1,md,doc);
            version.setStyle(getBestString(JSONKeys.STYLE, md, doc));
            String sName = Utils.getShortName(vPath);
            String gName = Utils.getGroupName(vPath);
            int vId = mvd.getVersionByNameAndGroup(sName, gName);
            version.setMVD(mvd);
            if (vId != 0) {
                data = mvd.getVersion(vId);
                // String desc = mvd.getDescription();
                //System.out.println("description="+desc);
                //int nversions = mvd.numVersions();
                //System.out.println("nversions="+nversions);
                //System.out.println("length of version "+vId+"="+data.length);
                if (data != null)
                    version.setVersion(data);
                else
                    throw new MMLException("Version " + vPath + " not found");
            } else
                throw new MMLException("Version " + vPath + " not found");
        } else {
            String body = (String) doc.get(JSONKeys.BODY);
            version.setStyle(getBestString(JSONKeys.STYLE, md, doc));
            //                version.setDescription(getBestString(JSONKeys.TITLE,md,doc)+" "
            //                    +getBestString(JSONKeys.SECTION,md,doc));
            //                version.setVersion1(getBestString(JSONKeys.VERSION1,md,doc));
            if (body == null)
                throw new MMLException("empty body");
            try {
                data = body.toCharArray();
            } catch (Exception e) {
                throw new MMLException(e);
            }
            version.setVersion(data);
        }
    }
    return version;
}

From source file:de.dailab.plistacontest.client.ContestHandlerOfflineCheating.java

/**
 * Method to handle incoming messages from the server.
 * //from ww  w . j  a v  a 2  s .c  o m
 * @param messageType
 *                the messageType of the incoming contest server message.
 * @param properties
 *                
 * @param entities
 * @return the response to the contest server
 */
@SuppressWarnings("unchecked")
private String handleIdomaarMessage(final String messageType, final String properties, final String entities) {
    // write all data from the server to a file
    // logger.info(messageType + "\t" + properties + "\t" + entities);

    // create an jSON object from the String
    final JSONObject jOP = (JSONObject) JSONValue.parse(properties);
    final JSONObject jOE = (JSONObject) JSONValue.parse(entities);

    // merge the different jsonObjects and correct missing itemIDs
    jOP.putAll(jOE);
    Object itemID = jOP.get("itemID");
    if (itemID == null) {
        jOP.put("itemID", 0);
    }

    // define a response object
    String response = null;

    if ("impression".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString());
        final String eventNotificationType = messageType;

        // impression refers to articles read by the user
        if ("impression".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {

                response = "handle impression eventNotification successful";

                boolean recommendationExpected = false;
                if (properties.contains("\"event_type\": \"recommendation_request\"")) {
                    recommendationExpected = true;
                }
                if (recommendationExpected) {
                    List<Long> suggestedItemIDs = recommenderItemTable.getFutureItems(item.getTimeStamp(),
                            item.getDomainID(), item.getUserID());
                    response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}";
                }

            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {

                response = "handle impression eventNotification successful";
            }
            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString());

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jOP.toString() + jOE.toJSONString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:ch.simas.jtoggl.JToggl.java

/**
 * Get running time entry//from  ww  w  . j a va 2s  .  co m
 * 
 * @return The running time entry or null if none
 */
public TimeEntry getCurrentTimeEntry() {
    Client client = prepareClient();
    WebResource webResource = client.resource(CURRENT_TIME_ENTRY);

    String response = null;
    try {
        response = webResource.get(String.class);
    } catch (UniformInterfaceException uniformInterfaceException) {
        return null;
    }

    JSONObject object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    if (data == null)
        return null;

    return new TimeEntry(data.toJSONString());
}

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

public void setLembasField(Field f, Object value) throws IllegalAccessException {
    JSONObject jsonObject = (JSONObject) JSONValue.parse((String) value);
    try {//from   w  ww.  j  a  v  a  2s  .c om
        LembasEntity obj = (LembasEntity) LembasUtil.deserialize(jsonObject);
        f.set(this, obj);
    } catch (UtilSerializeException e) {
        e.printStackTrace();
    }
}

From source file:coria2015.server.JsonRPCMethods.java

public void handle(String message) {
        JSONObject object;/*from  www  .jav  a2 s  .c o m*/
        try {
            Object parse = JSONValue.parse(message);
            object = (JSONObject) parse;

        } catch (Throwable t) {
            LOGGER.warning("Error while handling JSON request");

            try {
                mos.error(null, 1, "Could not parse JSON: " + t.getMessage());
            } catch (IOException e) {
                LOGGER.warning("Could not send the error message");
            }
            return;
        }

        handleJSON(object);
    }

From source file:mml.handler.scratch.ScratchVersion.java

/**
 * Convert a BSON object to a Scratch version internal format
 * @param json the bson object from the database
 * @return a ScratchVersion with layers//from   www .j a va  2s .c om
 */
public static ScratchVersion fromJSON(String json) {
    JSONObject jObj = (JSONObject) JSONValue.parse(json);
    boolean dirty = ((Boolean) jObj.get("dirty") != null) ? ((Boolean) jObj.get("dirty")) : false;
    Date saveTime = toDate((String) jObj.get(JSONKeys.TIME));
    String longName = (String) jObj.get(JSONKeys.LONGNAME);
    ScratchVersion sv = new ScratchVersion((String) jObj.get(JSONKeys.VERSION1), longName,
            (String) jObj.get(JSONKeys.DOCID), (String) jObj.get(JSONKeys.DBASE), saveTime, dirty);
    JSONArray jArr = (JSONArray) jObj.get("layers");
    if (jArr != null) {
        for (int i = 0; i < jArr.size(); i++) {
            JSONObject jLayer = (JSONObject) jArr.get(i);
            String layerName = (String) jLayer.get(JSONKeys.NAME);
            String body = (String) jLayer.get(JSONKeys.BODY);
            int layerNum = layerNumber(layerName);
            sv.addLayer(body.toCharArray(), layerNum);
        }
    }
    return sv;
}

From source file:com.mobicage.rogerthat.registration.RegistrationWizard2.java

@SuppressWarnings("unchecked")
@Override/*from ww  w  .ja v a 2  s  .  c  o  m*/
public void readFromPickle(int version, DataInput in) throws IOException, PickleException {
    T.UI();
    super.readFromPickle(version, in);
    boolean set = in.readBoolean();
    if (set)
        mCredentials = new Credentials(new Pickle(in.readInt(), in));
    set = in.readBoolean();
    mEmail = set ? in.readUTF() : null;
    mTimestamp = in.readLong();
    mRegistrationId = in.readUTF();
    mInGoogleAuthenticationProcess = in.readBoolean();
    mInstallationId = in.readUTF();
    // A version bump was forgotten when serializing mDeviceId, so we need a try/catch
    try {
        mDeviceId = in.readUTF();
    } catch (EOFException e) {
        mDeviceId = null;
    }
    if (version >= 2) {
        try {
            set = in.readBoolean();
            mBeaconRegions = set
                    ? new GetBeaconRegionsResponseTO((Map<String, Object>) JSONValue.parse(in.readUTF()))
                    : null;

            set = in.readBoolean();
            if (set) {
                String detectedBeacons = in.readUTF();
                JSONArray db1 = (JSONArray) JSONValue.parse(detectedBeacons);
                if (db1 != null) {
                    mDetectedBeacons = new HashSet<String>();
                    for (int i = 0; i < db1.size(); i++) {
                        mDetectedBeacons.add((String) db1.get(i));
                    }
                } else {
                    mDetectedBeacons = null;
                }
            } else {
                mDetectedBeacons = null;
            }
        } catch (IncompleteMessageException e) {
            L.bug(e);
        }
    }
}

From source file:com.jgoetsch.eventtrader.test.ProfidingMsgParserTest.java

@SuppressWarnings("rawtypes")
public void testPartialExit() throws Exception {
    msgParser.parseData("alert", (Map) JSONValue.parse(
            "{\"partial_entry\":{\"exitPrice\":null,\"dateAdded\":1344346779000,\"newsletterIds\":[3,26,2,24],\"type\":\"Short Stock\",\"dateClosed\":null,\"amount\":null,\"username\":\"timothysykes\",\"compareDate\":1344346779000,\"ticker\":\"CRMB\",\"action\":\"Shorted\",\"entryPrice\":3.1,\"shortSell\":true,\"shortUrl\":\"1Mn25g\",\"optionType\":\"CALL\",\"callOption\":true,\"entryComments\":\"Spiked waaaay too much on low volume so I shorted some, shares available at IB and SureTrader\",\"percentage\":null,\"optionExpiration\":null,\"entryDate\":1344346779000,\"futuresMonth\":0,\"futuresYear\":0,\"shares\":300,\"entryType\":\"STOCK\",\"exitDate\":null,\"optionStrike\":null,\"comments\":null,\"openTrade\":true},\"msgId\":27997,\"image\":\"http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg\",\"partial\":{\"shares\":1400,\"short\":true,\"tradeDate\":1344347770227,\"transactionType\":\"Covered\",\"price\":3.02,\"adding\":false}}"),
            new MsgHandler() {
                public boolean newMsg(Msg msg) {
                    Assert.assertEquals(TradeSignal.class, msg.getClass());
                    TradeSignal trade = (TradeSignal) msg;
                    Assert.assertEquals("timothysykes", trade.getSourceName());
                    Assert.assertEquals("http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg",
                            trade.getImageUrl());
                    Assert.assertEquals(1344347770227L, trade.getDate().toDate().getTime());
                    Assert.assertEquals(TradeSignal.TYPE_COVER, trade.getType());
                    Assert.assertEquals(Contract.stock("CRMB"), trade.getContract());
                    Assert.assertEquals(1400, trade.getNumShares());
                    Assert.assertEquals(3.02, trade.getPrice());
                    return false;
                }/*from  ww  w  . j a v a 2  s .c om*/
            });
}