Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:nl.b3p.viewer.stripes.IbisMergeFeaturesActionBean.java

/**
 * Force the workflow status attribute on the feature. This will handle the
 * case where the {@code extraData} attribute is a piecs of json with the
 * workflow, eg/*from   w  w w .  j  a va2 s .  co m*/
 * {@code {workflow_status:'afgevoerd',datum_mutatie:'2015-12-01Z00:00'}}.
 *
 * @param features A list of features to be modified
 * @return the list of modified features that are about to be committed to
 * the datastore
 *
 * @throws JSONException if json parsing failed
 */
@Override
protected List<SimpleFeature> handleExtraData(List<SimpleFeature> features) throws JSONException {
    JSONObject json = new JSONObject(this.getExtraData());
    Iterator items = json.keys();
    while (items.hasNext()) {
        String key = (String) items.next();
        for (SimpleFeature f : features) {
            log.debug(String.format("Setting value: %s for attribute: %s on feature %s", json.get(key), key,
                    f.getID()));
            f.setAttribute(key, json.get(key));
            if (key.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
                newWorkflowStatus = WorkflowStatus.valueOf(json.getString(key));
            }
        }
    }
    return features;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//* w ww.  j a v  a2  s. c o  m*/
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;//from w w w .j  a  va 2s .  com
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:org.vaadin.addons.locationtextfield.OpenStreetMapGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {//from w w w. j  av  a  2s .c o  m
        JSONArray results = new JSONArray(input);
        boolean ambiguous = results.length() > 1;
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            GeocodedLocation loc = new GeocodedLocation();
            loc.setAmbiguous(ambiguous);
            loc.setOriginalAddress(address);
            loc.setGeocodedAddress(result.getString("display_name"));
            loc.setLat(Double.parseDouble(result.getString("lat")));
            loc.setLon(Double.parseDouble(result.getString("lon")));
            loc.setType(getLocationType(result));
            if (result.has("address")) {
                JSONObject obj = result.getJSONObject("address");
                if (obj.has("house_number"))
                    loc.setStreetNumber(obj.getString("house_number"));
                if (obj.has("road"))
                    loc.setRoute(obj.getString("road"));
                if (obj.has("city"))
                    loc.setLocality(obj.getString("city"));
                if (obj.has("county"))
                    loc.setAdministrativeAreaLevel2(obj.getString("county"));
                if (obj.has("state"))
                    loc.setAdministrativeAreaLevel1(obj.getString("state"));
                if (obj.has("postcode"))
                    loc.setPostalCode(obj.getString("postcode"));
                if (obj.has("country_code"))
                    loc.setCountry(obj.getString("country_code").toUpperCase());
            }
            locations.add(loc);
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}

From source file:org.vaadin.addons.locationtextfield.OpenStreetMapGeocoder.java

private LocationType getLocationType(JSONObject result) throws JSONException {
    final String classValue = result.getString("class");
    final String type = result.getString("type");
    if ("highway".equals(classValue) || "railway".equals(classValue))
        return LocationType.ROUTE;
    else if ("amenity".equals(classValue) || "liesure".equals(classValue) || "natural".equals(type)
            || "shop".equals(classValue) || "tourism".equals(classValue) || "waterway".equals(type)) {
        return LocationType.POI;
    } else if ("building".equals(classValue))
        return LocationType.STREET_ADDRESS;
    else if ("place".equals(classValue)) {
        if ("house".equals(type) || "houses".equals(type) || "airport".equals(type) || "farm".equals(type))
            return LocationType.STREET_ADDRESS;
        else if ("city".equals(type) || "hamlet".equals(type) || "town".equals(type)
                || "unincorporated_area".equals(type) || "locality".equals(type) || "village".equals(type)
                || "municipality".equals(type)) {
            return LocationType.LOCALITY;
        } else if ("state".equals(type) || "region".equals(type))
            return LocationType.ADMIN_LEVEL_1;
        else if ("postcode".equals(type))
            return LocationType.POSTAL_CODE;
        else if ("country".equals(type))
            return LocationType.COUNTRY;
        else if ("county".equals(type))
            return LocationType.ADMIN_LEVEL_2;
        else if ("subdivision".equals(type) || "suburb".equals(type))
            return LocationType.NEIGHBORHOOD;
        else if ("moor".equals(type) || "island".equals(type) || "islet".equals(type) || "sea".equals(type))
            return LocationType.POI;
    } else if ("boundary".equals(classValue) && "administrative".equals(type))
        return LocationType.ADMIN_LEVEL_1;
    return LocationType.UNKNOWN;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

public static String getError(InputStream inputStream) throws IOException, JSONException {

    String error = Integer.toString(R.string.unknow_error);

    String jsonString = getString(inputStream);
    JSONObject jsonObject = jObjectFromString(jsonString);
    if (jsonObject.has("message")) {
        error = jsonObject.getString("message");
    } else {/* w w w .j a  v  a2s  . co  m*/
        error += jsonObject.toString();
    }
    return error;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

public static String getError(JSONObject jsonObject) {

    String error = Integer.toString(R.string.unknow_error);

    if (jsonObject.has("message")) {
        try {/*from  w  w w .  ja va 2 s.  c om*/
            error = jsonObject.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        error += jsonObject.toString();
    }
    return error;
}

From source file:org.openmidaas.library.authentication.AuthCallbackForRegistration.java

@Override
public void onSuccess(String deviceToken) {
    try {//from  w w w. j a  v  a 2  s  . com
        AVSServer.registerDevice(deviceToken, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                if (response == null || response.isEmpty()) {
                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                } else {
                    try {
                        MIDaaS.logDebug(TAG, "device successfully registered. persisting registration.");
                        JSONObject responseObject = new JSONObject(response);
                        if (responseObject.has("subjectToken") && !(responseObject.isNull("subjectToken"))) {
                            SubjectToken subjectToken = SubjectTokenFactory.createAttribute();
                            subjectToken.setValue(Build.MODEL);
                            subjectToken.setSignedToken(responseObject.getString("subjectToken"));
                            subjectToken.save();
                            // if we didn't get the access token, we can get it on-demand at a later time. 
                            if ((responseObject.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                                    && !(responseObject.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                                    && (responseObject.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                            && !(responseObject
                                                    .isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                                MIDaaS.logDebug(TAG, "Registration response has an access token.");
                                AccessToken token = AccessToken.createAccessToken(
                                        responseObject.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                        responseObject.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                                if (token != null) {
                                    MIDaaS.logDebug(TAG, "Access token is ok.");
                                    AuthenticationManager.getInstance().setAccessToken(token);
                                } else {
                                    MIDaaS.logError(TAG, "Access token is null.");
                                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                                }
                            } else {
                                MIDaaS.logDebug(TAG,
                                        "No access token object in server response. Access token will be created on-demand.");
                            }
                        } else {
                            MIDaaS.logError(TAG, "Server response doesn't match expected response");
                            mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                        mInitCallback.onSuccess();
                    } catch (InvalidAttributeValueException e) {
                        // should never get here b/c we're returning true. 
                        MIDaaS.logError(TAG, "logic error. should never have thrown exception");
                    } catch (MIDaaSException e) {
                        MIDaaS.logError(TAG, e.getError().getErrorMessage());
                        mInitCallback.onError(e);

                    } catch (JSONException e) {
                        MIDaaS.logError(TAG, e.getMessage());
                        mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }
                }
            }

            @Override
            public void onFailure(Throwable e, String response) {
                MIDaaS.logError(TAG, response);
                mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            }
        });
    } catch (JSONException e) {
        MIDaaS.logError(TAG, "Internal error");
        MIDaaS.logError(TAG, e.getMessage());
        mInitCallback.onError(null);
    }

}

From source file:com.ibm.iot.auto.bluemix.samples.ui.InputData.java

public List<CarProbe> getCarProbes() throws IOException, JSONException {
    List<CarProbe> carProbes = new ArrayList<CarProbe>();

    FileReader fileReader = null;
    try {/* w w w.  j a  va  2 s.  co m*/
        fileReader = new FileReader(inputFile);
        JSONTokener jsonTokener = new JSONTokener(fileReader);
        JSONArray cars = new JSONArray(jsonTokener);
        for (int i = 0; i < cars.length(); i++) {
            JSONObject car = cars.getJSONObject(i);
            CarProbe carProbe = new CarProbe(car.getString("trip_id"), car.getString("timestamp"),
                    car.getDouble("heading"), car.getDouble("speed"), car.getDouble("longitude"),
                    car.getDouble("latitude"));
            carProbes.add(carProbe);
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
    Collections.sort(carProbes);

    return carProbes;
}

From source file:net.jmhertlein.mcanalytics.console.gui.HostEntry.java

public static HostEntry fromJSON(JSONObject host) {
    return new HostEntry(host.getString("nick"), host.getString("url"), host.getInt("port"));
}