Search in sources :

Example 71 with JSONException

use of org.json.JSONException in project android-UniversalMusicPlayer by googlesamples.

the class RemoteJSONSource method iterator.

@Override
public Iterator<MediaMetadataCompat> iterator() {
    try {
        int slashPos = CATALOG_URL.lastIndexOf('/');
        String path = CATALOG_URL.substring(0, slashPos + 1);
        JSONObject jsonObj = fetchJSONFromUrl(CATALOG_URL);
        ArrayList<MediaMetadataCompat> tracks = new ArrayList<>();
        if (jsonObj != null) {
            JSONArray jsonTracks = jsonObj.getJSONArray(JSON_MUSIC);
            if (jsonTracks != null) {
                for (int j = 0; j < jsonTracks.length(); j++) {
                    tracks.add(buildFromJSON(jsonTracks.getJSONObject(j), path));
                }
            }
        }
        return tracks.iterator();
    } catch (JSONException e) {
        LogHelper.e(TAG, e, "Could not retrieve music list");
        throw new RuntimeException("Could not retrieve music list", e);
    }
}
Also used : MediaMetadataCompat(android.support.v4.media.MediaMetadataCompat) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 72 with JSONException

use of org.json.JSONException in project gdk-compass-sample by googleglass.

the class Landmarks method populatePlaceList.

/**
     * Populates the internal places list from places found in a JSON string. This string should
     * contain a root object with a "landmarks" property that is an array of objects that represent
     * places. A place has three properties: name, latitude, and longitude.
     */
private void populatePlaceList(String jsonString) {
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray array = json.optJSONArray("landmarks");
        if (array != null) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.optJSONObject(i);
                Place place = jsonObjectToPlace(object);
                if (place != null) {
                    mPlaces.add(place);
                }
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Could not parse landmarks JSON string", e);
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 73 with JSONException

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

the class JsonObjectRequest method readInputStream.

/**
   * Helper method to read an HTTP response.
   * @param is The InputStream.
   * @return An object representing the HTTP response.
   */
protected JSONObject readInputStream(InputStream is) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String line;
    while ((line = in.readLine()) != null) {
        stringBuilder.append(line);
    }
    JSONObject jsonObject;
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException error) {
        throw new IOException(error.toString());
    }
    return jsonObject;
}
Also used : InputStreamReader(java.io.InputStreamReader) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 74 with JSONException

use of org.json.JSONException 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 75 with JSONException

use of org.json.JSONException 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)

Aggregations

JSONException (org.json.JSONException)1904 JSONObject (org.json.JSONObject)1422 JSONArray (org.json.JSONArray)638 IOException (java.io.IOException)338 ArrayList (java.util.ArrayList)211 HashMap (java.util.HashMap)145 Test (org.junit.Test)128 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)98 File (java.io.File)77 Bundle (android.os.Bundle)75 VolleyError (com.android.volley.VolleyError)67 Intent (android.content.Intent)63 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)62 Response (com.android.volley.Response)59 URL (java.net.URL)57 Map (java.util.Map)48 TextView (android.widget.TextView)46 View (android.view.View)45 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 MalformedURLException (java.net.MalformedURLException)44