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.rmtheis.yandtran.YandexTranslatorAPI.java

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

    int i = 0;/*  www.j  av  a2  s  .c  o  m*/
    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.uzh.ddis.thesis.lambda_architecture.speed.spout.kafka.ZkState.java

public Map<Object, Object> readJSON(String path) {
    try {//from  w  ww .  java 2s  .co m
        byte[] b = readBytes(path);
        if (b == null) {
            return null;
        }
        return (Map<Object, Object>) JSONValue.parse(new String(b, "UTF-8"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.FFLive.Player.java

public void getPlayer() {
    try {//  w w w .j a va 2s  .  c o m
        if (playerID.equals("-1")) {
            //Average Team Player...
            Document doc = Jsoup.connect("http://fantasy.premierleague.com/entry/1/event-history/" + GW + "/")
                    .get();
            Elements averageScore = doc.select("div.ismUnit.ismSize2of5.ismLastUnit")
                    .select("div.ismSBSecondaryVal");
            if (averageScore.isEmpty()) {
                playerScore = 0;
            } else {
                try {
                    playerScore = Integer.parseInt(averageScore.text().replaceAll("\\D+", ""));
                } catch (NumberFormatException n) {
                    Main.log.log(2, "Issue saving Average Team..." + n + "\n");
                }
            }
            playerName = "Average";
        } else {
            Main.log.log(7, "Fetching Player " + playerID + "\n");
            //Connects to the players info page
            InputStream playerJson = new URL(
                    "http://fantasy.premierleague.com/web/api/elements/" + playerID + "/").openStream();
            //Reads the data into a JSON object (via casting into a regular object)
            Reader reader = new InputStreamReader(playerJson, "UTF-8");
            JSONObject playerValues = (JSONObject) JSONValue.parse(reader);

            //TODO Check if there are values overlength
            //Max Length Ref playerCount INT DEFAULT 1 NOT NULL, firstName VARCHAR(40), lastName VARCHAR(40),
            //webName VARCHAR(50), score INT, gameweekBreakdown VARCHAR(250), breakdown VARCHAR(250), 
            //teamName VARCHAR(40), currentFixture VARCHAR(40), nextFixture VARCHAR(40), status VARCHAR(10), 
            //news VARCHAR(250), photo VARCHAR(30))

            //Adds Required Data
            firstName = playerValues.get("first_name").toString();
            lastName = playerValues.get("second_name").toString();
            playerName = playerValues.get("web_name").toString();
            playerTeam = playerValues.get("team_name").toString();
            teamNumber = Integer.parseInt(playerValues.get("team_id").toString());
            position = playerValues.get("type_name").toString();
            /*
            JSONObject test = (JSONObject)JSONValue.parse(playerValues.get("fixture_history").toString());
            String summary = test.get("summary").toString();
            String all = test.get("all").toString();
             */
            playerScore = Integer.parseInt(playerValues.get("event_total").toString());
            gameweekBreakdown = playerValues.get("event_explain").toString();
            //scoreBreakdown = playerValues.get("fixture_history").toString();
            currentFixture = playerValues.get("current_fixture").toString();
            nextFixture = playerValues.get("next_fixture").toString();
            status = playerValues.get("status").toString();
            news = playerValues.get("news").toString();
            photo = playerValues.get("photo").toString();

            /*
            System.out.println(firstName);
            System.out.println(lastName);
            System.out.println(playerName);
            System.out.println(playerTeam);
            System.out.println(position);
            System.out.println(summary);
            System.out.println(all);
            System.out.println(playerScore);
            System.out.println(scoreBreakdown);
            System.out.println(currentFixture);
            System.out.println(nextFixture);
            System.out.println(status);
            System.out.println(news);
            System.out.println(photo);*/
        }
    } catch (ConnectException c) {
        if (timeoutCheck() > 3) {
            Main.log.log(2, "Too Many Timeouts.. Skipping\n");
        }
        Main.log.log(6, "Timeout Connecting, Retrying...\n");
        getPlayer();
    } catch (SocketTimeoutException e) {
        if (timeoutCheck() > 3) {
            Main.log.log(2, "Too Many Timeouts.. Skipping\n");
        }
        Main.log.log(6, "Timeout Connecting, Retrying...\n");
        getPlayer();
    } catch (UnknownHostException g) {
        Main.log.log(6, "No Connection... Skipping\n");
    } catch (NoRouteToHostException h) {
        Main.log.log(6, "No Connection... Skipping\n");
    } catch (IOException f) {
        Main.log.log(6, "In getPlayer: " + f + "\n");
    } catch (NullPointerException n) {
        Main.log.log(2, "Missing Player Field with ID:" + playerID + " " + n + "\n");
        Main.log.log(9, n);
    }
}

From source file:cpd3314.project.CPD3314ProjectTest.java

private void assertJSONFilesEqual(File a, File b) throws IOException {
    Scanner aIn = new Scanner(a);
    Scanner bIn = new Scanner(b);
    StringBuilder aJSON = new StringBuilder();
    StringBuilder bJSON = new StringBuilder();
    while (aIn.hasNext() && bIn.hasNext()) {
        aJSON.append(aIn.nextLine().trim());
        bJSON.append(bIn.nextLine().trim());
    }//  ww w  .ja v  a2 s. c  o m
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
    JSONObject aJ = (JSONObject) JSONValue.parse(aJSON.toString());
    JSONObject bJ = (JSONObject) JSONValue.parse(bJSON.toString());
    assertEquals(aJ.toJSONString(), bJ.toJSONString());
}

From source file:mml.handler.post.MMLPostHTMLHandler.java

void parseRequest(HttpServletRequest request) throws FileUploadException, Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(encoding);
        List<FileItem> items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString(encoding);
                    if (fieldName.equals(Params.DOCID))
                        this.docid = contents;
                    else if (fieldName.equals(Params.DIALECT)) {
                        JSONObject jv = (JSONObject) JSONValue.parse(contents);
                        if (jv.get("language") != null)
                            this.langCode = (String) jv.get("language");
                        this.dialect = jv;
                    } else if (fieldName.equals(Params.HTML)) {
                        html = contents;
                    } else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }/*from  ww  w . jav  a  2 s  . c o m*/
            }
            // we're not uploading files
        }
        if (encoding == null)
            encoding = "UTF-8";
        if (author == null)
            author = "Anon";
        if (style == null)
            style = "TEI/default";
        if (format == null)
            format = "MVD/TEXT";
        if (section == null)
            section = "";
        if (version1 == null)
            version1 = "/Base/first";
        if (description == null)
            description = "Version " + version1;
        if (docid == null)
            throw new Exception("missing docid");
        if (html == null)
            throw new Exception("Missing html");
        if (dialect == null)
            throw new Exception("Missing dialect");
    }
}

From source file:com.precioustech.fxtrading.oanda.restapi.position.OandaPositionManagementProvider.java

@Override
public Collection<Position<String>> getPositionsForAccount(Long accountId) {
    Collection<Position<String>> allPositions = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {//from   w  w w.  j av a2 s .  c  o  m
        String strResp = getResponseAsString(getPositionsForAccountUrl(accountId), httpClient);
        if (strResp != StringUtils.EMPTY) {
            Object obj = JSONValue.parse(strResp);
            JSONObject jsonResp = (JSONObject) obj;
            JSONArray accPositions = (JSONArray) jsonResp.get(positions);
            for (Object o : accPositions) {
                JSONObject accPosition = (JSONObject) o;
                Position<String> positionInfo = parsePositionInfo(accPosition);
                allPositions.add(positionInfo);
            }
        }
    } catch (Exception ex) {
        LOG.error("error encountered whilst fetching positions for account:" + accountId, ex);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return allPositions;
}

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

@Override
public Map<TradeableInstrument<String>, Price<String>> getCurrentPricesForInstruments(
        Collection<TradeableInstrument<String>> instruments) {
    StringBuilder instrumentCsv = new StringBuilder();
    boolean firstTime = true;
    for (TradeableInstrument<String> instrument : instruments) {
        if (firstTime) {
            firstTime = false;/*from  w  w w . j  ava  2  s  .c  om*/
        } else {
            instrumentCsv.append(TradingConstants.ENCODED_COMMA);
        }
        instrumentCsv.append(instrument.getInstrument());
    }

    Map<TradeableInstrument<String>, Price<String>> pricesMap = Maps.newHashMap();
    CloseableHttpClient httpClient = getHttpClient();
    try {
        HttpUriRequest httpGet = new HttpGet(
                this.url + OandaConstants.PRICES_RESOURCE + "?instruments=" + instrumentCsv.toString());
        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 prices = (JSONArray) jsonResp.get(OandaJsonKeys.prices);
            for (Object price : prices) {
                JSONObject trade = (JSONObject) price;
                Long priceTime = Long.parseLong(trade.get(time).toString());
                TradeableInstrument<String> instrument = new TradeableInstrument<String>(
                        (String) trade.get(OandaJsonKeys.instrument));
                Price<String> pi = new Price<String>(instrument, ((Number) trade.get(bid)).doubleValue(),
                        ((Number) trade.get(ask)).doubleValue(),
                        new DateTime(TradingUtils.toMillisFromNanos(priceTime)));
                pricesMap.put(instrument, pi);
            }
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception ex) {
        LOG.error(ex);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return pricesMap;
}

From source file:eu.anynet.java.util.HttpClient.java

/**
 * Request to JSONArray (max 2048 KB)//from   ww  w  .  j  a v  a2s . c o  m
 * @param request The request object
 * @return The JSON Array
 * @throws IOException
 */
public static JSONArray toJsonArray(Request request) throws IOException {
    String text = toString(request, DEFAULT_MAXDOWNLOADINKBYTE * 1024);
    JSONArray json = (JSONArray) JSONValue.parse(text);
    return json;
}

From source file:com.johncroth.histo.logging.LogHistogramWriterParserTest.java

@Test
public void testWriteAndReadInterval() throws Exception {
    LogHistogramRecorder rec = makeRecorder();
    RecordedInterval<LogHistogramRecorder> ri = new RecordedInterval<LogHistogramRecorder>(rec, 21, 35);
    String recJson = writer.convert(ri).toString();
    RecordedInterval<LogHistogramRecorder> riParsed = parser
            .parseIntervalJson((JSONObject) JSONValue.parse(recJson));
    assertEquals(21, riParsed.getStartMillis());
    assertEquals(35, riParsed.getEndMillis());
    LogHistogramRecorder recParsed = riParsed.getRecorder();
    assertEquals(makeRecorder().getHistogramMap().keySet(), recParsed.getHistogramMap().keySet());
    for (String key : rec.getHistogramMap().keySet()) {
        LogHistogramCalculator c = new LogHistogramCalculator(rec.getHistogram(key));
        LogHistogramCalculator cp = new LogHistogramCalculator(recParsed.getHistogram(key));
        assertEquals(c.getTotalCount(), cp.getTotalCount());
        assertEquals(c.getTotalWeight(), cp.getTotalWeight(), .00001);
    }//ww  w.j  ava 2s  .  c o m
}

From source file:com.precioustech.fxtrading.oanda.restapi.account.OandaAccountDataProviderService.java

private Account<Long> getLatestAccountInfo(final Long accountId, CloseableHttpClient httpClient) {
    try {/*  w  w  w. j a v a2 s .  c o m*/
        HttpUriRequest httpGet = new HttpGet(getSingleAccountUrl(accountId));
        httpGet.setHeader(authHeader);

        LOG.info(TradingUtils.executingRequestMsg(httpGet));
        HttpResponse httpResponse = httpClient.execute(httpGet);
        String strResp = TradingUtils.responseToString(httpResponse);
        if (strResp != StringUtils.EMPTY) {
            Object obj = JSONValue.parse(strResp);
            JSONObject accountJson = (JSONObject) obj;

            /*Parse JSON response for account information*/
            final double accountBalance = ((Number) accountJson.get(balance)).doubleValue();
            final double accountUnrealizedPnl = ((Number) accountJson.get(unrealizedPl)).doubleValue();
            final double accountRealizedPnl = ((Number) accountJson.get(realizedPl)).doubleValue();
            final double accountMarginUsed = ((Number) accountJson.get(marginUsed)).doubleValue();
            final double accountMarginAvailable = ((Number) accountJson.get(marginAvail)).doubleValue();
            final Long accountOpenTrades = (Long) accountJson.get(openTrades);
            final String accountBaseCurrency = (String) accountJson.get(accountCurrency);
            final Double accountLeverage = (Double) accountJson.get(marginRate);

            Account<Long> accountInfo = new Account<Long>(accountBalance, accountUnrealizedPnl,
                    accountRealizedPnl, accountMarginUsed, accountMarginAvailable, accountOpenTrades,
                    accountBaseCurrency, accountId, accountLeverage);

            return accountInfo;
        } else {
            TradingUtils.printErrorMsg(httpResponse);
        }
    } catch (Exception e) {
        LOG.error("Exception encountered whilst getting info for account:" + accountId, e);
    }
    return null;
}