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

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

Introduction

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

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:processingtest.CitySense.java

public ArrayList<CityData> getDayDataBySource() throws URISyntaxException, IOException {
    String query = queryBuilder.getDayDataBySource(2); //Over 2 days
    CloseableHttpResponse response = this.executeRequest(query);
    HttpEntity entity = response.getEntity();
    ArrayList<CityData> dataPoints = null;

    if (entity != null) {
        try ( // A Simple JSON Response Read
                InputStream instream = entity.getContent()) {
            String result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            //System.out.println("RESPONSE: " + result);

            JSONParser parser = new JSONParser();
            try {
                Object obj = parser.parse(result);
                JSONObject jobj = (JSONObject) obj;
                //System.out.println(jobj.entrySet());
                Object dataObject = jobj.get("data");
                JSONArray array = (JSONArray) dataObject;
                //System.out.println(array.get(0));
                dataPoints = decodeJsonData(array);
                System.out.println((dataPoints.size()));
            } catch (ParseException pe) {
                System.out.println("position: " + pe.getPosition());
                System.out.println(pe);
            }/*w  w w .jav  a 2  s.co m*/
        }
    }
    return dataPoints;
}

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   www  .  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));
            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.nubits.nubot.pricefeeds.feedservices.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;//  w w w  .  ja v  a  2s  . c  o  m
        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 {
            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.warn("Cannot find currency " + lookingfor + " on feed " + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } 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:at.uni_salzburg.cs.ckgroup.cscpp.mapper.algorithm.VehicleStatusTestCase.java

@Test
public void testCase04() throws ParseException {
    String status = "{\"vehicle.id\":\"532d463b-6836-487c-989d-47c59285c17d\",\"state\":\"completed\",\"latitude\":57.8226984,\"longitude\":15.04211393,\"altitude\":5.0,"
            + "\"tolerance\":52.0,\"actions\":\"temperature,photo\"}";
    JSONParser parser = new JSONParser();
    VehicleStatus s = new VehicleStatus((JSONObject) parser.parse(status));
    Assert.assertEquals("532d463b-6836-487c-989d-47c59285c17d", s.getId());
    Assert.assertEquals("completed", s.getState().toString().toLowerCase());
    //      Assert.assertEquals(57.8226984, s.getPosition().getLatitude(), 1E-9);
    //      Assert.assertEquals(15.04211393, s.getPosition().getLongitude(), 1E-9);
    //      Assert.assertEquals(5.0, s.getPosition().getAltitude(), 1E-9);
    Assert.assertEquals(Double.NaN, s.getTolerance(), 1E-9);
    Assert.assertNull(s.getPosition());/*  ww w  .  ja  va 2  s  .c  o  m*/
    //      Assert.assertNull(s.getTolerance());
    //      Assert.assertArrayEquals(new String[]{"temperature","photo"}, s.getActions());
    Assert.assertNull(s.getActions());

    s = new VehicleStatus((JSONObject) parser.parse(s.toJSONString()));
    Assert.assertEquals("532d463b-6836-487c-989d-47c59285c17d", s.getId());
    Assert.assertEquals("completed", s.getState().toString().toLowerCase());
    //      Assert.assertEquals(57.8226984, s.getPosition().getLatitude(), 1E-9);
    //      Assert.assertEquals(15.04211393, s.getPosition().getLongitude(), 1E-9);
    //      Assert.assertEquals(5.0, s.getPosition().getAltitude(), 1E-9);
    //      Assert.assertEquals(52.0, s.getTolerance(), 1E-9);
    //      Assert.assertArrayEquals(new String[]{"temperature","photo"}, s.getActions());
    Assert.assertEquals(Double.NaN, s.getTolerance(), 1E-9);
    Assert.assertNull(s.getPosition());
    Assert.assertNull(s.getActions());
}

From source file:com.pankaj.GenericResource.java

/**
 *
 * @param obj//from  www.  j  a v  a  2s.c o  m
 * @return
 * @throws SQLException
 */
@POST
@Path("/products")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)

public Response createProduct(String str) throws SQLException, ParseException {

    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(str);

    Object id = json.get("id");
    String productid = id.toString();
    int Id = Integer.parseInt(productid);
    Object name = json.get("name");
    String productname = name.toString();
    Object description = json.get("description");
    String productdescription = description.toString();
    Object quantity = json.get("quantity");
    String productquantity = quantity.toString();
    int Qnt = Integer.parseInt(productquantity);
    Statement smt = conn.createStatement();
    smt.executeUpdate("INSERT INTO product VALUES ('" + Id + "','" + productname + "','" + productdescription
            + "','" + Qnt + "' )");
    return Response.status(Status.CREATED).build();
}

From source file:ca.fastenalcompany.jsonconfig.ProductJson.java

@POST
@Consumes("application/json")
public Response doPost(String str) throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(str);
    Set<String> keySet = json.keySet();
    if (keySet.contains("name") && keySet.contains("description") && keySet.contains("quantity")) {
        int productid = update(PropertyManager.getProperty("db_insert"), json.get("name").toString(),
                json.get("description").toString(), json.get("quantity").toString());
        if (productid > 0) {
            String url = uriI.getBaseUri() + uriI.getPath() + "/" + productid;
            return Response.ok(url, MediaType.TEXT_PLAIN).build();
        } else {/*  w  w  w. ja v a  2s  .  c  om*/
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

From source file:com.androgogic.AikauLoginController.java

/**
 * //  ww  w.  ja v a 2 s .  c om
 * @param request
 * @param response
 * @throws Exception
 */
protected void beforeSuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        final HttpSession session = request.getSession();

        // Get the authenticated user name and use it to retrieve all of the groups that the user is a member of...
        String username = (String) request.getParameter(PARAM_USERNAME);
        if (username == null) {
            username = (String) session.getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);
        }

        if (username != null && session.getAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS) == null) {
            Connector conn = FrameworkUtil.getConnector(session, username,
                    AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
            ConnectorContext c = new ConnectorContext(HttpMethod.GET);
            c.setContentType("application/json");
            Response res = conn.call("/api/people/" + URLEncoder.encode(username) + "?groups=true", c);
            if (Status.STATUS_OK == res.getStatus().getCode()) {
                // Assuming we get a successful response then we need to parse the response as JSON and then
                // retrieve the group data from it...
                // 
                // Step 1: Get a String of the response...
                String resStr = res.getResponse();

                // Step 2: Parse the JSON...
                JSONParser jp = new JSONParser();
                Object userData = jp.parse(resStr.toString());

                // Step 3: Iterate through the JSON object getting all the groups that the user is a member of...
                StringBuilder groups = new StringBuilder(512);
                if (userData instanceof JSONObject) {
                    Object groupsArray = ((JSONObject) userData).get("groups");
                    if (groupsArray instanceof org.json.simple.JSONArray) {
                        for (Object groupData : (org.json.simple.JSONArray) groupsArray) {
                            if (groupData instanceof JSONObject) {
                                Object groupName = ((JSONObject) groupData).get("itemName");
                                if (groupName != null) {
                                    groups.append(groupName.toString()).append(',');
                                }
                            }
                        }
                    }
                }

                // Step 4: Trim off any trailing commas...
                if (groups.length() != 0) {
                    groups.delete(groups.length() - 1, groups.length());
                }

                // Step 5: Store the groups on the session...
                session.setAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS, groups.toString());
            } else {
                session.setAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS, "");
            }
        }
    } catch (ConnectorServiceException e1) {
        throw new Exception("Error creating remote connector to request user group data.");
    }
}

From source file:EditProductModel.EditProductWS.java

/**
 * This is a sample web service operation
 *//*from  ww  w . j  a  va 2  s .  c o  m*/
@WebMethod(operationName = "validasiTokenEdit")
public String validasiTokenEdit(@WebParam(name = "access_token") String access_token)
        throws IOException, ParseException {
    String targetIS = "ValidateToken";
    String urlParameters = "access_token=" + access_token;
    HttpURLConnection urlConn = UrlConnectionManager.doReqPost(targetIS, urlParameters);
    String resp = UrlConnectionManager.getResponse(urlConn);
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(resp);
    String statusResp = (String) obj.get("status");

    return statusResp;
}

From source file:ca.fastenalcompany.jsonconfig.ProductJson.java

@PUT
@Path("{id}")
@Consumes("application/json")
public Response doPut(@PathParam("id") Integer id, String str) throws ParseException {
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(str);
    Set<String> keySet = json.keySet();
    if (keySet.contains("name") && keySet.contains("description") && keySet.contains("quantity")) {
        int productid = update(PropertyManager.getProperty("db_update"), json.get("name").toString(),
                json.get("description").toString(), json.get("quantity").toString(), id + "");
        if (productid > 0) {
            String url = uriI.getBaseUri() + uriI.getPath();
            return Response.ok(url, MediaType.TEXT_PLAIN).build();
        } else {/*ww  w .ja  v  a 2  s  .co m*/
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

From source file:com.example.austin.test.TextActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text);

    Thread thread = new Thread(new Runnable() {
        @Override/*w  ww .  j  av a2s . co m*/
        public void run() {
            try {
                Bundle bundle = getIntent().getExtras();
                Bitmap photo = (Bitmap) bundle.get("photo");
                ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 100, stream1);
                byte[] fileContent = stream1.toByteArray();

                String license_code = "59D1D7B4-61FD-49EB-A549-C77E08B7103A";
                String user_name = "austincheng16";

                String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";
                URL url = new URL(ocrURL);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Authorization", "Basic "
                        + new String(Base64.encodeBase64((user_name + ":" + license_code).getBytes())));

                connection.setRequestProperty("Content-Type", "application/json");

                connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

                try {
                    OutputStream stream = connection.getOutputStream();

                    stream.write(fileContent);
                    stream.close();

                    int httpCode = connection.getResponseCode();

                    if (httpCode == HttpURLConnection.HTTP_OK) {
                        String jsonResponse = GetResponseToString(connection.getInputStream());
                        PrintOCRResponse(jsonResponse);
                    } else {
                        String jsonResponse = GetResponseToString(connection.getErrorStream());
                        JSONParser parser = new JSONParser();
                        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);
                        Log.i("austin", "Error Message: " + jsonObj.get("ErrorMessage"));
                    }
                    connection.disconnect();
                } catch (IOException e) {
                    Log.i("austin", "IOException");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}