List of usage examples for com.google.gson JsonElement isJsonNull
public boolean isJsonNull()
From source file:org.apache.twill.internal.json.JsonUtils.java
License:Apache License
/** * Returns a String representation of the given property. *//*from w w w. j a v a 2s. c o m*/ public static String getAsString(JsonObject json, String property) { JsonElement jsonElement = json.get(property); if (jsonElement == null || jsonElement.isJsonNull()) { return null; } if (jsonElement.isJsonPrimitive()) { return jsonElement.getAsString(); } return jsonElement.toString(); }
From source file:org.apache.twill.internal.json.TwillSpecificationCodec.java
License:Apache License
@Override public TwillSpecification deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObj = json.getAsJsonObject(); String name = jsonObj.get("name").getAsString(); Map<String, RuntimeSpecification> runnables = context.deserialize(jsonObj.get("runnables"), new TypeToken<Map<String, RuntimeSpecification>>() { }.getType());/*from w ww.j a va 2 s. com*/ List<TwillSpecification.Order> orders = context.deserialize(jsonObj.get("orders"), new TypeToken<List<TwillSpecification.Order>>() { }.getType()); List<TwillSpecification.PlacementPolicy> placementPolicies = context.deserialize( jsonObj.get("placementPolicies"), new TypeToken<List<TwillSpecification.PlacementPolicy>>() { }.getType()); JsonElement handler = jsonObj.get("handler"); EventHandlerSpecification eventHandler = null; if (handler != null && !handler.isJsonNull()) { eventHandler = context.deserialize(handler, EventHandlerSpecification.class); } return new DefaultTwillSpecification(name, runnables, orders, placementPolicies, eventHandler); }
From source file:org.coding.git.api.CodingNetConnection.java
License:Apache License
@NotNull private ResponsePage doRequest(@NotNull String uri, @Nullable String requestBody, @NotNull Collection<Header> headers, @NotNull HttpVerb verb) throws IOException { if (myAborted) throw new CodingNetOperationCanceledException(); if (EventQueue.isDispatchThread() && !ApplicationManager.getApplication().isUnitTestMode()) { LOG.warn("Network operation in EDT"); // TODO: fix }//from w ww . ja v a2 s .c o m CloseableHttpResponse response = null; try { response = doREST(uri, requestBody, headers, verb); if (myAborted) throw new CodingNetOperationCanceledException(); //--HTTP?? checkStatusCode(response, requestBody); HttpEntity entity = response.getEntity(); if (entity == null) { return createResponse(response); } JsonElement ret = parseResponse(entity.getContent()); if (ret.isJsonNull()) { return createResponse(response); } //--CodingNet?? checkCodingNetCode(ret); String nextPage = null; Header pageHeader = response.getFirstHeader("Link"); if (pageHeader != null) { for (HeaderElement element : pageHeader.getElements()) { NameValuePair rel = element.getParameterByName("rel"); if (rel != null && "next".equals(rel.getValue())) { String urlString = element.toString(); int begin = urlString.indexOf('<'); int end = urlString.lastIndexOf('>'); if (begin == -1 || end == -1) { LOG.error("Invalid 'Link' header", "{" + pageHeader.toString() + "}"); break; } nextPage = urlString.substring(begin + 1, end); break; } } } return createResponse(ret, nextPage, response); } catch (SSLHandshakeException e) { // User canceled operation from CertificateManager if (e.getCause() instanceof CertificateException) { LOG.info("Host SSL certificate is not trusted", e); throw new CodingNetOperationCanceledException("Host SSL certificate is not trusted", e); } throw e; } catch (IOException e) { if (myAborted) throw new CodingNetOperationCanceledException("Operation canceled", e); throw e; } finally { myRequest = null; if (response != null) { response.close(); } if (!myReusable) { myClient.close(); } } }
From source file:org.couchbase.mock.subdoc.Path.java
License:Apache License
public void validateComponentType(int ix, JsonElement parent) throws PathMismatchException { Component comp = components.get(ix); if (parent.isJsonPrimitive() || parent.isJsonNull()) { throw new PathMismatchException(); }/*ww w. jav a 2 s .c o m*/ if (comp.isIndex()) { if (!parent.isJsonArray()) { throw new PathMismatchException(); } } else { if (!parent.isJsonObject()) { throw new PathMismatchException(); } } }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.impl.jest.ElasticSearchJestClient.java
License:Apache License
/** * Parses a given value (for a given column type) returned by response JSON query body from EL server. * * @param column The data column definition. * @param valueElement The value element from JSON query response to format. * @return The formatted value for the given column type. */// w w w. j a v a 2s . c o m public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata, DataColumn column, JsonElement valueElement) { if (column == null || valueElement == null || valueElement.isJsonNull()) return null; if (!valueElement.isJsonPrimitive()) throw new RuntimeException("Not expected JsonElement type to parse from query response."); JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive(); ColumnType columnType = column.getColumnType(); if (ColumnType.NUMBER.equals(columnType)) { return valueElement.getAsDouble(); } else if (ColumnType.DATE.equals(columnType)) { // We can expect two return core types from EL server when handling dates: // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations. // 2.- Numeric type, when it's result from a scalar function or a value pickup. if (valuePrimitive.isString()) { DateTimeFormatter formatter = null; String datePattern = metadata.getFieldPattern(column.getId()); if (datePattern == null || datePattern.trim().length() == 0) { // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER; } else { // Obtain the date value by parsing using the EL pattern specified for this field. formatter = DateTimeFormat.forPattern(datePattern); } DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString()); return dateTime.toDate(); } if (valuePrimitive.isNumber()) { return new Date(valuePrimitive.getAsLong()); } throw new UnsupportedOperationException( "Value core type not supported. Expecting string or number when using date core field types."); } // LABEL, TEXT or grouped DATE column types. String valueAsString = valueElement.getAsString(); ColumnGroup columnGroup = column.getColumnGroup(); // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1") if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy()) && valueAsString.startsWith("0")) return valueAsString.substring(1); return valueAsString; }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClient.java
License:Apache License
/** * Parses a given value (for a given column type) returned by response JSON query body from EL server. * * @param column The data column definition. * @param valueElement The value element from JSON query response to format. * @return The object value for the given column type. *///from w ww .java 2 s . c o m public Object parseValue(DataSetMetadata metadata, DataColumn column, JsonElement valueElement) throws ParseException { if (column == null || valueElement == null || valueElement.isJsonNull()) return null; if (!valueElement.isJsonPrimitive()) throw new RuntimeException("Not expected JsonElement type to parse from query response."); ElasticSearchDataSetDef def = (ElasticSearchDataSetDef) metadata.getDefinition(); JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive(); ColumnType columnType = column.getColumnType(); if (ColumnType.TEXT.equals(columnType)) { return typeMapper.parseText(def, column.getId(), valueElement.getAsString()); } else if (ColumnType.LABEL.equals(columnType)) { boolean isColumnGroup = column.getColumnGroup() != null && column.getColumnGroup().getStrategy().equals(GroupStrategy.FIXED); return typeMapper.parseLabel(def, column.getId(), valueElement.getAsString(), isColumnGroup); } else if (ColumnType.NUMBER.equals(columnType)) { return typeMapper.parseNumeric(def, column.getId(), valueElement.getAsString()); } else if (ColumnType.DATE.equals(columnType)) { // We can expect two return core types from EL server when handling dates: // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations. // 2.- Numeric type, when it's result from a scalar function or a value pickup. if (valuePrimitive.isString()) { return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsString()); } if (valuePrimitive.isNumber()) { return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsLong()); } } throw new UnsupportedOperationException("Cannot parse value for column with id [" + column.getId() + "] (Data Set UUID [" + def.getUUID() + "]). Value core type not supported. Expecting string or number or date core field types."); }
From source file:org.debux.webmotion.server.call.ClientSession.java
License:Open Source License
/** * Return only JsonElement use getAttribute and getAttributes with class as * parameter to get a value./*from w w w . j a v a 2 s . c o m*/ */ @Override public Object getAttribute(String name) { JsonElement value = attributes.get(name); if (value == null) { return value; } else if (value.isJsonPrimitive()) { JsonPrimitive primitive = value.getAsJsonPrimitive(); if (primitive.isString()) { return primitive.getAsString(); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { return primitive.getAsDouble(); } } else if (value.isJsonArray()) { return value.getAsJsonArray(); } else if (value.isJsonObject()) { return value.getAsJsonObject(); } else if (value.isJsonNull()) { return value.getAsJsonNull(); } return value; }
From source file:org.dmu.expertiserecognition.doiResults.java
private doiResults extractFullAuthorList(String jsonresp, String alt) throws Exception { doiResults dr = new doiResults(standardizeAuthorName(alt)); ArrayList<String> strlst = new ArrayList<>(); JsonElement json = new JsonParser().parse(jsonresp); JsonArray array = json.getAsJsonArray(); if (array.iterator().hasNext() == false) { return dr; }//from ww w.jav a2s . c om JsonElement elem = array.iterator().next(); JsonObject jsonobj = elem.getAsJsonObject(); String coins = URLDecoder.decode(jsonobj.get("coins").getAsString(), "UTF-8"); String[] coinlist = coins.split("&"); int i; String[] pair; for (i = 0; i < coinlist.length; i++) { pair = coinlist[i].split("="); if ((pair.length >= 2) && (pair[0].trim().equalsIgnoreCase("rft.au"))) { strlst.add(standardizeAuthorName(pair[1])); } } dr.authList = strlst; StringBuilder sb = new StringBuilder("<a href=\""); sb.append(jsonobj.get("doi").getAsString()); sb.append("\" target=\"_blank\">"); sb.append(jsonobj.get("fullCitation").getAsString()); sb.append("</a>"); dr.citation = sb.toString(); // Adding "year" field verification; it may come as null // (translated by Gson as a JsonNull field) JsonElement year = jsonobj.get("year"); if (year == null || year.isJsonNull()) { dr.year = "N/A"; } else { dr.year = year.getAsString(); } return dr; }
From source file:org.dmu.expertiserecognition.ScopusServlet.java
public static boolean checkJsonElement(JsonElement jobj) { if (jobj == null) return false; return !jobj.isJsonNull(); }
From source file:org.dspace.handle.MultiRemoteDSpaceRepositoryHandlePlugin.java
License:BSD License
private String getRemoteDSpaceURL(String handle) throws HandleException { if (log.isInfoEnabled()) { log.info("Called getRemoteDSpaceURL(" + handle + ")."); }/*from ww w. j a v a2 s . c o m*/ InputStreamReader jsonStreamReader = null; String url = null; try { String prefix = handle.split("/")[0]; String endpoint = this.prefixes.get(prefix); if (endpoint == null) { if (log.isDebugEnabled()) { log.debug("Cannot find endpoint for prefix " + prefix + ", throw HANDLE_DOES_NOT_EXIST."); } throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST); } String jsonurl = endpoint + "/resolve/" + handle; jsonStreamReader = new InputStreamReader(new URL(jsonurl).openStream(), "UTF-8"); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(jsonStreamReader); if (jsonElement == null || jsonElement.isJsonNull() || jsonElement.getAsJsonArray().size() == 0 || jsonElement.getAsJsonArray().get(0).isJsonNull()) { if (log.isDebugEnabled()) { log.debug("Throw HandleException: HANDLE_DOES_NOT_EXIST."); } throw new HandleException(HandleException.HANDLE_DOES_NOT_EXIST); } url = jsonElement.getAsJsonArray().get(0).getAsString(); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Exception in getRawHandleValues", e); } // Stack loss as exception does not support cause throw new HandleException(HandleException.INTERNAL_ERROR); } finally { if (jsonStreamReader != null) { try { jsonStreamReader.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } if (log.isDebugEnabled()) { log.debug(("getRemoteDspaceURL returns " + url)); } return url; }