List of usage examples for com.google.gson JsonElement isJsonObject
public boolean isJsonObject()
From source file:club.jmint.crossing.specs.ParamBuilder.java
License:Apache License
public static String checkSignAndRemove(String p, String signKey) throws CrossException { JsonParser jp = new JsonParser(); JsonElement jop = null; try {/*w w w . j av a 2 s.co m*/ jop = jp.parse(p); if (!jop.isJsonObject()) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } } catch (JsonSyntaxException jse) { //jse.printStackTrace(); throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } JsonObject jo = (JsonObject) jop; String np = null; if (jo.has("sign") || jo.has("params")) { String sign = jo.getAsJsonPrimitive("sign").getAsString(); np = jo.getAsJsonObject("params").toString(); String signValue = Security.crossingSign(np, signKey, ""); if (!sign.equals(signValue)) { throw new CrossException(ErrorCode.COMMON_ERR_SIGN_BAD.getCode(), ErrorCode.COMMON_ERR_SIGN_BAD.getInfo()); } //remove sign field only and return Iterator<Entry<String, JsonElement>> it = jo.entrySet().iterator(); JsonObject rjo = new JsonObject(); Entry<String, JsonElement> en; while (it.hasNext()) { en = it.next(); if (!en.getKey().equals("sign")) { rjo.add(en.getKey(), en.getValue()); } } return rjo.toString(); } return p; }
From source file:club.jmint.crossing.specs.ParamBuilder.java
License:Apache License
public static String buildDecryptedParams(String encryptParams, String decryptKey) throws CrossException { JsonParser jp = new JsonParser(); JsonElement jop = null; try {/*from w w w . j a va 2 s . c om*/ jop = jp.parse(encryptParams); if (!jop.isJsonObject()) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } } catch (JsonSyntaxException jse) { //jse.printStackTrace(); throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } JsonObject jo = (JsonObject) jop; String np = null; if (jo.has("encrypted")) { String encrypted = jo.getAsJsonPrimitive("encrypted").getAsString(); String paramsValue = Security.crossingDecrypt(encrypted, decryptKey, "DES"); int ec = jo.getAsJsonPrimitive("errorCode").getAsInt(); String ed = jo.getAsJsonPrimitive("errorInfo").getAsString(); JsonParser jpr = new JsonParser(); JsonObject jor = null; try { jor = (JsonObject) jpr.parse(paramsValue); } catch (JsonSyntaxException je) { throw new CrossException(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); } jor.addProperty("errorCode", ec); jor.addProperty("errorInfo", ed); np = jor.toString(); return np; } return encryptParams; }
From source file:club.jmint.mifty.service.MiftyService.java
License:Apache License
public String callProxy(String method, String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")"); JsonObject ip;//w ww . j av a 2 s . c o m try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //extract all parameters HashMap<String, String> inputMap = new HashMap<String, String>(); Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator(); Entry<String, JsonElement> en = null; String key; JsonElement je; while (it.hasNext()) { en = it.next(); key = en.getKey(); je = en.getValue(); if (je.isJsonArray()) { inputMap.put(key, je.getAsJsonArray().toString()); //System.out.println(je.getAsJsonArray().toString()); } else if (je.isJsonNull()) { inputMap.put(key, je.getAsJsonNull().toString()); //System.out.println(je.getAsJsonNull().toString()); } else if (je.isJsonObject()) { inputMap.put(key, je.getAsJsonObject().toString()); //System.out.println(je.getAsJsonObject().toString()); } else if (je.isJsonPrimitive()) { inputMap.put(key, je.getAsJsonPrimitive().getAsString()); //System.out.println(je.getAsJsonPrimitive().toString()); } else { //unkown type; } } //execute specific method Method[] ma = this.getClass().getMethods(); int idx = 0; for (int i = 0; i < ma.length; i++) { if (ma[i].getName().equals(method)) { idx = i; break; } } HashMap<String, String> outputMap = null; try { Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes()); outputMap = (HashMap<String, String>) m.invoke(this, inputMap); CrossLog.logger.debug("callProxy: " + method + "() executed."); } catch (NoSuchMethodException nsm) { CrossLog.logger.error("callProxy: " + method + "() not found."); CrossLog.printStackTrace(nsm); return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(), ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo()); } catch (Exception e) { CrossLog.logger.error("callProxy: " + method + "() executed with exception."); CrossLog.printStackTrace(e); if (e instanceof CrossException) { return buildOutputByCrossException((CrossException) e); } else { return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(), ErrorCode.COMMON_ERR_UNKOWN.getInfo()); } } //if got error then return immediately String ec = outputMap.get("errorCode"); String ecInfo = outputMap.get("errorInfo"); if ((ec != null) && (!ec.isEmpty())) { return buildOutputError(Integer.parseInt(ec), ecInfo); } //build response parameters JsonObject op = new JsonObject(); Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator(); Entry<String, String> eno = null; JsonParser jpo = new JsonParser(); JsonElement jeo = null; while (ito.hasNext()) { eno = ito.next(); try { jeo = jpo.parse(eno.getValue()); } catch (JsonSyntaxException e) { // MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"]."); // return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), // ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); //we do assume that it should be a common string jeo = new JsonPrimitive(eno.getValue()); } op.add(eno.getKey(), jeo); } String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")"); return output; }
From source file:co.cask.cdap.common.conf.PluginClassDeserializer.java
License:Apache License
@Override public PluginClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("PluginClass should be a JSON Object"); }// w ww . ja va2 s . com JsonObject jsonObj = json.getAsJsonObject(); String type = jsonObj.has("type") ? jsonObj.get("type").getAsString() : Plugin.DEFAULT_TYPE; String name = getRequired(jsonObj, "name").getAsString(); String description = jsonObj.has("description") ? jsonObj.get("description").getAsString() : ""; String className = getRequired(jsonObj, "className").getAsString(); Set<String> endpointsSet = new HashSet<>(); if (jsonObj.has("endpoints")) { endpointsSet = context.deserialize(jsonObj.get("endpoints"), ENDPOINTS_TYPE); } Map<String, PluginPropertyField> properties = jsonObj.has("properties") ? context.<Map<String, PluginPropertyField>>deserialize(jsonObj.get("properties"), PROPERTIES_TYPE) : ImmutableMap.<String, PluginPropertyField>of(); return new PluginClass(type, name, description, className, null, properties, endpointsSet); }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceAssignmentTypeAdapter.java
License:Apache License
@Override public ResourceAssignment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("Expect a json object, got " + json); }/*from w ww .j a v a2s. c o m*/ JsonObject jsonObj = json.getAsJsonObject(); String name = jsonObj.get("name").getAsString(); Multimap<Discoverable, PartitionReplica> assignments = TreeMultimap .create(DiscoverableComparator.COMPARATOR, PartitionReplica.COMPARATOR); JsonArray assignmentsJson = context.deserialize(jsonObj.get("assignments"), JsonArray.class); for (JsonElement element : assignmentsJson) { if (!element.isJsonArray()) { throw new JsonParseException("Expect a json array, got " + element); } JsonArray entryJson = element.getAsJsonArray(); if (entryJson.size() != 2) { throw new JsonParseException("Expect json array of size = 2, got " + entryJson.size()); } Discoverable key = context.deserialize(entryJson.get(0), Discoverable.class); PartitionReplica value = context.deserialize(entryJson.get(1), PartitionReplica.class); assignments.put(key, value); } return new ResourceAssignment(name, assignments); }
From source file:co.cask.cdap.notifications.NotificationFeedInfoDeserializer.java
License:Apache License
@Override public NotificationFeedInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); String category = obj.get("category").getAsString(); JsonElement descriptionElement = obj.get("description"); String description = descriptionElement == null ? "" : descriptionElement.getAsString(); String namespace;//from w ww . ja v a 2s .co m String feed; JsonElement namespaceElement = obj.get("namespace"); // this means its the old Id.NotificationFeed object where namespace is something like "namespace":{"id":"default"} if (namespaceElement.isJsonObject()) { namespace = namespaceElement.getAsJsonObject().get("id").getAsString(); feed = obj.get("name").getAsString(); } else { namespace = namespaceElement.getAsString(); feed = obj.get("feed").getAsString(); } return new NotificationFeedInfo(namespace, category, feed, description); }
From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java
License:Apache License
public ValueObject fromGson(JsonElement gson) { if (gson.isJsonNull()) { return null; } else if (gson.isJsonObject()) { JsonObject object = gson.getAsJsonObject(); ValueMap map = ValueFactory.createMap(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { map.put(entry.getKey(), fromGson(entry.getValue())); }// w ww . jav a2 s . co m return map; } else if (gson.isJsonArray()) { JsonArray gsonArray = gson.getAsJsonArray(); ValueArray valueArray = ValueFactory.createArray(gsonArray.size()); for (JsonElement arrayElement : gsonArray) { valueArray.add(fromGson(arrayElement)); } return valueArray; } else { JsonPrimitive primitive = gson.getAsJsonPrimitive(); if (primitive.isNumber()) { return ValueFactory.create(primitive.getAsDouble()); } else { return ValueFactory.create(primitive.getAsString()); } } }
From source file:com.adkdevelopment.jokesactivity.JokesActivityFragment.java
License:Open Source License
/** * Method to parse JSON string and return String[] with a link and a title * * @param jokesJson JSON string with info about comics, link, etc. * @return String[] with a link and a title */// w ww. j av a 2 s . c om public static String[] getJokesInfo(String jokesJson) { String[] reviews = new String[2]; JsonParser parser = new JsonParser(); JsonElement element = parser.parse(jokesJson); if (element.isJsonObject()) { JsonObject results = element.getAsJsonObject(); JsonElement title = results.getAsJsonPrimitive("title"); JsonElement linkToImage = results.getAsJsonPrimitive("img"); reviews[0] = title.getAsString(); reviews[1] = linkToImage.getAsString(); return reviews; } return null; }
From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java
License:Apache License
/** * Create or update resources from remote JSON. * * @param json JsonObject/* w ww .j a v a 2s. c om*/ * @param resource Resource * @throws IOException exception * @throws RepositoryException exception */ private void createOrUpdateNodes(final ResourceResolver remoteAssetsResolver, final JsonObject json, final Resource resource) throws IOException, RepositoryException { for (Map.Entry<String, JsonElement> jsonEntry : json.entrySet()) { JsonElement jsonElement = jsonEntry.getValue(); if (jsonElement.isJsonObject()) { createOrUpdateNodesForJsonObject(remoteAssetsResolver, jsonEntry.getKey(), resource); } else if (jsonElement.isJsonArray()) { setNodeArrayProperty(remoteAssetsResolver, jsonEntry.getKey(), jsonElement.getAsJsonArray(), resource); } else { setNodeProperty(remoteAssetsResolver, jsonEntry.getKey(), json, resource); } } }
From source file:com.ai2020lab.aiutils.common.JsonUtils.java
License:Apache License
/** * ?JsonObject/*from ww w. jav a2s. co m*/ * * @param jsonStr * @return JsonObject */ public JsonObject stringToJsonObj(String jsonStr) { // JSON if (jsonStr == null || jsonStr.equals("")) { throw new IllegalArgumentException("???JsonObject?"); } JsonElement jsonE = null; try { jsonE = jsonParser.parse(jsonStr); } catch (Exception e) { // JSON?JSON?? LogUtils.e(TAG, " ??JsonObject"); } if (jsonE == null || !jsonE.isJsonObject()) { // ?JsonObject? LogUtils.e(TAG, "??JsonObject??JsonObject?"); return null; } return (JsonObject) jsonE; }