Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:model.Post_store.java

public static int getlastid() {
    JSONParser parser = new JSONParser();
    int lastid = 1;
    try {//ww  w  .j  ava 2s .  c  om

        Object idObj = parser.parse(new FileReader(root + "posts/lastid.json"));

        JSONObject jsonObject = (JSONObject) idObj;

        String slastid = jsonObject.get("lastid").toString();
        lastid = Integer.parseInt(slastid);

        //System.out.println(lastid);

    } catch (FileNotFoundException e) {
        JSONObject newIdObj = new JSONObject();
        lastid = 1;
        newIdObj.put("lastid", lastid);

        try (FileWriter file = new FileWriter(root + "posts/lastid.json");) {
            file.write(newIdObj.toJSONString());
            file.flush();
            file.close();

        } catch (IOException ex) {
            System.out.println(e);
        }
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return lastid;
}

From source file:at.ac.tuwien.dsg.smartcom.integration.JSONConverter.java

private static String[] parseResults(JSONObject json) {
    List<String> valueList = new ArrayList<>();

    if (json.containsKey("results")) {
        JSONArray array = (JSONArray) json.get("results");

        for (Object obj : array) {
            JSONArray innerArray = (JSONArray) obj;

            for (Object o : innerArray) {
                try {
                    valueList.add(parseToString(o));
                } catch (ConverterException e) {
                    return null;
                }//from w  w w .  j  a v a 2  s . c  om
            }
        }

        return valueList.toArray(new String[valueList.size()]);
    } else {
        return null;
    }
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static JSONArray pullNovaVM(String host, String tenantId, String token) throws IOException {

    String url = String.format("http://%s:8774/v2/%s/servers/detail", host, tenantId);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "", token);

    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);
    JSONArray servers = (JSONArray) responseJSON.get("servers");

    return servers;
}

From source file:com.emuneee.camerasyncmanager.util.GeocodeHelper.java

public static List<Camera> geocodeCameras(List<Camera> cameras, long sleep) throws Exception {
    List<Camera> geocoded = new ArrayList<Camera>(cameras.size());
    int count = 1;

    // loop through and geocode each camera
    for (Camera camera : cameras) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(sGeocodeUrl).append("?");
        urlBuilder.append(sLatLng).append("=");
        urlBuilder.append(camera.getLatitude()).append(",").append(camera.getLongitude());
        urlBuilder.append("&").append(sSensor);
        sLogger.debug("Geocode URL " + urlBuilder.toString());

        try {//from w ww  .  j a  v  a  2  s  . c o  m
            // retry
            String data = null;
            int retryCount = 0;

            while (data == null && retryCount < sRetryCount) {
                if (retryCount > 0) {
                    sLogger.info("Retrying geocoding");
                }
                data = HttpHelper.getStringDataFromUrl(urlBuilder.toString());
                Thread.sleep(sleep);
                retryCount++;
            }

            if (data == null) {
                sLogger.warn("Unable to geocode the camera, no data returned " + camera);
            } else if (data != null && data.contains("OVER_QUERY_LIMIT")) {
                sLogger.warn("Unable to geocode the camera, query limit exceeded " + camera);
                throw new Exception("Unable to geocode the camera, query limit exceeded");
            } else {
                JSONObject jsonObj = (JSONObject) new JSONParser().parse(data);
                JSONArray resultsArr = (JSONArray) jsonObj.get("results");

                if (resultsArr.size() > 0) {

                    for (int i = 0; i < resultsArr.size(); i++) {
                        JSONObject result = (JSONObject) resultsArr.get(i);

                        // loop through the address components
                        JSONArray addressComponents = (JSONArray) result.get("address_components");
                        for (Object compObj : addressComponents) {
                            JSONObject component = (JSONObject) compObj;
                            String shortName = (String) component.get("short_name");
                            JSONArray types = (JSONArray) component.get("types");

                            // loop through the types
                            for (Object typeObj : types) {
                                String type = (String) typeObj;

                                if (type.equalsIgnoreCase("administrative_area_level_3")) {
                                    camera.setArea(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("locality")) {
                                    camera.setCity(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("administrative_area_level_1")) {
                                    camera.setState(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("country")) {
                                    camera.setCountry(shortName);
                                    break;
                                } else if (type.equalsIgnoreCase("postal_code")) {
                                    camera.setZipCode(shortName);
                                    break;
                                }
                            }
                        }

                        if (camera.containsAllRequiredData()) {
                            break;
                        } else {
                            sLogger.info(
                                    "Some required data is missing, moving to the next address component set");
                        }
                    }
                }

                if (camera.containsAllRequiredData()) {
                    geocoded.add(camera);
                    sLogger.info("Camera " + count++ + " of " + cameras.size() + " geocoded");
                    sLogger.debug("Geocoded camera " + camera);
                    sLogger.debug("Sleeping for " + sleep + " milliseconds");
                } else {
                    sLogger.warn(
                            "Some required data is missing and geocoding results have been exhausted for camera: "
                                    + camera);
                }
            }
        } catch (InterruptedException e) {
            sLogger.error("Error geocoding address");
            sLogger.error(e.getMessage());
        } catch (ParseException e) {
            sLogger.error("Error geocoding address");
            sLogger.error(e.getMessage());
        }
    }

    return geocoded;
}

From source file:com.storageroomapp.client.util.JsonSimpleUtil.java

/**
 * Convenience method for pulling a Boolean value off of a JSONObject
 * @param obj the JSONObject received from the server
 * @param key the String key of the value we want
 * @param defaultValue the Boolean to return if a value is not found (can be null)
 * @return the Boolean value, or null if not found or not an boolean
 *//*www.j  a  va  2 s .com*/
static public Boolean parseJsonBooleanValue(JSONObject obj, String key, Boolean defaultValue) {
    if ((obj == null) || (key == null)) {
        return defaultValue;
    }
    String value = null;
    Object valueObj = obj.get(key);
    if (valueObj != null) {
        value = valueObj.toString();
    }
    return "true".equals(value);

}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Build RSA {@link PublicKey} from RSA JWK JSON object
 * // w ww.  jav a  2  s  . c o m
 * @param input
 *            RSA JSON Web Key {@link JSONObject}
 * @return {@link PublicKey} or null
 */
private static PublicKey buildRsaPublicKeyByJwk(JSONObject input) {
    try {
        BigInteger modulus = new BigInteger(Base64.decodeBase64(input.get("n").toString()));
        BigInteger publicExponent = new BigInteger(Base64.decodeBase64(input.get("e").toString()));

        loggerInstance.log(Converter.class, "RSA PublicKey values: N: " + modulus + " E: " + publicExponent,
                Logger.LogLevel.DEBUG);
        return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (Exception e) {
        return null;
    }
}

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

public static Artifact parseSingle(JSONObject jsonObject) {
    Artifact aObj = null;// w  w  w  . j  a  v a 2 s .  c om
    if (jsonObject != null) {
        aObj = new Artifact((String) getJSONValue(jsonObject, "uri"), (String) jsonObject.get("path"),
                (String) jsonObject.get("downloadUri"));
        aObj.setRepo((String) jsonObject.get("repo"));
        aObj.setCreated((String) jsonObject.get("created"));
        aObj.setCreatedBy((String) jsonObject.get("createdBy"));
        aObj.setLastModified((String) jsonObject.get("lastModified"));
        aObj.setModifiedBy((String) jsonObject.get("modifiedBy"));
        aObj.setLastUpdated((String) jsonObject.get("lastUpdated"));
        aObj.setMimeType((String) jsonObject.get("mimeType"));
        aObj.setSize((String) jsonObject.get("size"));
        try {
            URI uri = new URI((String) getJSONValue(jsonObject, "uri"));
            aObj.setName(uri.getName());
            String[] segments = uri.getPath().split("/");
            aObj.setVersion(segments[segments.length - 2]);
        } catch (URIException ex) {
            logger.error("Error while parsing input JSON - " + (String) getJSONValue(jsonObject, "uri"), ex);
        }
    }
    return aObj;
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static String getTenantId(String host, String tenantName, String token) throws IOException {

    String url = String.format("http://%s:35357/v2.0/tenants", host);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "python-keystoneclient", token);
    //System.out.println(responseStr);
    JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr);
    JSONArray tenants = (JSONArray) responseJSON.get("tenants");

    String tenantId = "";
    for (Object tenant : tenants) {
        if (((JSONObject) tenant).get("name").equals(tenantName)) {
            tenantId = (String) ((JSONObject) tenant).get("id");
        }//from  ww  w  .j  a v a 2 s .co m
    }

    return tenantId;
}

From source file:com.grouptuity.venmo.VenmoSDK.java

public static VenmoResponse validateVenmoPaymentResponse(String signed_payload) {
    String encoded_signature, payload;
    if (signed_payload == null) {
        return new VenmoResponse(null, null, null, "0");
    }//  ww  w. java  2 s.  c o  m
    try {
        String[] encodedsig_payload_array = signed_payload.split("\\.");
        encoded_signature = encodedsig_payload_array[0];
        payload = encodedsig_payload_array[1];
    } catch (ArrayIndexOutOfBoundsException e) {
        return new VenmoResponse(null, null, null, "0");
    }

    String decoded_signature = base64_url_decode(encoded_signature);
    String data;
    // check signature 
    String expected_sig = hash_hmac(payload, Grouptuity.VENMO_SECRET, "HmacSHA256");

    Log.d("VenmoSDK", "expected_sig using HmacSHA256:" + expected_sig);

    VenmoResponse myVenmoResponse;

    if (decoded_signature.equals(expected_sig)) {
        data = base64_url_decode(payload);

        try {
            JSONArray response = (JSONArray) JSONValue.parse(data);
            JSONObject obj = (JSONObject) response.get(0);
            String payment_id = obj.get("payment_id").toString();
            String note = obj.get("note").toString();
            String amount = obj.get("amount").toString();
            String success = obj.get("success").toString();
            myVenmoResponse = new VenmoResponse(payment_id, note, amount, success);
        } catch (Exception e) {
            Log.d("VenmoSDK", "Exception caught: " + e.getMessage());
            myVenmoResponse = new VenmoResponse(null, null, null, "0");
        }
    } else {
        Log.d("VenmoSDK", "Signature does NOT match");
        myVenmoResponse = new VenmoResponse(null, null, null, "0");
    }
    return myVenmoResponse;
}

From source file:model.Post_store.java

public static List<String> getpostcomments(int id) {

    JSONParser parser = new JSONParser();
    List<String> comments = new ArrayList<>();

    try {/*from   w w  w.ja  v  a 2 s.c  o  m*/

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray Jcomments = (JSONArray) jsonObject.get("comments");
        if (Jcomments != null) {
            Iterator<String> iterator = Jcomments.iterator();
            while (iterator.hasNext()) {
                comments.add(iterator.next());
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return comments;

}