Search in sources :

Example 6 with JSONArray

use of org.json.JSONArray in project zeppelin by apache.

the class HttpBasedClient method search.

@Override
public ActionResponse search(String[] indices, String[] types, String query, int size) {
    ActionResponse response = null;
    if (!StringUtils.isEmpty(query)) {
        // So, try to parse as a JSON => if there is an error, consider the query a Lucene one
        try {
            gson.fromJson(query, Map.class);
        } catch (final JsonParseException e) {
            // This is not a JSON (or maybe not well formatted...)
            query = QUERY_STRING_TEMPLATE.replace("_Q_", query);
        }
    }
    try {
        final HttpRequestWithBody request = Unirest.post(getUrl(indices, types) + "/_search?size=" + size).header("Content-Type", "application/json");
        if (StringUtils.isNoneEmpty(query)) {
            request.header("Accept", "application/json").body(query);
        }
        if (StringUtils.isNotEmpty(username)) {
            request.basicAuth(username, password);
        }
        final HttpResponse<JsonNode> result = request.asJson();
        final JSONObject body = result.getBody() != null ? result.getBody().getObject() : null;
        if (isSucceeded(result)) {
            final long total = getFieldAsLong(result, "hits/total");
            response = new ActionResponse().succeeded(true).totalHits(total);
            if (containsAggs(result)) {
                JSONObject aggregationsMap = body.getJSONObject("aggregations");
                if (aggregationsMap == null) {
                    aggregationsMap = body.getJSONObject("aggs");
                }
                for (final String key : aggregationsMap.keySet()) {
                    final JSONObject aggResult = aggregationsMap.getJSONObject(key);
                    if (aggResult.has("buckets")) {
                        // Multi-bucket aggregations
                        final Iterator<Object> buckets = aggResult.getJSONArray("buckets").iterator();
                        while (buckets.hasNext()) {
                            response.addAggregation(new AggWrapper(AggregationType.MULTI_BUCKETS, buckets.next().toString()));
                        }
                    } else {
                        response.addAggregation(new AggWrapper(AggregationType.SIMPLE, aggregationsMap.toString()));
                    }
                    // Keep only one aggregation
                    break;
                }
            } else if (size > 0 && total > 0) {
                final JSONArray hits = getFieldAsArray(body, "hits/hits");
                final Iterator<Object> iter = hits.iterator();
                while (iter.hasNext()) {
                    final JSONObject hit = (JSONObject) iter.next();
                    final Object data = hit.opt("_source") != null ? hit.opt("_source") : hit.opt("fields");
                    response.addHit(new HitWrapper(hit.getString("_index"), hit.getString("_type"), hit.getString("_id"), data.toString()));
                }
            }
        } else {
            throw new ActionException(body.get("error").toString());
        }
    } catch (final UnirestException e) {
        throw new ActionException(e);
    }
    return response;
}
Also used : JSONArray(org.json.JSONArray) ActionException(org.apache.zeppelin.elasticsearch.action.ActionException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) JsonNode(com.mashape.unirest.http.JsonNode) AggWrapper(org.apache.zeppelin.elasticsearch.action.AggWrapper) JsonParseException(com.google.gson.JsonParseException) ActionResponse(org.apache.zeppelin.elasticsearch.action.ActionResponse) HitWrapper(org.apache.zeppelin.elasticsearch.action.HitWrapper) JSONObject(org.json.JSONObject) HttpRequestWithBody(com.mashape.unirest.request.HttpRequestWithBody) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject)

Example 7 with JSONArray

use of org.json.JSONArray in project zeppelin by apache.

the class HttpBasedClient method get.

@Override
public ActionResponse get(String index, String type, String id) {
    ActionResponse response = null;
    try {
        final HttpRequest request = Unirest.get(getUrl(index, type, id, true));
        if (StringUtils.isNotEmpty(username)) {
            request.basicAuth(username, password);
        }
        final HttpResponse<String> result = request.asString();
        final boolean isSucceeded = isSucceeded(result);
        if (isSucceeded) {
            final JsonNode body = new JsonNode(result.getBody());
            if (body.getObject().has("_index")) {
                response = new ActionResponse().succeeded(true).hit(new HitWrapper(getFieldAsString(body, "_index"), getFieldAsString(body, "_type"), getFieldAsString(body, "_id"), getFieldAsString(body, "_source")));
            } else {
                final JSONArray hits = getFieldAsArray(body.getObject(), "hits/hits");
                final JSONObject hit = (JSONObject) hits.iterator().next();
                response = new ActionResponse().succeeded(true).hit(new HitWrapper(hit.getString("_index"), hit.getString("_type"), hit.getString("_id"), hit.opt("_source").toString()));
            }
        } else {
            if (result.getStatus() == 404) {
                response = new ActionResponse().succeeded(false);
            } else {
                throw new ActionException(result.getBody());
            }
        }
    } catch (final UnirestException e) {
        throw new ActionException(e);
    }
    return response;
}
Also used : HttpRequest(com.mashape.unirest.request.HttpRequest) HitWrapper(org.apache.zeppelin.elasticsearch.action.HitWrapper) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ActionException(org.apache.zeppelin.elasticsearch.action.ActionException) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) JsonNode(com.mashape.unirest.http.JsonNode) ActionResponse(org.apache.zeppelin.elasticsearch.action.ActionResponse)

Example 8 with JSONArray

use of org.json.JSONArray in project glide by bumptech.

the class PhotoJsonStringParser method parse.

List<Photo> parse(String response) throws JSONException {
    JSONObject searchResults = new JSONObject(response.substring(FLICKR_API_PREFIX_LENGTH, response.length() - 1));
    JSONArray photos = searchResults.getJSONObject("photos").getJSONArray("photo");
    List<Photo> results = new ArrayList<>(photos.length());
    for (int i = 0, size = photos.length(); i < size; i++) {
        results.add(new Photo(photos.getJSONObject(i)));
    }
    return results;
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList)

Example 9 with JSONArray

use of org.json.JSONArray in project clutchandroid by clutchio.

the class ClutchSync method background.

public static void background(final ClutchStats clutchStats) {
    ArrayList<StatRow> logs = clutchStats.getLogs();
    if (logs.size() == 0) {
        return;
    }
    final StatRow lastRow = logs.get(logs.size() - 1);
    JSONArray jsonLogs = new JSONArray();
    for (StatRow row : logs) {
        JSONObject rowObj = new JSONObject();
        try {
            rowObj.put("uuid", row.uuid);
            rowObj.put("ts", row.ts);
            rowObj.put("action", row.action);
            rowObj.put("data", row.data);
        } catch (JSONException e1) {
            // TODO: Don't discard the row.
            Log.e(TAG, "Could not properly encode the logs into JSON for upload to Clutch. Discarding the row.");
            continue;
        }
        jsonLogs.put(rowObj);
    }
    HashMap<String, JSONArray> params = new HashMap<String, JSONArray>();
    params.put("logs", jsonLogs);
    ClutchAPIClient.callMethod("stats", params, new ClutchAPIResponseHandler() {

        @Override
        public void onSuccess(JSONObject response) {
            if ("ok".equals(response.optString("status"))) {
                clutchStats.deleteLogs(lastRow.ts);
            } else {
                Log.e(TAG, "Failed to send the Clutch stats logs to the server.");
            }
        }

        @Override
        public void onFailure(Throwable e, JSONObject errorResponse) {
            Log.e(TAG, "Failed to send logs to Clutch: " + errorResponse);
        }
    });
}
Also used : StatRow(com.clutch.ClutchStats.StatRow) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 10 with JSONArray

use of org.json.JSONArray in project clutchandroid by clutchio.

the class ClutchAB method sendABLogs.

private static void sendABLogs() {
    ArrayList<ABRow> logs = stats.getABLogs();
    if (logs.size() == 0) {
        return;
    }
    final ABRow lastRow = logs.get(logs.size() - 1);
    JSONArray jsonLogs = new JSONArray();
    for (ABRow row : logs) {
        JSONObject rowObj = new JSONObject();
        try {
            rowObj.put("uuid", row.uuid);
            rowObj.put("ts", row.ts);
            rowObj.put("data", row.data);
        } catch (JSONException e1) {
            // TODO: Don't discard the row.
            Log.e(TAG, "Could not properly encode the AB logs into JSON for upload to Clutch. Discarding the row.");
            continue;
        }
        jsonLogs.put(rowObj);
    }
    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("logs", jsonLogs);
    params.put("guid", ClutchAPIClient.getFakeGUID());
    ClutchAPIClient.callMethod("send_ab_logs", params, new ClutchAPIResponseHandler() {

        @Override
        public void onSuccess(JSONObject response) {
            if ("ok".equals(response.optString("status"))) {
                stats.deleteABLogs(lastRow.ts);
            } else {
                Log.e(TAG, "Failed to send the Clutch AB logs to the server.");
            }
        }

        @Override
        public void onFailure(Throwable e, JSONObject errorResponse) {
            Log.e(TAG, "Failed to send AB logs to Clutch: " + errorResponse);
        }
    });
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ABRow(com.clutch.ClutchStats.ABRow) JSONObject(org.json.JSONObject)

Aggregations

JSONArray (org.json.JSONArray)1596 JSONObject (org.json.JSONObject)1121 JSONException (org.json.JSONException)690 ArrayList (java.util.ArrayList)303 IOException (java.io.IOException)232 Test (org.junit.Test)199 HashMap (java.util.HashMap)105 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)96 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)61 List (java.util.List)59 HashSet (java.util.HashSet)53 File (java.io.File)49 Query (org.b3log.latke.repository.Query)47 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 Date (java.util.Date)44 GraphObject (com.abewy.android.apps.klyph.core.graph.GraphObject)43 Map (java.util.Map)40 FileNotFoundException (java.io.FileNotFoundException)37 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)36 VolleyError (com.android.volley.VolleyError)35