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.taiter.ce.Main.java

public void updateCheck() {
    try {/*from  ww  w.  j  av  a  2s. co m*/
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Checking for updates...");

        URLConnection connection = updateListURL.openConnection();
        connection.setConnectTimeout(5000);
        connection.addRequestProperty("User-Agent", "Custom Enchantments - Update Checker");
        connection.setDoOutput(true);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        JSONObject newestUpdate = (JSONObject) array.get(array.size() - 1);

        newVersion = newestUpdate.get("name").toString().replace("Custom Enchantments ", "").trim();
        newMD5 = newestUpdate.get("md5").toString();

        int newLength = newVersion.length();
        int currentLength = currentVersion.length();

        double versionNew;
        double versionCurrent;

        Boolean newHasSubVersion = false;
        Boolean currentHasSubVersion = false;

        try {
            versionNew = Double.parseDouble(newVersion);
        } catch (NumberFormatException ex) {
            newHasSubVersion = true;
            versionNew = Double.parseDouble(newVersion.substring(0, newVersion.length() - 1));
        }

        try {
            versionCurrent = Double.parseDouble(currentVersion);
        } catch (NumberFormatException ex) {
            currentHasSubVersion = true;
            versionCurrent = Double.parseDouble(currentVersion.substring(0, currentVersion.length() - 1));
        }

        if ((versionNew > versionCurrent) || ((versionNew == versionCurrent) && newHasSubVersion
                && currentHasSubVersion && ((byte) newVersion.toCharArray()[newLength
                        - 1] > (byte) currentVersion.toCharArray()[currentLength - 1]))) {
            hasUpdate = true;
            updateDownloadURL = new URL(newestUpdate.get("downloadUrl").toString().replace("\\.", ""));
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] A new update is available!");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] The new version is " + ChatColor.AQUA
                    + newVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] You are currently using "
                    + ChatColor.AQUA + currentVersion + ChatColor.GREEN + ".");
            Bukkit.getConsoleSender().sendMessage(
                    ChatColor.GREEN + "[CE] You can use '/ce update applyupdate' to update automatically.");

        } else {
            hasUpdate = false;
            Bukkit.getConsoleSender()
                    .sendMessage(ChatColor.GREEN + "[CE] You are using the latest Version of CE!");
        }
        hasChecked = true;
    } catch (IOException ioex) {
        Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "[CE] Failed to check for updates");
    }

}

From source file:example.Test.java

public static void testJSON() {
    String textFile = "MobyDick.txt";
    int numberOfAddedLines = 8000;

    System.out.println(/* w w w . ja v a2  s  .c  o m*/
            "This is a Test for the efficiency and accuracy of JSON encoding and decoding of the String Phone Lattice data structure");
    System.out.println(
            " It tests how quickly a String Phone Lattice data structure can encode its contents into a JSON object,\n How quickly it can decode a JSON object resembling a String Phone Lattice data structure,\n and how accurately it can decode those JSON objects  ");
    System.out.print(
            "As a bonus, it will also be testing the speed in which the JSONObjects from the JSON Simple library can be converted to and from String objects");
    System.out.println("All time measurements are given in milliseconds  ");
    System.out.println("The test will be parsing the words off of " + textFile + "  ");
    System.out.println("The test will now start  ");
    TextIO.readFile("src/" + textFile);
    String added = "";
    for (int i = 0; i < numberOfAddedLines; i++) {
        added += " " + TextIO.getln().trim();
    }

    String[] AddedWords = added.split(" ");

    System.out.println("Done parsing words  ");
    System.out.println("**" + AddedWords.length + "** added words  ");

    StringPhoneLattice root = new StringPhoneLattice();
    for (String word : AddedWords) {
        root.addWord(word);
    }

    long startEncode, endEncode, startString, endString, startJSON, endJSON, startDecode, endDecode;
    startEncode = System.currentTimeMillis();
    JSONObject json = root.toJSON();
    endEncode = System.currentTimeMillis();
    System.out.println("Time to encode to JSON:  ");
    System.out.println("*" + (endEncode - startEncode) + "*  ");

    startString = System.currentTimeMillis();
    String stringJSON = json.toJSONString();
    endString = System.currentTimeMillis();
    System.out.println("Time to encode to JSON Object to String object:  ");
    System.out.println("*" + (endString - startString) + "*  ");

    startJSON = System.currentTimeMillis();
    JSONObject json1 = (JSONObject) JSONValue.parse(stringJSON); //This is null!
    endJSON = System.currentTimeMillis();
    System.out.println("Time to encode to String Object to JSON object:  ");
    System.out.println("*" + (endJSON - startJSON) + "*  ");

    startDecode = System.currentTimeMillis();
    StringPhoneLattice root1 = new StringPhoneLattice(json1);
    endDecode = System.currentTimeMillis();
    System.out.println("Time to encode to JSON Object to StringPhoneLattice object:  ");
    System.out.println("*" + (endDecode - startDecode) + "*  ");

    if (root1.toJSON().toJSONString().equals(stringJSON)) {
        System.out.println(
                "JSON Encoding and decoding of StringPhoneLattice data structure is completely accurate  ");
        //   System.out.println(root1.toJSON().toJSONString());
    } else {
        System.out.println("JSON Encoding and decoding of StringPhoneLattice data structure is inaccurate  ");
        System.out.println("Here is the original JSON output:  ");
        System.out.println(json.toJSONString() + "  ");
        System.out.println("Here is the JSON output after conversions:  ");
        System.out.println(root1.toJSON().toJSONString() + "  ");
    }
}

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

public boolean connect(String number) {
    if (!isLoggedIn()) {
        login();//from www  .ja  v a  2 s. com
        if (!isLoggedIn()) {
            myError = "Could not log in!";
            return false;
        }
    }

    String lineNumber = mySettings.getGVCallbackNum();
    if (lineNumber == null || lineNumber.length() == 0) {
        myError = "No callback number available! Please set this in 'GV Settings'";
        return false;
    }
    HttpPost post = new HttpPost(BASE + "/voice/call/connect/");
    List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("_rnr_se", myToken));
    data.add(new BasicNameValuePair("forwardingNumber", lineNumber));
    data.add(new BasicNameValuePair("outgoingNumber", number));
    data.add(new BasicNameValuePair("remember", "0"));
    data.add(new BasicNameValuePair("subscriberNumber", "undefined"));
    data.add(new BasicNameValuePair("phoneType", "2"));
    try {
        post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
        HttpResponse response = myClient.execute(post);
        String responseText = getJSON(response.getEntity());
        JSONObject json = (JSONObject) JSONValue.parse(responseText);
        boolean success = (Boolean) json.get("ok");
        if (!success) {
            myError = responseText;
        }
        return success;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    myError = "Unknown exception!";
    return false;
}

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

@Override
public Order<String, Long> pendingOrderForAccount(Long orderId, Long accountId) {
    CloseableHttpClient httpClient = getHttpClient();
    try {// w ww .  j a  v a  2s .  c  o  m
        HttpUriRequest httpGet = new HttpGet(orderForAccountUrl(accountId, orderId));
        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) {
            JSONObject order = (JSONObject) JSONValue.parse(strResp);
            return parseOrder(order);
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception e) {
        LOG.error(
                String.format("error encountered whilst fetching pending order for account %d and order id %d",
                        accountId, orderId),
                e);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return null;
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

private static String[] jsonToStringArr(final String inputString, final String propertyName) throws Exception {
    final JSONArray jsonArr = (JSONArray) JSONValue.parse(inputString);
    String[] values = new String[jsonArr.size()];

    int i = 0;/*  ww  w .  j av  a 2s  . c  om*/
    for (Object obj : jsonArr) {
        if (propertyName != null && propertyName.length() != 0) {
            final JSONObject json = (JSONObject) obj;
            if (json.containsKey(propertyName)) {
                values[i] = json.get(propertyName).toString();
            }
        } else {
            values[i] = obj.toString();
        }
        i++;
    }
    return values;
}

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

/**
 * Stop the given time entry.// w w w.j a v a2s.co m
 * 
 * @param timeEntry
 *            to time entry to stop
 * @return the stopped {@link TimeEntry}
 */
public TimeEntry stopTimeEntry(TimeEntry timeEntry) {
    Client client = prepareClient();
    String url = TIME_ENTRY_STOP.replace(PLACEHOLDER, timeEntry.getId().toString());
    WebResource webResource = client.resource(url);

    JSONObject object = createTimeEntryRequestParameter(timeEntry);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .put(String.class);

    object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    return new TimeEntry(data.toJSONString());
}

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

@SuppressWarnings("rawtypes")
public void testIntPrice() throws Exception {
    msgParser.parseData("alert", (Map) JSONValue.parse(
            "{\"entry\":{\"exitPrice\":null,\"dateAdded\":1346162335587,\"newsletterIds\":[3,2,24,26],\"type\":\"Short Stock\",\"dateClosed\":null,\"amount\":null,\"username\":\"timothysykes\",\"compareDate\":1346162335587,\"ticker\":\"NTE\",\"action\":\"Shorted\",\"entryPrice\":9,\"shortSell\":true,\"shortUrl\":\"1Mn43l\",\"optionType\":\"CALL\",\"callOption\":true,\"entryComments\":\"Shorted some into this mammoth spike, this is not a volatile stock, Seeking Alpha hyped it up based on rumors, goal is to make 50 cents/share in 1-2 days\",\"percentage\":null,\"optionExpiration\":null,\"entryDate\":1346162335587,\"futuresMonth\":0,\"futuresYear\":0,\"shares\":2000,\"entryType\":\"STOCK\",\"exitDate\":null,\"optionStrike\":null,\"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("timothysykes", trade.getSourceName());
                    Assert.assertEquals(1346162335587L, trade.getDate().toDate().getTime());
                    Assert.assertEquals(TradeSignal.TYPE_SHORT, trade.getType());
                    Assert.assertEquals(Contract.stock("NTE"), trade.getContract());
                    Assert.assertEquals(2000, trade.getNumShares());
                    Assert.assertEquals(9.0, trade.getPrice());
                    return false;
                }//from  w ww.  ja v  a  2  s  . c  o m
            });
}

From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java

@Override
public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
    try {//w  ww .  j av  a  2 s. co m

        String sessionId = sugarLogin();
        Gson gson = new Gson();

        SugarGetEntryList sgel = new SugarGetEntryList();
        sgel.setSession(sessionId);
        sgel.setModule_name("Contacts");
        StringBuffer b = new StringBuffer();
        b.append(
                "contacts.id in (SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address = '")
                .append(user.getUserID()).append("')");
        sgel.setQuery(b.toString());
        sgel.setOrder_by("");
        sgel.setOffset(0);
        ArrayList<String> reqFields = new ArrayList<String>();
        reqFields.add("id");
        sgel.setSelect_fields(reqFields);
        sgel.setMax_results(-1);
        sgel.setDeleted(false);
        sgel.setLink_name_to_fields_array(new HashMap<String, List<String>>());

        String searchJson = gson.toJson(sgel);
        String respJSON = execJson(searchJson, "get_entry_list");
        JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON);
        JSONArray jsonArray = (JSONArray) jsonObj.get("entry_list");

        if (jsonArray.size() == 0) {
            throw new Exception("User " + user.getUserID() + " not found");
        }

        String id = (String) ((JSONObject) jsonArray.get(0)).get("id");

        SugarEntry newContact = new SugarEntry();
        newContact.setSession(sessionId);
        newContact.setModule("Contacts");
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("id", id);
        nvps.put("deleted", "1");

        newContact.setName_value_list(nvps);
        String createUserJSON = gson.toJson(newContact);

        execJson(createUserJSON, "set_entry");
    } catch (Exception e) {
        throw new ProvisioningException("Could not delete user", e);
    }

}

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

/**
 * Get the document body of the given urn or null
 * @param db the database where it is/* www  .jav a 2s .  com*/
 * @param docID the docID of the resource
 * @return the document body or null if not present
 */
protected String getDocumentBody(String db, String docID) throws MMLException {
    try {
        String jStr = Connector.getConnection().getFromDb(db, docID);
        if (jStr != null) {
            JSONObject jDoc = (JSONObject) JSONValue.parse(jStr);
            if (jDoc != null) {
                Object body = jDoc.get(JSONKeys.BODY);
                if (body != null)
                    return body.toString();
            }
        }
        throw new MMLException("document " + db + "/" + docID + " not found");
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.precioustech.fxtrading.oanda.restapi.marketdata.historic.OandaHistoricMarketDataProvider.java

private List<CandleStick<String>> getCandleSticks(TradeableInstrument<String> instrument, String url,
        CandleStickGranularity granularity) throws OandaLimitExceededException {
    List<CandleStick<String>> allCandleSticks = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {//from  w  w  w.  j av a 2s  .c o  m
        HttpUriRequest httpGet = new HttpGet(url);
        httpGet.setHeader(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 candlsticks = (JSONArray) jsonResp.get(candles);

            for (Object o : candlsticks) {
                JSONObject candlestick = (JSONObject) o;

                final double openPrice = ((Number) candlestick.get(openMid)).doubleValue();
                final double highPrice = ((Number) candlestick.get(highMid)).doubleValue();
                final double lowPrice = ((Number) candlestick.get(lowMid)).doubleValue();
                final double closePrice = ((Number) candlestick.get(closeMid)).doubleValue();
                final long timestamp = Long.parseLong(candlestick.get(time).toString());

                CandleStick<String> candle = new CandleStick<String>(openPrice, highPrice, lowPrice, closePrice,
                        new DateTime(TradingUtils.toMillisFromNanos(timestamp)), instrument, granularity);
                allCandleSticks.add(candle);
            }
        } else {
            String errResponse = TradingUtils.getResponse(resp);
            Object obj = JSONValue.parse(errResponse);
            JSONObject jsonResp = (JSONObject) obj;
            int errCode = Integer.parseInt(jsonResp.get(code).toString());
            if (errCode == LIMIT_ERR_CODE) {
                throw new OandaLimitExceededException();
            }
            System.err.println(errResponse);
        }
    } catch (OandaLimitExceededException leex) {
        throw leex;
    } catch (Exception e) {
        LOG.error(String.format(
                "exception encountered whilst retrieving candlesticks for instrument %s with granularity %s",
                instrument.getInstrument(), granularity.getLabel()), e);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return allCandleSticks;
}