List of usage examples for com.google.gson JsonObject has
public boolean has(String memberName)
From source file:com.chiwanpark.flume.plugins.handler.JSONHandler.java
License:Apache License
/** * {@inheritDoc}// w w w. j a v a2 s. c om */ @Override public Event getEvent(String message) throws Exception { /* * Gson throws Exception if the data is not parseable to JSON. * Need not catch it since the source will catch it and return error. */ JsonObject json = parser.parse(message).getAsJsonObject(); String body = ""; JsonElement bodyElm = json.get("body"); if (bodyElm != null) { body = bodyElm.getAsString(); } Map<String, String> headers = null; if (json.has("headers")) { headers = new HashMap<String, String>(); for (Map.Entry<String, JsonElement> header : json.get("headers").getAsJsonObject().entrySet()) { if (header.getValue().isJsonPrimitive()) { headers.put(header.getKey(), header.getValue().getAsString()); } else { // If a header is not a json primitive (it contains subfields), // we have to use toString() to get it as valid json. headers.put(header.getKey(), header.getValue().toString()); } } } return EventBuilder.withBody(body.getBytes(charset), headers); }
From source file:com.chiwanpark.flume.plugins.JSONHandler.java
License:Apache License
/** * {@inheritDoc}// w w w .j av a2 s. c om */ @Override public Event getEvent(String message) throws Exception { /* * Gson throws Exception if the data is not parseable to JSON. * Need not catch it since the source will catch it and return error. */ JsonObject json = parser.parse(message).getAsJsonObject(); String body = ""; JsonElement bodyElm = json.get("body"); if (bodyElm != null) { body = bodyElm.toString(); } HashMap<String, String> headers = null; if (json.has("headers")) { headers = new HashMap<String, String>(); for (Map.Entry<String, JsonElement> header : json.get("headers").getAsJsonObject().entrySet()) { if (header.getValue().isJsonPrimitive()) { headers.put(header.getKey(), header.getValue().getAsString()); } else { // If a header is not a json primitive (it contains subfields), // we have to use toString() to get it as valid json. headers.put(header.getKey(), header.getValue().toString()); } } } return EventBuilder.withBody(body.getBytes(charset), headers); }
From source file:com.cinchapi.concourse.importer.LineBasedImporter.java
License:Apache License
/** * Import the data contained in {@code file} into {@link Concourse}. * <p>//from w w w . ja v a 2s .c o m * <strong>Note</strong> that if {@code resolveKey} is specified, an attempt * will be made to add the data in from each group into the existing records * that are found using {@code resolveKey} and its corresponding value in * the group. * </p> * * @param file * @param resolveKey * @return a collection of {@link ImportResult} objects that describes the * records created/affected from the import and whether any errors * occurred. */ public final Set<Long> importFile(String file, @Nullable String resolveKey) { // TODO add option to specify batchSize, which is how many objects to // send over the wire in one atomic batch List<String> lines = FileOps.readLines(file); String[] keys = header(); JsonArray array = new JsonArray(); boolean checkedFileFormat = false; for (String line : lines) { if (!checkedFileFormat) { validateFileFormat(line); checkedFileFormat = true; } if (keys == null) { keys = parseKeys(line); log.info("Parsed keys from header: " + line); } else { JsonObject object = parseLine(line, keys); if (resolveKey != null && object.has(resolveKey)) { JsonElement resolveValue = object.get(resolveKey); if (!resolveValue.isJsonArray()) { JsonArray temp = new JsonArray(); temp.add(resolveValue); resolveValue = temp; } for (int i = 0; i < resolveValue.getAsJsonArray().size(); ++i) { String value = resolveValue.getAsJsonArray().get(i).toString(); Object stored = Convert.stringToJava(value); Set<Long> resolved = concourse.find(resolveKey, Operator.EQUALS, stored); for (long record : resolved) { object = parseLine(line, keys); // this is // inefficient, but // there is no good // way to clone the // original object object.addProperty(Constants.JSON_RESERVED_IDENTIFIER_NAME, record); array.add(object); } } } else { array.add(object); } log.info("Importing {}", line); } } Set<Long> records = importString(array.toString()); return records; }
From source file:com.claresco.tinman.json.JsonUtility.java
License:Open Source License
protected static boolean hasElement(JsonObject theObject, String theKey) { if (theObject.has(theKey)) { if (!isJsonElementNull(get(theObject, theKey))) { return true; }//from www . j a v a 2 s . c o m } return false; }
From source file:com.claresco.tinman.json.XapiAgentJson.java
License:Open Source License
@Override public XapiAgent deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { JsonObject localJsonObject = JsonUtility.convertJsonElementToJsonObject(arg0); // This to handles if the member of a group is another group if (localJsonObject.has("objectType")) { if (JsonUtility.getElementAsString(localJsonObject, "objectType").equals("Group")) { throw new XapiBadGroupException("A group must not have another group as its member"); }/*ww w . j a va2s. co m*/ } // Find the name of the agent String theName = JsonUtility.getElementAsString(localJsonObject, "name"); // Delegate the inverse functional identifier XapiInverseFunctionalIdentifier theID = JsonUtility.delegateDeserialization(arg2, arg0, XapiInverseFunctionalIdentifier.class); XapiAgent theAgent = new XapiAgent(theName, theID); // Check if there is indeed an identifier if (!theAgent.isValid()) { throw new XapiBadAgentException("Identifier must not be null"); } return theAgent; }
From source file:com.claresco.tinman.json.XapiGroupJson.java
License:Open Source License
@Override public XapiGroup deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { JsonObject theJsonGroup = JsonUtility.convertJsonElementToJsonObject(arg0); String theName = JsonUtility.getElementAsString(theJsonGroup, "name"); JsonArray theJsonMember = null;/* ww w . ja va 2s. c om*/ // Retrieve member as JsonArray if (theJsonGroup.has("member")) { theJsonMember = theJsonGroup.get("member").getAsJsonArray(); } XapiAgent[] theMember = null; // Initialize an array of agents if (theJsonMember != null) { theMember = new XapiAgent[theJsonMember.size()]; // Iterate through the JsonArray for (int i = 0; i < theMember.length; i++) { theMember[i] = JsonUtility.delegateDeserialization(arg2, theJsonMember.get(i), XapiAgent.class); } } XapiInverseFunctionalIdentifier theId = JsonUtility.delegateDeserialization(arg2, arg0, XapiInverseFunctionalIdentifier.class); XapiGroup theGroup = new XapiGroup(theName, theMember, theId); if (!theGroup.isValid()) { throw new XapiBadGroupException("The group is not valid"); } return theGroup; }
From source file:com.cloudant.client.api.DatabaseImpl.java
License:Open Source License
private JsonObject getFindByIndexBody(String selectorJson, FindByIndexOptions options) { JsonArray fieldsArray = new JsonArray(); if (options.getFields().size() > 0) { for (String field : options.getFields()) { JsonPrimitive jsonField = client.getGson().fromJson(field, JsonPrimitive.class); fieldsArray.add(jsonField);//w ww. ja va 2 s . c om } } JsonArray sortArray = new JsonArray(); if (options.getSort().size() > 0) { for (IndexField sort : options.getSort()) { JsonObject sortObject = new JsonObject(); sortObject.addProperty(sort.getName(), sort.getOrder().toString()); sortArray.add(sortObject); } } JsonObject indexObject = new JsonObject(); //parse and find if valid json issue #28 JsonObject selectorObject = null; boolean isObject = true; try { selectorObject = getGson().fromJson(selectorJson, JsonObject.class); } catch (JsonParseException e) { isObject = false; } if (!isObject) { if (selectorJson.startsWith("\"selector\"")) { selectorJson = selectorJson.substring(selectorJson.indexOf(":") + 1, selectorJson.length()).trim(); selectorObject = getGson().fromJson(selectorJson, JsonObject.class); } else { throw new JsonParseException("selectorJson should be valid json or like " + "\"selector\": {...} "); } } if (selectorObject.has("selector")) { indexObject.add("selector", selectorObject.get("selector")); } else { indexObject.add("selector", selectorObject); } if (fieldsArray.size() > 0) { indexObject.add("fields", fieldsArray); } if (sortArray.size() > 0) { indexObject.add("sort", sortArray); } if (options.getLimit() != null) { indexObject.addProperty("limit", options.getLimit()); } if (options.getSkip() != null) { indexObject.addProperty("skip", options.getSkip()); } if (options.getReadQuorum() != null) { indexObject.addProperty("r", options.getReadQuorum()); } if (options.getUseIndex() != null) { indexObject.add("use_index", getGson().fromJson(options.getUseIndex(), JsonArray.class)); } return indexObject; }
From source file:com.cloudant.client.api.Search.java
License:Open Source License
/** * Queries a Search Index and returns ungrouped results. In case the query * used grouping, an empty list is returned * * @param <T> Object type T// ww w. j av a 2s. com * @param query the Lucene query to be passed to the Search index * @param classOfT The class of type T * @return The result of the search query as a {@code List<T> } */ public <T> List<T> query(String query, Class<T> classOfT) { InputStream instream = null; List<T> result = new ArrayList<T>(); try { Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8"); JsonObject json = new JsonParser().parse(reader).getAsJsonObject(); if (json.has("rows")) { if (!includeDocs) { log.warn("includeDocs set to false and attempting to retrieve doc. " + "null object will be returned"); } for (JsonElement e : json.getAsJsonArray("rows")) { result.add(JsonToObject(db.getGson(), e, "doc", classOfT)); } } else { log.warn("No ungrouped result available. Use queryGroups() if grouping set"); } 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
/** * 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//w w 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
/** * Performs a Cloudant Search and returns the result as an {@link SearchResult} * * @param <T> Object type T, an instance into which the rows[].doc/group[].rows[].doc * attribute of the Search result response should be deserialized into. Same * goes for the rows[].fields/group[].rows[].fields attribute * @param query the Lucene query to be passed to the Search index * @param classOfT The class of type T./*from ww w. ja va 2s . com*/ * @return The Search result entries */ public <T> SearchResult<T> querySearchResult(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(); SearchResult<T> sr = new SearchResult<T>(); sr.setTotalRows(getAsLong(json, "total_rows")); sr.setBookmark(getAsString(json, "bookmark")); if (json.has("rows")) { sr.setRows(getRows(json.getAsJsonArray("rows"), sr, classOfT)); } else if (json.has("groups")) { setGroups(json.getAsJsonArray("groups"), sr, classOfT); } if (json.has("counts")) { sr.setCounts(getFieldsCounts(json.getAsJsonObject("counts").entrySet())); } if (json.has("ranges")) { sr.setRanges(getFieldsCounts(json.getAsJsonObject("ranges").entrySet())); } return sr; } 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(instream); } }