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:org.kitodo.data.elasticsearch.index.type.TemplateTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    TemplateType templateType = new TemplateType();
    JSONParser parser = new JSONParser();

    Template template = prepareData().get(0);
    HttpEntity document = templateType.createDocument(template);
    JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    JSONObject excepted = (JSONObject) parser
            .parse("{\"process\":1,\"origin\":null,\"properties\":[{\"id\":1}," + "{\"id\":2}]}");
    assertEquals("Template JSONObject doesn't match to given JSONObject!", excepted, actual);

    template = prepareData().get(1);//from w  ww . jav a  2 s . com
    document = templateType.createDocument(template);
    actual = (JSONObject) parser.parse(EntityUtils.toString(document));
    excepted = (JSONObject) parser.parse("{\"process\":2,\"origin\":null,\"properties\":[]}");
    assertEquals("Template JSONObject doesn't match to given JSONObject!", excepted, actual);
}

From source file:me.ryandowling.allmightybot.utils.TwitchAPI.java

public static String setTopic(String username, String topic) throws IOException, ParseException {
    TwitchAPIRequest request = new TwitchAPIRequest("/channels/" + username);

    String response = request.put(new ChannelPutRequest(topic));

    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(response);

    return (String) jsonObject.get("status");
}

From source file:me.uni.sushilkumar.geodine.util.YummlyImage.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//ww w.j a  v  a  2s  . co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String id = request.getParameter("id");
        JSONParser parser = new JSONParser();
        URL u = new URL("http://api.yummly.com/v1/api/recipe/" + id
                + "?_app_id=bad04ef2&_app_key=f2df74726bb514d9390abf1e6c9ad4f0");
        Object json = parser.parse(new BufferedReader(new InputStreamReader(u.openStream())));
        JSONObject obj = (JSONObject) json;
        JSONArray images = (JSONArray) obj.get("images");
        Iterator<JSONObject> it = images.iterator();
        JSONObject temp = it.next();
        String url = (String) temp.get("hostedLargeUrl");
        out.println("<h1>" + url + "</h1>");
    } catch (ParseException ex) {
        Logger.getLogger(YummlyImage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:com.nubits.nubot.pricefeeds.feedservices.CcedkPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    String url = TradeUtilsCCEDK.getCCEDKTickerUrl(pair);
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String htmlString;/* w w w . j a v a  2s.c om*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        try {
            //{"errors":false,"response":{"entity":{"pair_id":"2","min":"510","max":"510","avg":"510","vol":"0.0130249"}}}
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
            JSONObject tickerObject = (JSONObject) httpAnswerJson.get("response");
            JSONObject entityObject = (JSONObject) tickerObject.get("entity");

            double last = Double.valueOf((String) entityObject.get("avg"));

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

}

From source file:br.net.fabiozumbi12.RedProtect.hooks.MojangUUIDs.java

public static String getUUID(String player) {
    try {/*  ww w. j av a2s .c  om*/
        URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + player);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = in.readLine();
        if (line == null) {
            return null;
        }
        JSONObject jsonProfile = (JSONObject) new JSONParser().parse(line);
        String name = (String) jsonProfile.get("id");
        return toUUID(name);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:msuresh.raftdistdb.RaftClient.java

public static void GetValue(String name, String key) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;/*w w w.  j a  va2 s  . c  o m*/
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Getting key .. Hold on.");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        Object str = client.submit(new GetQuery(key)).get();
        System.out.println("For the key : " + key + ", the database returned the value : " + (String) str);
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

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

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*  w  ww .jav 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();
        boolean found = false;
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();
            JSONObject rates = (JSONObject) httpAnswerJson.get("rates");
            lastRequest = System.currentTimeMillis();
            if (rates.containsKey(lookingfor)) {
                double last = (Double) rates.get(lookingfor);
                last = Utils.round(1 / last, 8);
                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(last, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warning("Cannot find currency :" + lookingfor + " on feed :" + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (ParseException 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;
    }
}

From source file:com.nubits.nubot.pricefeeds.ExchangeratelabPriceFeed.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  va 2  s.co  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));
            JSONArray array = (JSONArray) httpAnswerJson.get("rates");

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();

            boolean found = false;
            double rate = -1;
            for (int i = 0; i < array.size(); i++) {
                JSONObject temp = (JSONObject) array.get(i);
                String tempCurrency = (String) temp.get("to");
                if (tempCurrency.equalsIgnoreCase(lookingfor)) {
                    found = true;
                    rate = Utils.getDouble((Double) temp.get("rate"));
                    rate = Utils.round(1 / rate, 8);
                }
            }

            lastRequest = System.currentTimeMillis();

            if (found) {

                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(rate, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warning("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } 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;
    }
}

From source file:com.serena.rlc.provider.artifactory.domain.Artifact.java

public static Artifact parseSingle(String options) {
    JSONParser parser = new JSONParser();
    try {/*from   w ww.j ava  2  s  .  c  om*/
        Object parsedObject = parser.parse(options);
        Artifact artifact = parseSingle((JSONObject) parsedObject);
        return artifact;
    } catch (ParseException e) {
        logger.error("Error while parsing input JSON - " + options, e);
    }
    return null;
}

From source file:com.conwet.silbops.model.AbstractMappingTest.java

@Before
public void setUp() throws ParseException {

    String jsonString = "{\"symbol:str\":\"GOOG\", \"value:long\":18}";
    json = (JSONObject) new JSONParser().parse(jsonString);

    attrib1 = new Attribute("symbol", Type.STRING);
    attrib2 = new Attribute("value", Type.LONG);

    instance = newInstance();/*from  w w  w  .j av  a 2  s. c om*/
    instance.attribute(attrib1, "GOOG").attribute(attrib2, 18L);
}