List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
From source file:com.cloudant.client.api.Database.java
License:Open Source License
/** * Set permissions for a user/apiKey on this database. * <p>/*from w ww. j a va2s. c om*/ * Note this method is only applicable to databases that support the * <a href="http://docs.cloudant.com/authorization.html"> * Cloudant authorization API * </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security * endpoint. * </p> * * @param userNameorApikey * @param permissions permissions to grant * @throws UnsupportedOperationException if called on a database that does not provide the * Cloudant authorization API * @see <a href="http://docs.cloudant.com/authorization.html#roles">Roles</a> * @see <a href="http://docs.cloudant.com/authorization.html#modifying-permissions">Modifying * permissions</a> */ public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) { assertNotEmpty(userNameorApikey, "userNameorApikey"); assertNotEmpty(permissions, "permissions"); final JsonArray jsonPermissions = new JsonArray(); for (Permissions s : permissions) { final JsonPrimitive permission = new JsonPrimitive(s.toString()); jsonPermissions.add(permission); } // get existing permissions JsonObject perms = getPermissionsObject(); // now set back JsonElement elem = perms.get("cloudant"); if (elem == null) { perms.addProperty("_id", "_security"); elem = new JsonObject(); perms.add("cloudant", elem); } elem.getAsJsonObject().add(userNameorApikey, jsonPermissions); HttpResponse response = null; HttpPut put = new HttpPut(apiV2DBSecurityURI); setEntity(put, client.getGson().toJson(perms), "application/json"); try { response = executeRequest(put); String ok = getAsString(response, "ok"); if (!ok.equalsIgnoreCase("true")) { //raise exception } } finally { close(response); } }
From source file:com.cloudant.client.api.Database.java
License:Open Source License
/** * Find documents using an index/* w w w. j a va 2 s. co m*/ * * @param selectorJson JSON object describing criteria used to select documents. * Is of the form <code>"selector": {<your data here>} </code> * @param options {@link FindByIndexOptions query Index options} * @param classOfT The class of Java objects to be returned * @return List of classOfT objects * @see <a href="http://docs.cloudant.com/api/cloudant-query.html#cloudant-query-selectors"> * selector syntax</a> */ public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions options) { assertNotEmpty(selectorJson, "selectorJson"); assertNotEmpty(options, "options"); URI uri = buildUri(getDBUri()).path("_find").build(); String body = getFindByIndexBody(selectorJson, options); InputStream stream = null; try { stream = getStream(client.executeRequest(createPost(uri, body, "application/json"))); Reader reader = new InputStreamReader(stream, "UTF-8"); JsonArray jsonArray = new JsonParser().parse(reader).getAsJsonObject().getAsJsonArray("docs"); List<T> list = new ArrayList<T>(); for (JsonElement jsonElem : jsonArray) { JsonElement elem = jsonElem.getAsJsonObject(); T t = client.getGson().fromJson(elem, classOfT); list.add(t); } return list; } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } finally { close(stream); } }
From source file:com.cloudant.client.api.Database.java
License:Open Source License
public List<Shard> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final List<Shard> shards = new ArrayList<Shard>(); final JsonObject jsonObject = json.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> shardsObj = jsonObject.get("shards").getAsJsonObject().entrySet(); for (Entry<String, JsonElement> entry : shardsObj) { String range = entry.getKey(); List<String> nodeNames = context.deserialize(entry.getValue(), new TypeToken<List<String>>() { }.getType());//from w w w . j a va2 s .c o m shards.add(new Shard(range, nodeNames)); } return shards; }
From source file:com.cloudant.client.api.Database.java
License:Open Source License
public List<Index> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final List<Index> indices = new ArrayList<Index>(); final JsonObject jsonObject = json.getAsJsonObject(); JsonArray indArray = jsonObject.get("indexes").getAsJsonArray(); for (int i = 0; i < indArray.size(); i++) { JsonObject ind = indArray.get(i).getAsJsonObject(); String ddoc = null;/*w ww . java 2 s . c o m*/ if (!ind.get("ddoc").isJsonNull()) { // ddoc is optional ddoc = ind.get("ddoc").getAsString(); } Index idx = new Index(ddoc, ind.get("name").getAsString(), ind.get("type").getAsString()); JsonArray fldArray = ind.get("def").getAsJsonObject().get("fields").getAsJsonArray(); for (int j = 0; j < fldArray.size(); j++) { Set<Map.Entry<String, JsonElement>> fld = fldArray.get(j).getAsJsonObject().entrySet(); for (Entry<String, JsonElement> entry : fld) { idx.addIndexField(entry.getKey(), SortOrder.valueOf(entry.getValue().getAsString())); } } //end fldArray indices.add(idx); } // end indexes return indices; }
From source file:com.cloudant.client.api.Database.java
License:Open Source License
public Map<String, EnumSet<Permissions>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Map<String, EnumSet<Permissions>> perms = new HashMap<String, EnumSet<Permissions>>(); JsonElement elem = json.getAsJsonObject().get("cloudant"); if (elem == null) { return perms; }/*from w ww. j ava 2 s .c o m*/ Set<Map.Entry<String, JsonElement>> permList = elem.getAsJsonObject().entrySet(); for (Entry<String, JsonElement> entry : permList) { String user = entry.getKey(); EnumSet<Permissions> p = context.deserialize(entry.getValue(), new TypeToken<EnumSet<Permissions>>() { }.getType()); perms.put(user, p); } return perms; }
From source file:com.cloudant.client.api.DatabaseImpl.java
License:Open Source License
@Override public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) { assertNotEmpty(userNameorApikey, "userNameorApikey"); assertNotEmpty(permissions, "permissions"); final JsonArray jsonPermissions = new JsonArray(); for (Permissions s : permissions) { final JsonPrimitive permission = new JsonPrimitive(s.toString()); jsonPermissions.add(permission); }/* w w w .j a va 2 s.co m*/ // get existing permissions JsonObject perms = getPermissionsObject(); // now set back JsonElement elem = perms.get("cloudant"); if (elem == null) { perms.addProperty("_id", "_security"); elem = new JsonObject(); perms.add("cloudant", elem); } elem.getAsJsonObject().add(userNameorApikey, jsonPermissions); InputStream response = null; HttpConnection put = Http.PUT(apiV2DBSecurityURI, "application/json"); put.setRequestBody(client.getGson().toJson(perms)); try { response = client.couchDbClient.executeToInputStream(put); String ok = getAsString(response, "ok"); if (!ok.equalsIgnoreCase("true")) { //raise exception } } finally { close(response); } }
From source file:com.cloudant.client.api.DatabaseImpl.java
License:Open Source License
@Override public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions options) { assertNotEmpty(selectorJson, "selectorJson"); assertNotEmpty(options, "options"); URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build(); JsonObject body = getFindByIndexBody(selectorJson, options); InputStream stream = null;/* w w w . j a v a2 s . co m*/ try { stream = client.couchDbClient .executeToInputStream(createPost(uri, body.toString(), "application/json")); Reader reader = new InputStreamReader(stream, "UTF-8"); JsonArray jsonArray = new JsonParser().parse(reader).getAsJsonObject().getAsJsonArray("docs"); List<T> list = new ArrayList<T>(); for (JsonElement jsonElem : jsonArray) { JsonElement elem = jsonElem.getAsJsonObject(); T t = client.getGson().fromJson(elem, classOfT); list.add(t); } return list; } catch (UnsupportedEncodingException e) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e); } finally { close(stream); } }
From source file:com.cloudant.client.api.Search.java
License:Open Source License
/** * Queries a Search Index and returns grouped results in a map where key * of the map is the groupName. In case the query didnt use grouping, * an empty map is returned/*from ww w . j a v a 2 s . c o m*/ * * @param <T> Object type T * @param query the Lucene query to be passed to the Search index * @param classOfT The class of type T * @return The result of the grouped search query as a ordered {@code Map<String,T> } */ public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) { InputStream instream = null; try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); Map<String, List<T>> result = new LinkedHashMap<String, List<T>>(); if (json.has("groups")) { for (JsonElement e : json.getAsJsonArray("groups")) { String groupName = e.getAsJsonObject().get("by").getAsString(); List<T> orows = new ArrayList<T>(); if (!includeDocs) { log.warn("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) { orows.add(JsonToObject(db.getGson(), rows, "doc", classOfT)); } result.put(groupName, orows); } // end for(groups) } // end hasgroups else { log.warn("No grouped results available. Use query() if non grouped query"); } return result; } catch (UnsupportedEncodingException e1) { // This should never happen as every implementation of the java platform is required // to support UTF-8. throw new RuntimeException(e1); } finally { close(instream); } }
From source file:com.cloudant.client.api.Search.java
License:Open Source License
private <T> List<SearchResult<T>.SearchResultRows> getRows(JsonArray jsonrows, SearchResult<T> sr, Class<T> classOfT) { List<SearchResult<T>.SearchResultRows> ret = new ArrayList<SearchResult<T>.SearchResultRows>(); for (JsonElement e : jsonrows) { SearchResult<T>.SearchResultRows row = sr.new SearchResultRows(); JsonObject oe = e.getAsJsonObject(); row.setId(oe.get("id").getAsString()); row.setOrder(JsonToObject(db.getGson(), e, "order", Object[].class)); row.setFields(JsonToObject(db.getGson(), e, "fields", classOfT)); if (includeDocs) { row.setDoc(JsonToObject(db.getGson(), e, "doc", classOfT)); }//from www . j a va 2 s . c om ret.add(row); } return ret; }
From source file:com.cloudant.client.api.Search.java
License:Open Source License
private <T> void setGroups(JsonArray jsongroups, SearchResult<T> sr, Class<T> classOfT) { for (JsonElement e : jsongroups) { SearchResult<T>.SearchResultGroups group = sr.new SearchResultGroups(); JsonObject oe = e.getAsJsonObject(); group.setBy(oe.get("by").getAsString()); group.setTotalRows(oe.get("total_rows").getAsLong()); group.setRows(getRows(oe.getAsJsonArray("rows"), sr, classOfT)); sr.getGroups().add(group);/*from w w w. j a va 2 s .c o m*/ } }