Search in sources :

Example 76 with JSONArray

use of org.json.JSONArray in project physical-web by google.

the class PwsClient method resolve.

/**
   * Send an HTTP request to the PWS to resolve a set of URLs.
   * @param broadcastUrls The URLs to resolve.
   * @param pwsResultCallback The callback to be run when the response is received.
   */
public void resolve(final Collection<String> broadcastUrls, final PwsResultCallback pwsResultCallback) {
    // Create the response callback.
    final long startTime = new Date().getTime();
    JsonObjectRequest.RequestCallback requestCallback = new JsonObjectRequest.RequestCallback() {

        private void recordResponse() {
            pwsResultCallback.onResponseReceived(new Date().getTime() - startTime);
        }

        private PwsResult getPwsResult(JSONObject jsonUrlMetadata) {
            switch(apiVersion) {
                case 1:
                    return getV1PwsResult(jsonUrlMetadata);
                case 2:
                    return getV2PwsResult(jsonUrlMetadata);
                default:
                    throw new RuntimeException(UKNOWN_API_ERROR_MESSAGE);
            }
        }

        private PwsResult getV1PwsResult(JSONObject jsonUrlMetadata) {
            try {
                return new PwsResult.Builder(jsonUrlMetadata.getString("id"), jsonUrlMetadata.getString("url")).setTitle(jsonUrlMetadata.optString("title")).setDescription(jsonUrlMetadata.optString("description")).setIconUrl(jsonUrlMetadata.optString("icon")).setGroupId(jsonUrlMetadata.optString("groupId")).build();
            } catch (JSONException e) {
                return null;
            }
        }

        private PwsResult getV2PwsResult(JSONObject jsonUrlMetadata) {
            try {
                JSONObject jsonPageInfo = jsonUrlMetadata.getJSONObject("pageInfo");
                return new PwsResult.Builder(jsonUrlMetadata.getString("scannedUrl"), jsonUrlMetadata.getString("resolvedUrl")).setTitle(jsonPageInfo.optString("title")).setDescription(jsonPageInfo.optString("description")).setIconUrl(jsonPageInfo.optString("icon")).build();
            } catch (JSONException e) {
                return null;
            }
        }

        public void onResponse(JSONObject result) {
            recordResponse();
            // Build the metadata from the response.
            JSONArray foundMetadata;
            String jsonKey;
            switch(apiVersion) {
                case 1:
                    jsonKey = "metadata";
                    break;
                case 2:
                    jsonKey = "results";
                    break;
                default:
                    throw new RuntimeException(UKNOWN_API_ERROR_MESSAGE);
            }
            try {
                foundMetadata = result.getJSONArray(jsonKey);
            } catch (JSONException e) {
                pwsResultCallback.onPwsResultError(broadcastUrls, 200, e);
                return;
            }
            // Loop through the metadata for each url.
            Set<String> foundUrls = new HashSet<>();
            for (int i = 0; i < foundMetadata.length(); i++) {
                JSONObject jsonUrlMetadata = foundMetadata.getJSONObject(i);
                PwsResult pwsResult = getPwsResult(jsonUrlMetadata);
                pwsResultCallback.onPwsResult(pwsResult);
                foundUrls.add(pwsResult.getRequestUrl());
            }
            // See which urls the PWS didn't give us a response for.
            Set<String> missed = new HashSet<>(broadcastUrls);
            missed.removeAll(foundUrls);
            for (String url : missed) {
                pwsResultCallback.onPwsResultAbsent(url);
            }
        }

        public void onError(int responseCode, Exception e) {
            recordResponse();
            pwsResultCallback.onPwsResultError(broadcastUrls, responseCode, e);
        }
    };
    // Create the request.
    String targetUrl = constructPwsResolveUrl();
    JSONObject payload = new JSONObject();
    try {
        JSONArray urls = new JSONArray();
        for (String url : broadcastUrls) {
            JSONObject obj = new JSONObject();
            obj.put("url", url);
            urls.put(obj);
        }
        String jsonKey;
        switch(apiVersion) {
            case 1:
                jsonKey = "objects";
                break;
            case 2:
                jsonKey = "urls";
                break;
            default:
                throw new RuntimeException(UKNOWN_API_ERROR_MESSAGE);
        }
        payload.put(jsonKey, urls);
    } catch (JSONException e) {
        pwsResultCallback.onPwsResultError(broadcastUrls, 0, e);
        return;
    }
    Request request;
    try {
        request = new JsonObjectRequest(targetUrl, payload, requestCallback);
    } catch (MalformedURLException e) {
        pwsResultCallback.onPwsResultError(broadcastUrls, 0, e);
        return;
    }
    makeRequest(request);
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Date(java.util.Date) JSONException(org.json.JSONException) MalformedURLException(java.net.MalformedURLException) JSONObject(org.json.JSONObject) HashSet(java.util.HashSet)

Example 77 with JSONArray

use of org.json.JSONArray in project android-maps-utils by googlemaps.

the class GeoJsonParser method parseGeometry.

/**
     * Parses a single GeoJSON geometry object containing a coordinates array or a geometries array
     * if it has type GeometryCollection
     *
     * @param geoJsonGeometry geometry object to parse
     * @return Geometry object
     */
private static Geometry parseGeometry(JSONObject geoJsonGeometry) {
    try {
        String geometryType = geoJsonGeometry.getString("type");
        JSONArray geometryArray;
        if (geometryType.equals(GEOMETRY_COLLECTION)) {
            // GeometryCollection
            geometryArray = geoJsonGeometry.getJSONArray(GEOMETRY_COLLECTION_ARRAY);
        } else if (isGeometry(geometryType)) {
            geometryArray = geoJsonGeometry.getJSONArray(GEOMETRY_COORDINATES_ARRAY);
        } else {
            // No geometries or coordinates array
            return null;
        }
        return createGeometry(geometryType, geometryArray);
    } catch (JSONException e) {
        return null;
    }
}
Also used : JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 78 with JSONArray

use of org.json.JSONArray in project android-maps-utils by googlemaps.

the class GeoJsonParser method parseFeatureCollection.

/**
     * Parses the array of GeoJSON features in a given GeoJSON feature collection. Also parses the
     * bounding box member of the feature collection if it exists.
     *
     * @param geoJsonFeatureCollection feature collection to parse
     * @return array of GeoJsonFeature objects
     */
private ArrayList<GeoJsonFeature> parseFeatureCollection(JSONObject geoJsonFeatureCollection) {
    JSONArray geoJsonFeatures;
    ArrayList<GeoJsonFeature> features = new ArrayList<GeoJsonFeature>();
    try {
        geoJsonFeatures = geoJsonFeatureCollection.getJSONArray(FEATURE_COLLECTION_ARRAY);
        if (geoJsonFeatureCollection.has(BOUNDING_BOX)) {
            mBoundingBox = parseBoundingBox(geoJsonFeatureCollection.getJSONArray(BOUNDING_BOX));
        }
    } catch (JSONException e) {
        Log.w(LOG_TAG, "Feature Collection could not be created.");
        return features;
    }
    for (int i = 0; i < geoJsonFeatures.length(); i++) {
        try {
            JSONObject feature = geoJsonFeatures.getJSONObject(i);
            if (feature.getString("type").equals(FEATURE)) {
                GeoJsonFeature parsedFeature = parseFeature(feature);
                if (parsedFeature != null) {
                    // Don't add null features
                    features.add(parsedFeature);
                } else {
                    Log.w(LOG_TAG, "Index of Feature in Feature Collection that could not be created: " + i);
                }
            }
        } catch (JSONException e) {
            Log.w(LOG_TAG, "Index of Feature in Feature Collection that could not be created: " + i);
        }
    }
    return features;
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException)

Example 79 with JSONArray

use of org.json.JSONArray in project android-maps-utils by googlemaps.

the class HeatmapsDemoActivity method readItems.

// Datasets from http://data.gov.au
private ArrayList<LatLng> readItems(int resource) throws JSONException {
    ArrayList<LatLng> list = new ArrayList<LatLng>();
    InputStream inputStream = getResources().openRawResource(resource);
    String json = new Scanner(inputStream).useDelimiter("\\A").next();
    JSONArray array = new JSONArray(json);
    for (int i = 0; i < array.length(); i++) {
        JSONObject object = array.getJSONObject(i);
        double lat = object.getDouble("lat");
        double lng = object.getDouble("lng");
        list.add(new LatLng(lat, lng));
    }
    return list;
}
Also used : Scanner(java.util.Scanner) JSONObject(org.json.JSONObject) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) LatLng(com.google.android.gms.maps.model.LatLng)

Example 80 with JSONArray

use of org.json.JSONArray in project LiveSDK-for-Android by liveservices.

the class ContactsActivity method loadContacts.

private void loadContacts() {
    final ProgressDialog progDialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
    mClient.getAsync("me/contacts", new LiveOperationListener() {

        @Override
        public void onError(LiveOperationException exception, LiveOperation operation) {
            progDialog.dismiss();
            showToast(exception.getMessage());
        }

        @Override
        public void onComplete(LiveOperation operation) {
            progDialog.dismiss();
            JSONObject result = operation.getResult();
            if (result.has(JsonKeys.ERROR)) {
                JSONObject error = result.optJSONObject(JsonKeys.ERROR);
                String message = error.optString(JsonKeys.MESSAGE);
                String code = error.optString(JsonKeys.CODE);
                showToast(code + ": " + message);
                return;
            }
            ArrayList<Contact> contacts = mAdapter.getContacts();
            contacts.clear();
            JSONArray data = result.optJSONArray(JsonKeys.DATA);
            for (int i = 0; i < data.length(); i++) {
                Contact contact = new Contact(data.optJSONObject(i));
                contacts.add(contact);
            }
            mAdapter.notifyDataSetChanged();
        }
    });
}
Also used : JSONObject(org.json.JSONObject) LiveOperationListener(com.microsoft.live.LiveOperationListener) LiveOperation(com.microsoft.live.LiveOperation) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) ProgressDialog(android.app.ProgressDialog) LiveOperationException(com.microsoft.live.LiveOperationException)

Aggregations

JSONArray (org.json.JSONArray)1710 JSONObject (org.json.JSONObject)1191 JSONException (org.json.JSONException)738 ArrayList (java.util.ArrayList)323 IOException (java.io.IOException)243 Test (org.junit.Test)207 HashMap (java.util.HashMap)108 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)96 List (java.util.List)63 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)61 File (java.io.File)54 HashSet (java.util.HashSet)54 Date (java.util.Date)47 Query (org.b3log.latke.repository.Query)47 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 GraphObject (com.abewy.android.apps.klyph.core.graph.GraphObject)43 FileNotFoundException (java.io.FileNotFoundException)40 Map (java.util.Map)40 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)36 VolleyError (com.android.volley.VolleyError)35