Example usage for org.json.simple.parser JSONParser JSONParser

List of usage examples for org.json.simple.parser JSONParser JSONParser

Introduction

In this page you can find the example usage for org.json.simple.parser JSONParser JSONParser.

Prototype

JSONParser

Source Link

Usage

From source file:com.appdynamics.cloudfoundry.appdservicebroker.CredentialsHolder.java

CredentialsHolder() {
    try {//from  w  w w .  j av  a2s .c o m
        HashMap<String, JSONObject> appd_plans_map = (JSONObject) new JSONParser()
                .parse(System.getenv("APPD_PLANS"));
        init(appd_plans_map);
    } catch (ParseException pe) {
        log.error("Unable to parse the passed content: " + System.getenv("APPD_PLANS"));
    }
}

From source file:com.nubits.nubot.tests.TestAggregateOptions.java

private void aggregate() {
    Map setMap = new HashMap();

    for (int i = 0; i < fileNames.size(); i++) {
        try {/* w  w w.  java  2 s  .  c  o  m*/
            JSONParser parser = new JSONParser();

            JSONObject fileJSON = (JSONObject) (parser.parse(FileSystem.readFromFile(fileNames.get(i))));
            JSONObject tempOptions = (JSONObject) fileJSON.get("options");

            Set tempSet = tempOptions.entrySet();
            for (Object o : tempSet) {
                Entry entry = (Entry) o;
                setMap.put(entry.getKey(), entry.getValue());
            }

        } catch (ParseException ex) {
            LOG.severe("Parse exception \n" + ex.toString());
            System.exit(0);
        }
    }

    JSONObject optionsObject = new JSONObject();
    optionsObject.put("options", setMap);
}

From source file:ch.asadzia.cognitive.EmotionDetect.java

public ServiceResult process() {

    HttpClient httpclient = HttpClients.createDefault();

    try {//from  w  w w . j a  v a  2  s  . com
        URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/octet-stream");
        request.setHeader("Ocp-Apim-Subscription-Key", apikey);

        // Request body
        FileEntity reqEntity = new FileEntity(imageData);
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String responseStr = EntityUtils.toString(entity);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                System.err.println(responseStr);
                return null;
            }

            JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseStr);
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);

            HashMap<char[], Double> scores = (HashMap) jsonObject.get("scores");

            Map.Entry<char[], Double> maxEntry = null;

            for (Map.Entry<char[], Double> entry : scores.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

                if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
                    maxEntry = entry;
                }
            }
            Object key = maxEntry.getKey();

            String winningEmotionName = (String) key;

            ServiceResult result = new ServiceResult(translateEmotion(winningEmotionName), winningEmotionName);

            System.out.println(responseStr);

            return result;
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    return null;
}

From source file:ClubImpl.java

public String getEvents() throws IOException {
    JSONParser parser = new JSONParser();

    Object obj = null;//from w  ww  .  j  a  v  a  2s. c  om
    try {
        File f = new File(".");
        System.out.println(f.getAbsolutePath());
        File relative = new File("Events.json");
        obj = parser.parse(new FileReader(relative));
    } catch (Exception ex) {
        Logger.getLogger(ClubImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONObject jsonObject = (JSONObject) obj;
    return jsonObject.toJSONString();
}

From source file:org.kitodo.data.elasticsearch.index.type.BatchTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    BatchType batchType = new BatchType();
    JSONParser parser = new JSONParser();

    Batch batch = prepareData().get(0);/*  ww  w .  j a v  a 2 s . co  m*/
    HttpEntity document = batchType.createDocument(batch);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject expected = (JSONObject) parser
            .parse("{\"title\":\"Batch1\",\"type\":\"LOGISTIC\"," + "\"processes\":[{\"id\":1},{\"id\":2}]}");
    assertEquals("Batch JSONObject doesn't match to given JSONObject!", expected, actual);

    batch = prepareData().get(1);
    document = batchType.createDocument(batch);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    expected = (JSONObject) parser.parse("{\"title\":\"Batch2\",\"type\":null,\"processes\":[]}");
    assertEquals("Batch JSONObject doesn't match to given JSONObject!", expected, actual);
}

From source file:mobilebank.Json.java

public JSONObject getJson(String url) throws ParseException {

    HttpPost httppost = new HttpPost(baseUrl + url);
    // Depends on your web service
    httppost.setHeader("Content-type", "application/x-www-form-urlencoded");

    InputStream inputStream = null;
    String result = null;/*  ww w  . j  a v a  2 s .c  o  m*/
    try {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        result = sb.toString();
    } catch (Exception e) {
        // Oops
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception squish) {
        }
    }
    JSONParser parser = new JSONParser();
    JSONObject jObject = (JSONObject) parser.parse(result);
    return jObject;

}

From source file:com.nubits.nubot.pricefeeds.BtcePriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {

    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*from   ww w .  ja  v  a  2  s. c  o  m*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.severe(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONObject tickerObject = (JSONObject) httpAnswerJson.get("ticker");
            double last = Utils.getDouble(tickerObject.get("last"));

            lastRequest = System.currentTimeMillis();
            lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                    new Amount(last, pair.getPaymentCurrency()));
            return lastPrice;
        } catch (Exception ex) {
            LOG.severe(htmlString);
            LOG.severe(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:it.polimi.logging.LogMessageUtils.java

public static LogType getLogType(String message) {
    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;/*from   ww  w. j a v  a  2s. c o m*/
    String logType = "";
    try {
        jsonMsg = (JSONObject) parser.parse(message);
        logType = (String) jsonMsg.get(JsonStrings.LOG_TYPE);
        return LogType.valueOf(logType);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:eu.celarcloud.jcatascopia.serverpack.MetricProcessor.java

public void run() {
    if (this.server.inDebugMode())
        System.out.println("\nMetricProcessor>> processing the following message...\n" + msg);

    try {//w  ww . j a v  a2s.c o  m
        JSONParser parser = new JSONParser();
        JSONObject json;
        json = (JSONObject) parser.parse(msg);

        //check if metrics are from an intermediate server
        if (json.get("serverID") == null)
            processor(json);
        else
            redistProcessor(json);
    } catch (NullPointerException e) {
        this.server.writeToLog(Level.SEVERE, e);
        e.printStackTrace();
    } catch (Exception e) {
        this.server.writeToLog(Level.SEVERE, e);
        e.printStackTrace();
    }
    return;
}

From source file:com.nubits.nubot.pricefeeds.CoinbasePriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;//from   w w w . j a  v a 2s  .  c  o  m
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.severe(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            double last = Double.valueOf((String) httpAnswerJson.get("amount"));

            lastRequest = System.currentTimeMillis();
            lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                    new Amount(last, pair.getPaymentCurrency()));
            return lastPrice;
        } catch (Exception ex) {
            LOG.severe(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}