List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
From source file:org.ireas.intuition.IntuitionLoader.java
License:Open Source License
private Optional<JsonObject> getDomainObject(final JsonElement element) { Optional<JsonObject> domainObject = Optional.absent(); // two types of valid responses: // (1) {"messages": {"<domain>": { } } } // --> messages found // (2) {"messages": {"<domain>": false} } // --> no messages available if (!element.isJsonObject()) { throw new IllegalArgumentException(); }/* w ww. java 2s . c om*/ JsonObject rootObject = element.getAsJsonObject(); if (!rootObject.has(KEY_MESSAGES)) { throw new IllegalArgumentException(); } JsonElement messagesElement = rootObject.get(KEY_MESSAGES); if (!messagesElement.isJsonObject()) { throw new IllegalArgumentException(); } JsonObject messagesObject = messagesElement.getAsJsonObject(); if (!messagesObject.has(domain)) { throw new IllegalArgumentException(); } JsonElement domainElement = messagesObject.get(domain); if (domainElement.isJsonObject()) { // valid response (1): messages found domainObject = Optional.of(domainElement.getAsJsonObject()); } else if (domainElement.isJsonPrimitive()) { JsonPrimitive domainPrimitive = domainElement.getAsJsonPrimitive(); if (!domainPrimitive.isBoolean()) { throw new IllegalArgumentException(); } boolean domainBoolean = domainPrimitive.getAsBoolean(); if (domainBoolean) { throw new IllegalArgumentException(); } // valid response (2): no messages available } else { throw new IllegalArgumentException(); } return domainObject; }
From source file:org.ireas.intuition.IntuitionLoader.java
License:Open Source License
private Map<String, String> parseMessages(final JsonObject jsonObject) { Map<String, String> messages = new HashMap<>(); Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet(); for (Entry<String, JsonElement> entry : entrySet) { String key = entry.getKey(); JsonElement element = entry.getValue(); if (element.isJsonPrimitive()) { String value = element.getAsString(); messages.put(key, value);//from w w w .j av a 2 s .c o m } } return messages; }
From source file:org.jboss.aerogear.android.authorization.oauth2.OAuth2AuthzService.java
License:Apache License
private void runAccountAction(OAuth2AuthzSession storedAccount, OAuth2Properties config, final Map<String, String> data, URL endpoint) throws OAuth2AuthorizationException { try {/* w w w . j a va 2 s. c om*/ final HttpProvider provider = getHttpProvider(endpoint); final String formTemplate = "%s=%s"; provider.setDefaultHeader("Content-Type", "application/x-www-form-urlencoded"); final StringBuilder bodyBuilder = new StringBuilder(); String amp = ""; for (Map.Entry<String, String> entry : data.entrySet()) { bodyBuilder.append(amp); try { bodyBuilder.append(String.format(formTemplate, entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } amp = "&"; } HeaderAndBody headerAndBody; try { headerAndBody = provider.post(bodyBuilder.toString().getBytes("UTF-8")); } catch (HttpException exception) { if (exception.getStatusCode() == HttpURLConnection.HTTP_BAD_REQUEST) { JsonElement response = new JsonParser().parse(new String(exception.getData())); JsonObject jsonResponseObject = response.getAsJsonObject(); String error = ""; if (jsonResponseObject.has("error")) { JsonElement errorObject = jsonResponseObject.get("error"); if (errorObject.isJsonPrimitive()) { error = errorObject.getAsString(); } else { error = errorObject.toString(); } } throw new OAuth2AuthorizationException(error); } else { throw exception; } } String responseString = new String(headerAndBody.getBody()); try { JsonElement response = new JsonParser().parse(responseString); JsonObject jsonResponseObject = response.getAsJsonObject(); String accessToken = jsonResponseObject.get("access_token").getAsString(); storedAccount.setAccessToken(accessToken); // Will need to check this one day // String tokenType = jsonResponseObject.get("token_type").getAsString(); if (jsonResponseObject.has("expires_in")) { Long expiresIn = jsonResponseObject.get("expires_in").getAsLong(); Long expires_on = new Date().getTime() + expiresIn * 1000; storedAccount.setExpires_on(expires_on); } if (jsonResponseObject.has("refresh_token")) { String refreshToken = jsonResponseObject.get("refresh_token").getAsString(); if (!isNullOrEmpty(refreshToken)) { storedAccount.setRefreshToken(refreshToken); } } } catch (JsonParseException parseEx) { try { //Check if body is http form format String[] values = responseString.split("&"); for (String pair : values) { String property[] = pair.split("="); String key = property[0]; String value = property[1]; if ("access_token".equals(key)) { storedAccount.setAccessToken(value); } else if ("expires_in".equals(key)) { Long expiresIn = Long.parseLong(value); Long expires_on = new Date().getTime() + expiresIn * 1000; storedAccount.setExpires_on(expires_on); } else if ("refresh_token".equals(key)) { if (!isNullOrEmpty(value)) { storedAccount.setRefreshToken(value); } } } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); throw new OAuth2AuthorizationException(responseString); } } storedAccount.setAuthorizationCode(""); } catch (UnsupportedEncodingException ex) { // Should never happen... Log.d(OAuth2AuthzService.class.getName(), null, ex); throw new RuntimeException(ex); } }
From source file:org.jboss.aerogear.android.impl.datamanager.SQLStore.java
License:Apache License
private void saveElement(JsonObject serialized, String path, Serializable id) { String sql = String.format( "insert into %s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)", className); Set<Entry<String, JsonElement>> members = serialized.entrySet(); String pathVar = path.isEmpty() ? "" : "."; for (Entry<String, JsonElement> member : members) { JsonElement jsonValue = member.getValue(); String propertyName = member.getKey(); if (jsonValue.isJsonObject()) { saveElement((JsonObject) jsonValue, path + pathVar + propertyName, id); } else {/*from w ww. j av a2 s . c om*/ if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { Integer value = primitive.getAsBoolean() ? 1 : 0; database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else if (primitive.isString()) { String value = primitive.getAsString(); database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else { throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive"); } } } }
From source file:org.jboss.aerogear.android.impl.datamanager.SQLStore.java
License:Apache License
private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) { Set<Entry<String, JsonElement>> keys = where.entrySet(); String pathVar = parentPath.isEmpty() ? "" : ".";//Set a dot if parent path is not empty for (Entry<String, JsonElement> entry : keys) { String key = entry.getKey(); String path = parentPath + pathVar + key; JsonElement jsonValue = entry.getValue(); if (jsonValue.isJsonObject()) { buildKeyValuePairs((JsonObject) jsonValue, keyValues, path); } else {//w w w. j av a 2s . co m if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { Integer value = primitive.getAsBoolean() ? 1 : 0; keyValues.add(new Pair<String, String>(path, value.toString())); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); keyValues.add(new Pair<String, String>(path, value.toString())); } else if (primitive.isString()) { String value = primitive.getAsString(); keyValues.add(new Pair<String, String>(path, value)); } else { throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive"); } } } }
From source file:org.jboss.aerogear.android.store.sql.SQLStore.java
License:Apache License
private void saveElement(JsonElement serialized, String path, Serializable id) { String sql = String.format( "insert into %s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)", className); if (serialized.isJsonObject()) { Set<Entry<String, JsonElement>> members = ((JsonObject) serialized).entrySet(); String pathVar = path.isEmpty() ? "" : "."; for (Entry<String, JsonElement> member : members) { JsonElement jsonValue = member.getValue(); String propertyName = member.getKey(); if (jsonValue.isJsonArray()) { JsonArray jsonArray = jsonValue.getAsJsonArray(); for (int index = 0; index < jsonArray.size(); index++) { saveElement(jsonArray.get(index), path + pathVar + propertyName + String.format("[%d]", index), id); }// w w w . ja v a2s .c o m } else { saveElement(jsonValue, path + pathVar + propertyName, id); } } } else if (serialized.isJsonPrimitive()) { JsonPrimitive primitive = serialized.getAsJsonPrimitive(); if (primitive.isBoolean()) { String value = primitive.getAsBoolean() ? "true" : "false"; database.execSQL(sql, new Object[] { path, value, id }); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); database.execSQL(sql, new Object[] { path, value, id }); } else if (primitive.isString()) { String value = primitive.getAsString(); database.execSQL(sql, new Object[] { path, value, id }); } else { throw new IllegalArgumentException(serialized + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(serialized + " isn't a JsonObject or JsonPrimitive"); } }
From source file:org.jboss.aerogear.android.store.sql.SQLStore.java
License:Apache License
private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) { Set<Entry<String, JsonElement>> keys = where.entrySet(); String pathVar = parentPath.isEmpty() ? "" : ".";// Set a dot if parent path is not empty for (Entry<String, JsonElement> entry : keys) { String key = entry.getKey(); String path = parentPath + pathVar + key; JsonElement jsonValue = entry.getValue(); if (jsonValue.isJsonObject()) { buildKeyValuePairs((JsonObject) jsonValue, keyValues, path); } else {//from www . j a v a2 s . c om if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { String value = primitive.getAsBoolean() ? "true" : "false"; keyValues.add(new Pair<String, String>(path, value)); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); keyValues.add(new Pair<String, String>(path, value.toString())); } else if (primitive.isString()) { String value = primitive.getAsString(); keyValues.add(new Pair<String, String>(path, value)); } else { throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive"); } } } }
From source file:org.jbpm.form.builder.services.encoders.FormRepresentationDecoderImpl.java
License:Apache License
private Object fromJsonValue(JsonElement elem) { if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isString()) { return elem.getAsString(); } else if (elem.isJsonPrimitive() && elem.getAsJsonPrimitive().isNumber()) { return elem.getAsNumber(); } else if (elem.isJsonArray()) { return asList(elem.getAsJsonArray()); } else if (elem.isJsonNull()) { return null; } else if (elem.isJsonObject()) { return asMap(elem.getAsJsonObject()); } else {//from www.j a va2 s .c o m return ""; } }
From source file:org.jclouds.json.internal.ParseObjectFromElement.java
License:Apache License
public Object apply(JsonElement input) { Object value = null;/* ww w . ja v a2 s. c o m*/ if (input == null || input.isJsonNull()) { value = null; } else if (input.isJsonPrimitive()) { JsonPrimitive primitive = input.getAsJsonPrimitive(); if (primitive.isNumber()) { value = primitive.getAsNumber(); } else if (primitive.isBoolean()) { value = primitive.getAsBoolean(); } else { value = primitive.getAsString(); } } else if (input.isJsonArray()) { value = Lists.newArrayList(Iterables.transform(input.getAsJsonArray(), this)); } else if (input.isJsonObject()) { value = Maps.<String, Object>newLinkedHashMap( Maps.transformValues(JsonObjectAsMap.INSTANCE.apply(input.getAsJsonObject()), this)); } return value; }
From source file:org.jenkinsci.plugins.fod.FoDAPI.java
/** * Given a URL, request, and HTTP client, authenticates with FoD API. * This is just a utility method which uses none of the class member fields. * /* w ww . j a v a 2s. c o m*/ * @param baseUrl URL for FoD * @param request request to authenticate * @param client HTTP client object * @return */ private AuthTokenResponse authorize(String baseUrl, AuthTokenRequest request) { final String METHOD_NAME = CLASS_NAME + ".authorize"; PrintStream out = FodBuilder.getLogger(); AuthTokenResponse response = new AuthTokenResponse(); try { String endpoint = baseUrl + "/oauth/token"; HttpPost httppost = new HttpPost(endpoint); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(CONNECTION_TIMEOUT).build(); httppost.setConfig(requestConfig); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); if (AuthCredentialType.CLIENT_CREDENTIALS.getName().equals(request.getGrantType())) { AuthApiKey cred = (AuthApiKey) request.getPrincipal(); formparams.add(new BasicNameValuePair("scope", FOD_SCOPE_TENANT)); formparams.add(new BasicNameValuePair("grant_type", request.getGrantType())); formparams.add(new BasicNameValuePair("client_id", cred.getClientId())); formparams.add(new BasicNameValuePair("client_secret", cred.getClientSecret())); } else { out.println(METHOD_NAME + ": unrecognized grant type"); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, UTF_8); httppost.setEntity(entity); HttpResponse postResponse = getHttpClient().execute(httppost); StatusLine sl = postResponse.getStatusLine(); Integer statusCode = Integer.valueOf(sl.getStatusCode()); if (statusCode.toString().startsWith("2")) { InputStream is = null; try { HttpEntity respopnseEntity = postResponse.getEntity(); is = respopnseEntity.getContent(); StringBuffer content = collectInputStream(is); String x = content.toString(); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(x); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement tokenElement = jsonObject.getAsJsonPrimitive("access_token"); if (null != tokenElement && !tokenElement.isJsonNull() && tokenElement.isJsonPrimitive()) { response.setAccessToken(tokenElement.getAsString()); } JsonElement expiresIn = jsonObject.getAsJsonPrimitive("expires_in"); Integer expiresInInt = expiresIn.getAsInt(); response.setExpiresIn(expiresInInt); //TODO handle remaining two fields in response } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } EntityUtils.consumeQuietly(postResponse.getEntity()); httppost.releaseConnection(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; }