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:com.plancake.api.client.PlancakeApiClient.java

/**
*
* @param Map<String, String> params
* @param string methodName/*w  w  w.j  a  v  a  2  s  .  c  o  m*/
* @param array $requestOpts (= null) - the options for the HTTP request
* @param String httpMethod ('GET' or 'POST')
* @return stdClass - result of json_decode
*/
private JSONObject sendRequest(Map<String, String> params, String methodName, String httpMethod)
        throws PlancakeApiException, UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        MalformedURLException, IOException {
    if (this.token == "") {
        this.resetToken();
    }

    String request = this.prepareRequest(params, methodName);

    String response = this.getResponse(request, httpMethod);

    // Debug
    //System.out.println("request:  " + request);
    //System.out.println("response:  " + response);

    Object obj = JSONValue.parse(response);
    JSONObject jsonResponse = (JSONObject) obj;

    // checking whether an error occurred
    Object error = jsonResponse.get("error");
    if (error != null) {
        // if the error is an INVALID_TOKEN_ERROR, we try to get the token again
        // (maybe it was just expired)
        if (error.toString().equals(Integer.toString(PlancakeApiClient.INVALID_TOKEN_ERROR))) {
            this.resetToken();

            request = this.prepareRequest(params, methodName);
            response = this.getResponse(request, httpMethod);

            obj = JSONValue.parse(response);
            jsonResponse = (JSONObject) obj;
            error = jsonResponse.get("error");

            if (error != null) {
                throw new PlancakeApiException("Error " + error);
            }
        } else {
            throw new PlancakeApiException("Error " + error);
        }
    }

    return jsonResponse;
}

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

@SuppressWarnings("rawtypes")
public void testOption() throws Exception {
    msgParser.parseData("alert", (Map) JSONValue.parse(
            "{\"entry\": {\"exitPrice\": null,\"dateAdded\": 1355246510000,\"newsletterIds\": [58,59],\"type\": \"Long Option\",\"dateClosed\": null,\"amount\": null,\"username\": \"super_trades\",\"compareDate\": 1355246510000,\"ticker\": \"SGYP\",\"action\": \"Bought\",\"entryPrice\": 0.7,\"shortSell\": false,\"shortUrl\": \"1MnC9Y\",\"optionType\": \"CALL\",\"callOption\": true,\"entryComments\": \"All or nothing option position like SRPT was.  If drug data is good, I see targets out there from 15-40.  If data is not good,  then these options WILL BE WORTH ZERO.  Data due first week of January.  \",\"percentage\": null,\"optionExpiration\": 1358571600000,\"entryDate\": 1355246510000,\"futuresMonth\": 0,\"futuresYear\": 0,\"shares\": 50,\"entryType\": \"OPTION\",\"exitDate\": null,\"optionStrike\": 7.5,\"comments\": null,\"openTrade\": true},\"msgId\":30040,\"image\":\"http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg\"}"),
            new MsgHandler() {
                public boolean newMsg(Msg msg) {
                    Assert.assertEquals(TradeSignal.class, msg.getClass());
                    TradeSignal trade = (TradeSignal) msg;
                    Assert.assertEquals("super_trades", trade.getSourceName());
                    Assert.assertEquals(1355246510000L, trade.getDate().toDate().getTime());
                    Assert.assertEquals(TradeSignal.TYPE_BUY, trade.getType());
                    Assert.assertEquals("SGYP", trade.getContract().getSymbol());
                    Assert.assertEquals(Contract.OPTIONS, trade.getContract().getType());
                    Assert.assertEquals(50, trade.getNumShares());
                    Assert.assertEquals(0.7, trade.getPrice());
                    return false;
                }/*from ww  w.  ja  v  a  2s .  c om*/
            });
}

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

private void register() {
    mStatusLbl.setText(R.string.initializing);
    mProgressBar.setProgress(0);//from  w ww  . j  av a2s. co  m
    mProgressBar.setVisibility(View.VISIBLE);

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            mUIHandler.post(new SafeRunnable() {
                @Override
                protected void safeRun() throws Exception {
                    T.UI();
                    mProgressBar.setProgress(mProgressBar.getProgress() + 1);
                }
            });
        }
    };
    mTimer.scheduleAtFixedRate(timerTask, 250, 250);

    mRetryBtn.setVisibility(View.GONE);
    if (!mService.getNetworkConnectivityManager().isConnected()) {
        mTimer.cancel();
        mProgressBar.setVisibility(View.GONE);
        mStatusLbl.setText(R.string.registration_screen_instructions_check_network_not_available);
        mRetryBtn.setVisibility(View.VISIBLE);
        UIUtils.showNoNetworkDialog(this);
        return;
    }

    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.UI();
            AlertDialog.Builder builder = new AlertDialog.Builder(YSAAARegistrationActivity.this);
            builder.setMessage(R.string.error_please_try_again);
            builder.setPositiveButton(R.string.rogerthat, null);
            AlertDialog dialog = builder.create();
            dialog.show();

            mTimer.cancel();
            mProgressBar.setVisibility(View.GONE);
            mStatusLbl.setText(R.string.error_please_try_again);
            mRetryBtn.setVisibility(View.VISIBLE);
        }
    };

    final String timestamp = "" + mWiz.getTimestamp();
    final String deviceId = mWiz.getDeviceId();
    final String registrationId = mWiz.getRegistrationId();
    final String installId = mWiz.getInstallationId();

    mWorkerHandler.post(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "1";
            String signature = Security.sha256(
                    version + " " + installId + " " + timestamp + " " + deviceId + " " + registrationId + " "
                            + CloudConstants.APP_SERVICE_GUID + CloudConstants.REGISTRATION_MAIN_SIGNATURE);

            HttpPost httppost = new HttpPost(CloudConstants.REGISTRATION_YSAAA_URL);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(13);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("platform", "android"));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("signature", signature));
                nameValuePairs.add(new BasicNameValuePair("install_id", installId));
                nameValuePairs.add(new BasicNameValuePair("service", CloudConstants.APP_SERVICE_GUID));
                nameValuePairs.add(new BasicNameValuePair("language", Locale.getDefault().getLanguage()));
                nameValuePairs.add(new BasicNameValuePair("country", Locale.getDefault().getCountry()));
                nameValuePairs.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));
                nameValuePairs.add(
                        new BasicNameValuePair("use_xmpp_kick", CloudConstants.USE_XMPP_KICK_CHANNEL + ""));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", mGCMRegistrationId));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = mHttpClient.execute(httppost);

                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    mUIHandler.post(showErrorDialog);
                    return;
                }

                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
                        .parse(new InputStreamReader(entity.getContent()));

                if (statusCode != 200 || responseMap == null) {
                    if (statusCode == 500 && responseMap != null) {
                        final String errorMessage = (String) responseMap.get("error");
                        if (errorMessage != null) {
                            mUIHandler.post(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    T.UI();
                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                            YSAAARegistrationActivity.this);
                                    builder.setMessage(errorMessage);
                                    builder.setPositiveButton(R.string.rogerthat, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();

                                    mTimer.cancel();
                                    mProgressBar.setVisibility(View.GONE);
                                    mStatusLbl.setText(errorMessage);
                                    mRetryBtn.setVisibility(View.VISIBLE);
                                }
                            });
                            return;
                        }
                    }
                    mUIHandler.post(showErrorDialog);
                    return;
                }
                JSONObject account = (JSONObject) responseMap.get("account");
                final String email = (String) responseMap.get("email");
                final RegistrationInfo info = new RegistrationInfo(email,
                        new Credentials((String) account.get("account"), (String) account.get("password")));
                mUIHandler.post(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWiz.setEmail(email);
                        mWiz.save();
                        tryConnect(1, getString(R.string.registration_establish_connection, email,
                                getString(R.string.app_name)) + " ", info);
                    }
                });

            } catch (Exception e) {
                L.d(e);
                mUIHandler.post(showErrorDialog);
            }
        }
    });
}

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

/**
 * Get clients.//www.  j av  a2 s . c  o  m
 * 
 * @return list of {@link ch.simas.jtoggl.Client}
 */
public List<ch.simas.jtoggl.Client> getClients() {
    Client client = prepareClient();
    WebResource webResource = client.resource(CLIENTS);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<ch.simas.jtoggl.Client> clients = new ArrayList<ch.simas.jtoggl.Client>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            clients.add(new ch.simas.jtoggl.Client(entryObject.toJSONString()));
        }
    }
    return clients;
}

From source file:com.greatmancode.tools.utils.Updater.java

private boolean read() {
    try {/*from  www  .j av  a  2 s. c  om*/
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            caller.getLogger().warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            caller.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            caller.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            caller.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            caller.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

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

private JSONObject handleResponse(final HttpResponse RESPONSE) {
    int statusCode = RESPONSE.getStatusLine().getStatusCode();
    if (statusCode != 200) {
        //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
        return new JSONObject();
    }//from  w  w  w  .  j a  v  a2  s . c o m

    StringBuilder output = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(RESPONSE.getEntity().getContent()))) {
        String line;
        while ((line = br.readLine()) != null) {
            output.append(line);
        }
    } catch (IOException exception) {
        System.out.println("Error: " + exception);
    }
    JSONObject jsonObject = (JSONObject) JSONValue.parse(output.toString());
    return jsonObject;
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

@SuppressWarnings("unchecked")
public Map<String, Long> getUnreadCounts() {
    if (!isLoggedIn()) {
        login(myUsername, myPassword);//from www. ja va  2s . com
    }

    try {
        // go to an extremely high page so that it loads faster. Examine the
        // JSON feeds if you don't know what I mean by this.
        HttpGet get = new HttpGet(BASE + "/voice/inbox/recent?page=p1000");
        HttpResponse response = myClient.execute(get);
        String rsp = getJSON(response.getEntity());
        Object obj = JSONValue.parse(rsp);
        JSONObject msgs = (JSONObject) obj;

        Map<String, Long> unread = new HashMap<String, Long>();
        msgs = (JSONObject) msgs.get("unreadCounts");
        for (String key : (Set<String>) msgs.keySet()) {
            Object data = msgs.get(key);
            unread.put(key, (Long) data);
        }
        return unread;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap<String, Long>();
}

From source file:com.treasure_data.client.DefaultClientAdaptorImpl.java

private GetServerStatusResult doGetServerStatus(GetServerStatusRequest request) throws ClientException {
    request.setCredentials(getConfig().getCredentials());

    String jsonData = null;/*from www  . j  a v  a  2  s .co  m*/
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = HttpURL.V3_SYSTEM_SERVER_STATUS;
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doGetRequest(request, path, header, params);

        // receive response code and body
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Server is down", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Server is down", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "getServerStatus", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Server is down", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // { "status": "ok" }
    @SuppressWarnings("rawtypes")
    Map map = (Map) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);
    String status = (String) map.get("status");

    return new GetServerStatusResult(new ServerStatus(status));
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private ListSessionsResult doListSessions(ListSessionsRequest request) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;// w ww.j a  v a 2  s .  co  m
    String message = null;
    int code = 0;
    try {
        conn = createConnection();

        // send request
        String path = HttpURL.V3_LIST;
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doGetRequest(request, path, header, params);

        // receive response code and body
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("List sessions failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("List sessions failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "listSessions", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("List sessions failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // parse JSON data
    // {"bulk_imports":
    //   [
    //     {"name":"t01", "database":"sfdb", "table":"bi02",
    //      "status":"ready", "upload_frozen":false,
    //      "job_id":"70220", "valid_records":100,
    //      "error_records":10, "valid_parts":2, "error_parts":1},
    //     {"name":"sess01", "database":"mugadb", "table":"test04",
    //      "status":"uploading", "upload_frozen":false,
    //      "job_id":null, "valid_records":null,
    //      "error_records":null, "valid_parts":null, "error_parts":null}
    //   ]}
    @SuppressWarnings("rawtypes")
    Map map = (Map) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);

    @SuppressWarnings("unchecked")
    Iterator<Map<String, Object>> sessIter = ((List<Map<String, Object>>) map.get("bulk_imports")).iterator();
    List<SessionSummary> sessions = new ArrayList<SessionSummary>();
    while (sessIter.hasNext()) {
        Map<String, Object> sess = sessIter.next();
        String name = (String) sess.get("name");
        String database = (String) sess.get("database");
        String table = (String) sess.get("table");
        String status = (String) sess.get("status");
        boolean upload_frozen = (Boolean) sess.get("upload_frozen");
        String job_id = (String) sess.get("job_id");
        Long vr = (Long) sess.get("valid_records");
        long valid_records = vr != null ? vr : 0;
        Long er = (Long) sess.get("error_records");
        long error_records = er != null ? er : 0;
        Long vp = (Long) sess.get("valid_parts");
        long valid_parts = vp != null ? vp : 0;
        Long ep = (Long) sess.get("error_parts");
        long error_parts = ep != null ? ep : 0;
        SessionSummary summary = new SessionSummary(name, database, table,
                SessionSummary.Status.fromString(status), upload_frozen, job_id, valid_records, error_records,
                valid_parts, error_parts);
        sessions.add(summary);
    }

    return new ListSessionsResult(new ListSessions<SessionSummary>(sessions));
}

From source file:com.precioustech.fxtrading.oanda.restapi.order.OandaOrderManagementProvider.java

private Collection<Order<String, Long>> pendingOrdersForAccount(Long accountId,
        TradeableInstrument<String> instrument) {
    Collection<Order<String, Long>> pendingOrders = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {/*from  w w  w.  j a  v  a 2 s. co  m*/
        HttpUriRequest httpGet = new HttpGet(this.url + OandaConstants.ACCOUNTS_RESOURCE
                + TradingConstants.FWD_SLASH + accountId + ordersResource
                + (instrument != null ? "?instrument=" + instrument.getInstrument() : StringUtils.EMPTY));
        httpGet.setHeader(this.authHeader);
        httpGet.setHeader(OandaConstants.UNIX_DATETIME_HEADER);
        LOG.info(TradingUtils.executingRequestMsg(httpGet));
        HttpResponse resp = httpClient.execute(httpGet);
        String strResp = TradingUtils.responseToString(resp);
        if (strResp != StringUtils.EMPTY) {
            Object obj = JSONValue.parse(strResp);
            JSONObject jsonResp = (JSONObject) obj;
            JSONArray accountOrders = (JSONArray) jsonResp.get(orders);

            for (Object o : accountOrders) {
                JSONObject order = (JSONObject) o;
                Order<String, Long> pendingOrder = parseOrder(order);
                pendingOrders.add(pendingOrder);
            }
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception e) {
        LOG.error(String.format(
                "error encountered whilst fetching pending orders for account %d and instrument %s", accountId,
                instrument.getInstrument()), e);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return pendingOrders;
}