List of usage examples for com.google.gson JsonObject has
public boolean has(String memberName)
From source file:com.atlauncher.data.mojang.DownloadsTypeAdapter.java
License:Open Source License
@Override public Downloads deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { DownloadsItem artifact = null;//from ww w.jav a 2 s. com Map<String, DownloadsItem> classifiers = new HashMap<String, DownloadsItem>(); final JsonObject rootJsonObject = json.getAsJsonObject(); if (rootJsonObject.has("artifact")) { final JsonObject artifactObject = rootJsonObject.getAsJsonObject("artifact"); artifact = Gsons.DEFAULT_ALT.fromJson(artifactObject, DownloadsItem.class); } if (rootJsonObject.has("classifiers")) { final JsonObject classifiersObject = rootJsonObject.getAsJsonObject("classifiers"); Set<Entry<String, JsonElement>> entrySet = classifiersObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entrySet) { classifiers.put(entry.getKey(), Gsons.DEFAULT_ALT.fromJson(entry.getValue().getAsJsonObject(), DownloadsItem.class)); } } return new Downloads(artifact, classifiers); }
From source file:com.autoclavestudios.jbower.config.internal.JsonRegistryTranslator.java
License:Apache License
@Override public Registry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Registry registry = new Registry(); try {//from w w w . j a v a 2s . c o m if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("search")) registry.search(ConvertToArray(jsonObject.get("search").getAsJsonArray())); if (jsonObject.has("publish")) registry.publish(ConvertToArray(jsonObject.get("publish").getAsJsonArray())); if (jsonObject.has("register")) registry.register(ConvertToArray(jsonObject.get("register").getAsJsonArray())); } else if (json.isJsonPrimitive()) { registry.all(json.getAsString()); } else { throw new JsonParseException("Registry object is not a Json Object or Primitive"); } } catch (MalformedURLException e) { logger.error("Malformed URL: {}", json.getAsString()); } return registry; }
From source file:com.azure.webapi.LoginManager.java
License:Open Source License
/** * Creates a User based on a Windows Azure Mobile Service JSON object * containing a UserId and Authentication Token * //from w ww . j a v a 2s . c om * @param json * JSON object used to create the User * @return The created user if it is a valid JSON object. Null otherwise * @throws MobileServiceException */ private MobileServiceUser createUserFromJSON(JsonObject json) throws MobileServiceException { if (json == null) { throw new IllegalArgumentException("json can not be null"); } // If the JSON object is valid, create a MobileServiceUser object if (json.has(USER_JSON_PROPERTY)) { JsonObject jsonUser = json.getAsJsonObject(USER_JSON_PROPERTY); if (!jsonUser.has(USERID_JSON_PROPERTY)) { throw new JsonParseException(USERID_JSON_PROPERTY + " property expected"); } String userId = jsonUser.get(USERID_JSON_PROPERTY).getAsString(); MobileServiceUser user = new MobileServiceUser(userId); if (!json.has(TOKEN_JSON_PARAMETER)) { throw new JsonParseException(TOKEN_JSON_PARAMETER + " property expected"); } user.setAuthenticationToken(json.get(TOKEN_JSON_PARAMETER).getAsString()); return user; } else { // If the JSON contains an error property show it, otherwise raise // an error with JSON content if (json.has("error")) { throw new MobileServiceException(json.get("error").getAsString()); } else { throw new JsonParseException(json.toString()); } } }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Removes the Id property from a JsonObject * //from ww w . j a v a2 s . co m * @param json * The JsonObject to modify */ private void removeIdFromJson(final JsonObject json) { // Remove id property if exists String[] idPropertyNames = new String[] { "id", "Id", "iD", "ID" }; for (int i = 0; i < 4; i++) { String idProperty = idPropertyNames[i]; if (json.has(idProperty)) { JsonElement idElement = json.get(idProperty); if (isValidTypeId(idElement) && idElement.getAsInt() != 0) { throw new InvalidParameterException( "The entity to insert should not have " + idProperty + " property defined"); } json.remove(idProperty); } } }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Updates an element from a Mobile Service Table * //from w ww. j a v a 2 s. co m * @param element * The JsonObject to update * @param parameters * A list of user-defined parameters and values to include in the request URI query string * @param callback * Callback to invoke when the operation is completed */ public void update(final JsonObject element, final List<Pair<String, String>> parameters, final TableJsonOperationCallback callback) { try { updateIdProperty(element); if (!element.has("id") || element.get("id").getAsInt() == 0) { throw new IllegalArgumentException( "You must specify an id property with a valid value for updating an object."); } } catch (Exception e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } String content = element.toString(); ServiceFilterRequest putRequest; try { Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon(); uriBuilder.path(TABLES_URL); //This needs to reference to "api/" uriBuilder.appendPath(URLEncoder.encode(mTableName, MobileServiceClient.UTF8_ENCODING)); uriBuilder.appendPath(Integer.valueOf(getObjectId(element)).toString()); if (parameters != null && parameters.size() > 0) { for (Pair<String, String> parameter : parameters) { uriBuilder.appendQueryParameter(parameter.first, parameter.second); } } putRequest = new ServiceFilterRequestImpl(new HttpPut(uriBuilder.build().toString())); putRequest.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE); } catch (UnsupportedEncodingException e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } try { putRequest.setContent(content); } catch (Exception e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } executeTableOperation(putRequest, new TableJsonOperationCallback() { // TODO webapi is different in response. It return status code only @Override public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) { if (callback != null) { if (exception == null && jsonEntity != null) { JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, jsonEntity); callback.onCompleted(patchedJson, exception, response); } else { callback.onCompleted(jsonEntity, exception, response); } } } }); }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Retrieves a set of rows from using the specified URL * //from w w w .j a v a 2 s . c o m * @param query * The URL used to retrieve the rows * @param callback * Callback to invoke when the operation is completed */ private void executeGetRecords(final String url, final TableJsonQueryCallback callback) { ServiceFilterRequest request = new ServiceFilterRequestImpl(new HttpGet(url)); MobileServiceConnection conn = mClient.createConnection(); // Create AsyncTask to execute the request and parse the results new RequestAsyncTask(request, conn) { @Override protected void onPostExecute(ServiceFilterResponse response) { if (callback != null) { if (mTaskException == null && response != null) { JsonElement results = null; int count = 0; try { // Parse the results using the given Entity class String content = response.getContent(); JsonElement json = new JsonParser().parse(content); if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); // If the response has count property, store its // value if (jsonObject.has("results") && jsonObject.has("count")) { // inlinecount // result count = jsonObject.get("count").getAsInt(); results = jsonObject.get("results"); } else { results = json; } } else { results = json; } } catch (Exception e) { callback.onCompleted(null, 0, new MobileServiceException("Error while retrieving data from response.", e), response); return; } callback.onCompleted(results, count, null, response); } else { callback.onCompleted(null, 0, mTaskException, response); } } } }.execute(); }
From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java
License:Open Source License
/** * A recursive merge of two json elements. * * @param source1 the first json element * @param source2 the second json element * @param mergeArray the flag to denote if arrays should be merged * @return the recursively merged json element *//*from ww w .j ava2s.c o m*/ public JsonElement merge(JsonElement source1, JsonElement source2, Boolean mergeArray) { mergeArray = null == mergeArray ? Boolean.FALSE : mergeArray; JsonElement result = JsonNull.INSTANCE; source1 = asJsonElement(source1, JsonNull.INSTANCE); source2 = asJsonElement(source2, JsonNull.INSTANCE); if (source1.getClass().equals(source2.getClass())) { if (source1.isJsonObject()) { JsonObject obj1 = asJsonObject(source1); JsonObject obj2 = asJsonObject(source2); result = obj1; JsonObject resultObj = result.getAsJsonObject(); for (Entry<String, JsonElement> entry : obj1.entrySet()) { String key = entry.getKey(); JsonElement value1 = entry.getValue(); JsonElement value2 = obj2.get(key); JsonElement merge = merge(value1, value2, mergeArray); resultObj.add(key, merge); } for (Entry<String, JsonElement> entry : obj2.entrySet()) { String key = entry.getKey(); if (!resultObj.has(key)) { resultObj.add(key, entry.getValue()); } } } else if (source1.isJsonArray()) { result = new JsonArray(); JsonArray resultArray = result.getAsJsonArray(); JsonArray array1 = asJsonArray(source1); JsonArray array2 = asJsonArray(source2); int index = 0; int a1size = array1.size(); int a2size = array2.size(); if (!mergeArray) { for (; index < a1size && index < a2size; index++) { resultArray.add(merge(array1.get(index), array2.get(index), mergeArray)); } } for (; index < a1size; index++) { resultArray.add(array1.get(index)); } index = mergeArray ? 0 : index; for (; index < a2size; index++) { resultArray.add(array2.get(index)); } } else { result = source1 != null ? source1 : source2; } } else { result = isNotNull(source1) ? source1 : source2; } return result; }
From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java
License:Open Source License
public static void copyBucketBetweenSystems(RiakCSClient fromSystem, String fromBucket, RiakCSClient toSystem, String toBucket) throws RiakCSException { try {//from w w w.ja v a2s . c om JsonObject response = fromSystem.listObjectNames(fromBucket); JsonArray resultList = response.getAsJsonArray("objectList"); System.out.println("Number of Objects to transfer: " + resultList.size() + "\n"); for (int pt = 0; pt < resultList.size(); pt++) { String key = resultList.get(pt).getAsJsonObject().get("key").getAsString(); File tempFile = File.createTempFile("cscopy-", ".bin"); //Retrieve Object FileOutputStream outputStream = new FileOutputStream(tempFile); JsonObject objectData = fromSystem.getObject(fromBucket, key, outputStream); outputStream.close(); //Upload Object Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", objectData.get("contenttype").getAsString()); Map<String, String> metadata = null; if (objectData.has("metadata") && !objectData.getAsJsonObject("metadata").entrySet().isEmpty()) { metadata = new HashMap<String, String>(); Set<Map.Entry<String, JsonElement>> metadataRaw = objectData.getAsJsonObject("metadata") .entrySet(); for (Map.Entry<String, JsonElement> entry : metadataRaw) { metadata.put(entry.getKey(), entry.getValue().getAsString()); } } FileInputStream inputStream = new FileInputStream(tempFile); toSystem.createObject(toBucket, key, inputStream, headers, metadata); inputStream.close(); tempFile.delete(); } } catch (Exception e) { throw new RiakCSException(e); } }
From source file:com.betafase.mcmanager.api.SpigotUpdateChecker.java
@Override public UpdateInfo checkUpdate() { ServerRequest r = new ServerRequest("resources/" + spigot_id + "/versions?sort=-name"); JsonElement e = r.getAsJsonElement(); if (e.isJsonArray()) { JsonObject current = e.getAsJsonArray().get(0).getAsJsonObject(); String version = current.get("name").getAsString(); if (!version.equalsIgnoreCase(plugin.getDescription().getVersion())) { UpdateInfo info = new UpdateInfo(plugin, null, version, "8Update found via SpigotUpdater", current.has("url") ? current.get("url").getAsString() : null) { @Override//w w w . j a v a2 s . c o m public void performUpdate(Player notifier) { SpigetPlugin d = new SpigetPlugin(spigot_id); d.loadInformation(); if (d.hasDirectDownload()) { notifier.sendMessage( "aCached Download from spiget.org found. Downloading directly..."); d.downloadDirectly(notifier, "plugins/" + getJarName()); } else if (d.isExternalDownload()) { notifier.sendMessage( "clError elThis Plugin has an external download. You must download it manually: " + d.getDownloadURL()); } else { notifier.sendMessage("aDownload started. Please wait..."); notifier.performCommand("wget plugins " + d.getDownloadURL()); } } }; return info; } } else { System.out.println("Could not check update for " + plugin.getName() + " : " + r.getAsString()); } return null; }
From source file:com.bizosys.dataservice.sql.KVPairsSerde.java
License:Apache License
public static final void deserJson(final String jsonStr, final Map<String, String> container) { if (StringUtils.isEmpty(jsonStr)) return;/*ww w . j a v a 2 s . c o m*/ Gson gson = new Gson(); JsonElement jsonElem = gson.fromJson(jsonStr, JsonElement.class); JsonObject jsonObj = jsonElem.getAsJsonObject(); if (!jsonObj.has("variables")) return; Iterator<JsonElement> variablesIterator = jsonObj.get("variables").getAsJsonArray().iterator(); while (variablesIterator.hasNext()) { JsonObject variableObj = (JsonObject) variablesIterator.next(); if (variableObj.has("key") && variableObj.has("value")) { String varKey = variableObj.get("key").getAsString(); JsonElement obj = variableObj.get("value"); String varVal = (obj.isJsonNull()) ? null : obj.getAsString(); container.put(varKey, varVal); } } if (LOG.isDebugEnabled()) LOG.debug("Parsed variables are : " + container.toString()); }