List of usage examples for com.google.gson JsonElement isJsonObject
public boolean isJsonObject()
From source file:com.flipkart.android.proteus.view.manager.ProteusViewManagerImpl.java
License:Apache License
public void set(String dataPath, JsonElement newValue) { if (dataPath == null) { return;//from w ww .jav a2 s. c o m } String aliasedDataPath = DataContext.getAliasedDataPath(dataPath, dataContext.getReverseScope(), true); Result result = Utils.readJson(aliasedDataPath.substring(0, aliasedDataPath.lastIndexOf(".")), dataContext.getData(), dataContext.getIndex()); JsonElement parent = result.isSuccess() ? result.element : null; if (parent == null || !parent.isJsonObject()) { return; } String propertyName = aliasedDataPath.substring(aliasedDataPath.lastIndexOf(".") + 1, aliasedDataPath.length()); parent.getAsJsonObject().add(propertyName, newValue); update(aliasedDataPath); }
From source file:com.flipkart.polyguice.config.JsonConfiguration.java
License:Apache License
private void load(Reader in) { configTab = new HashMap<>(); JsonStreamParser parser = new JsonStreamParser(in); JsonElement root = null; if (parser.hasNext()) { root = parser.next();/*from w ww.j av a2s . c om*/ } if (root != null && root.isJsonObject()) { flatten(null, root); } LOGGER.debug("json configuration loaded: {}", configTab); }
From source file:com.flipkart.polyguice.config.JsonConfiguration.java
License:Apache License
private void flatten(String prefix, JsonElement element) { if (element.isJsonPrimitive()) { JsonPrimitive jsonPrim = element.getAsJsonPrimitive(); if (jsonPrim.isBoolean()) { configTab.put(prefix, jsonPrim.getAsBoolean()); } else if (jsonPrim.isNumber()) { configTab.put(prefix, jsonPrim.getAsNumber()); } else if (jsonPrim.isString()) { configTab.put(prefix, jsonPrim.getAsString()); }/*from w ww . j a v a 2 s . com*/ } else if (element.isJsonObject()) { JsonObject jsonObj = element.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) { String prefix1 = ((prefix != null) ? prefix + "." : "") + entry.getKey(); flatten(prefix1, entry.getValue()); } } }
From source file:com.fooock.shodan.model.banner.BannerDeserializer.java
License:Open Source License
@Override public List<Banner> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { final List<Banner> banners = new ArrayList<>(); if (json.isJsonNull()) { return banners; }/*w w w.ja v a 2 s .c o m*/ JsonArray jsonArray = json.getAsJsonArray(); if (jsonArray.isJsonNull()) { return banners; } for (JsonElement element : jsonArray) { JsonObject jsonObject = element.getAsJsonObject(); JsonElement port = jsonObject.get("port"); JsonElement ip = jsonObject.get("ip"); JsonElement asn = jsonObject.get("asn"); JsonElement data = jsonObject.get("data"); JsonElement ipStr = jsonObject.get("ip_str"); JsonElement ipv6 = jsonObject.get("ipv6"); JsonElement timestamp = jsonObject.get("timestamp"); JsonElement hostnames = jsonObject.get("hostnames"); JsonElement domains = jsonObject.get("domains"); JsonElement location = jsonObject.get("location"); JsonElement options = jsonObject.get("opts"); JsonElement metadata = jsonObject.get("_shodan"); JsonElement ssl = jsonObject.get("ssl"); JsonElement uptime = jsonObject.get("uptime"); JsonElement link = jsonObject.get("link"); JsonElement title = jsonObject.get("title"); JsonElement html = jsonObject.get("html"); JsonElement product = jsonObject.get("product"); JsonElement version = jsonObject.get("version"); JsonElement isp = jsonObject.get("isp"); JsonElement os = jsonObject.get("os"); JsonElement transport = jsonObject.get("transport"); JsonElement devicetype = jsonObject.get("devicetype"); JsonElement info = jsonObject.get("info"); JsonElement cpe = jsonObject.get("cpe"); final Banner banner = new Banner(); if (port == null || port.isJsonNull()) { banner.setPort(0); } else { banner.setPort(port.getAsInt()); } if (ip == null || ip.isJsonNull()) { banner.setIp(0); } else { banner.setIp(ip.getAsLong()); } if (asn == null || asn.isJsonNull()) { banner.setAsn("unknown"); } else { banner.setAsn(asn.getAsString()); } if (data == null || data.isJsonNull()) { banner.setData("unknown"); } else { banner.setData(data.getAsString()); } if (ipStr == null || ipStr.isJsonNull()) { banner.setIpStr("unknown"); } else { banner.setIpStr(ipStr.getAsString()); } if (ipv6 == null || ipv6.isJsonNull()) { banner.setIpv6("unknown"); } else { banner.setIpv6(ipv6.getAsString()); } if (timestamp == null || timestamp.isJsonNull()) { banner.setTimestamp("unknown"); } else { banner.setTimestamp(timestamp.getAsString()); } if (hostnames == null || hostnames.isJsonNull()) { banner.setHostnames(new String[0]); } else { JsonArray hostnamesAsJsonArray = hostnames.getAsJsonArray(); String[] hostnameArray = new String[hostnamesAsJsonArray.size()]; for (int i = 0; i < hostnamesAsJsonArray.size(); i++) { hostnameArray[i] = hostnamesAsJsonArray.get(i).getAsString(); } banner.setHostnames(hostnameArray); } if (domains == null || domains.isJsonNull()) { banner.setDomains(new String[0]); } else { JsonArray domainsAsJsonArray = domains.getAsJsonArray(); String[] domainsArray = new String[domainsAsJsonArray.size()]; for (int i = 0; i < domainsAsJsonArray.size(); i++) { domainsArray[i] = domainsAsJsonArray.get(i).getAsString(); } banner.setDomains(domainsArray); } if (location == null || location.isJsonNull()) { banner.setLocation(new Location()); } else { JsonObject locationAsJsonObject = location.getAsJsonObject(); JsonElement areaCode = locationAsJsonObject.get("area_code"); JsonElement latitude = locationAsJsonObject.get("latitude"); JsonElement longitude = locationAsJsonObject.get("longitude"); JsonElement city = locationAsJsonObject.get("city"); JsonElement regionCode = locationAsJsonObject.get("region_code"); JsonElement postalCode = locationAsJsonObject.get("postal_code"); JsonElement dmaCode = locationAsJsonObject.get("dma_code"); JsonElement countryCode = locationAsJsonObject.get("country_code"); JsonElement countryCode3 = locationAsJsonObject.get("country_code3"); JsonElement countryName = locationAsJsonObject.get("country_name"); Location locationObject = new Location(); if (areaCode == null || areaCode.isJsonNull()) { locationObject.setAreaCode(0); } else { locationObject.setAreaCode(areaCode.getAsInt()); } if (latitude == null || latitude.isJsonNull()) { locationObject.setLatitude(0.0); } else { locationObject.setLatitude(latitude.getAsDouble()); } if (longitude == null || location.isJsonNull()) { locationObject.setLongitude(0.0); } else { locationObject.setLongitude(longitude.getAsDouble()); } if (city == null || city.isJsonNull()) { locationObject.setCity("unknown"); } else { locationObject.setCity(city.getAsString()); } if (regionCode == null || regionCode.isJsonNull()) { locationObject.setRegionCode("unknown"); } else { locationObject.setRegionCode(regionCode.getAsString()); } if (postalCode == null || postalCode.isJsonNull()) { locationObject.setPostalCode("unknown"); } else { locationObject.setPostalCode(postalCode.getAsString()); } if (dmaCode == null || dmaCode.isJsonNull()) { locationObject.setDmaCode("unknown"); } else { locationObject.setDmaCode(dmaCode.getAsString()); } if (countryCode == null || countryCode.isJsonNull()) { locationObject.setCountryCode("unknown"); } else { locationObject.setCountryCode(countryCode.getAsString()); } if (countryCode3 == null || countryCode3.isJsonNull()) { locationObject.setCountryCode3("unknown"); } else { locationObject.setCountryCode3(countryCode3.getAsString()); } if (countryName == null || countryName.isJsonNull()) { locationObject.setCountryName("unknown"); } else { locationObject.setCountryName(countryName.getAsString()); } banner.setLocation(locationObject); } final Options opts = new Options(); if (options == null || options.isJsonNull()) { opts.setRaw("unknown"); } else { JsonObject object = options.getAsJsonObject(); JsonElement raw = object.get("raw"); if (raw == null || raw.isJsonNull()) { opts.setRaw("unknown"); } else { opts.setRaw(raw.getAsString()); } } banner.setOptions(opts); final Metadata shodanMetadata = new Metadata(); if (metadata == null || metadata.isJsonNull()) { shodanMetadata.setCrawler("unknown"); shodanMetadata.setId("unknown"); shodanMetadata.setModule("unknown"); } else { JsonObject metadataAsJsonObject = metadata.getAsJsonObject(); JsonElement crawler = metadataAsJsonObject.get("crawler"); JsonElement id = metadataAsJsonObject.get("id"); JsonElement module = metadataAsJsonObject.get("module"); if (crawler == null || crawler.isJsonNull()) { shodanMetadata.setCrawler("unknown"); } else { shodanMetadata.setCrawler(crawler.getAsString()); } if (id == null || id.isJsonNull()) { shodanMetadata.setId("unknown"); } else { shodanMetadata.setId(id.getAsString()); } if (module == null || module.isJsonNull()) { shodanMetadata.setModule("unknown"); } else { shodanMetadata.setModule(module.getAsString()); } } banner.setMetadata(shodanMetadata); final SslInfo sslInfo = new SslInfo(); if (ssl == null || ssl.isJsonNull()) { banner.setSslEnabled(false); } else { banner.setSslEnabled(true); JsonObject sslAsJsonObject = ssl.getAsJsonObject(); JsonElement chain = sslAsJsonObject.get("chain"); JsonArray chainAsJsonArray = chain.getAsJsonArray(); String[] chainArray = new String[chainAsJsonArray.size()]; for (int i = 0; i < chainAsJsonArray.size(); i++) { chainArray[i] = chainAsJsonArray.get(i).getAsString(); } sslInfo.setChain(chainArray); JsonElement versions = sslAsJsonObject.get("versions"); JsonArray versionAsJsonArray = versions.getAsJsonArray(); String[] versionsArray = new String[versionAsJsonArray.size()]; for (int i = 0; i < versionsArray.length; i++) { versionsArray[i] = versionAsJsonArray.get(i).getAsString(); } sslInfo.setVersions(versionsArray); JsonElement cipher = sslAsJsonObject.get("cipher"); JsonObject cipherAsJsonObject = cipher.getAsJsonObject(); JsonElement bits = cipherAsJsonObject.get("bits"); JsonElement cipherVersion = cipherAsJsonObject.get("version"); JsonElement name = cipherAsJsonObject.get("name"); final Cipher cipherObject = new Cipher(); if (bits != null && !bits.isJsonNull()) { cipherObject.setBits(bits.getAsInt()); } if (cipherVersion != null && !cipherVersion.isJsonNull()) { cipherObject.setVersion(cipherVersion.getAsString()); } else { cipherObject.setVersion("unknown"); } if (name == null || name.isJsonNull()) { cipherObject.setName("unknown"); } else { cipherObject.setName(name.getAsString()); } sslInfo.setCipher(cipherObject); JsonElement dhparams = sslAsJsonObject.get("dhparams"); if (dhparams != null && !dhparams.isJsonNull()) { JsonObject dhparamsAsJsonObject = dhparams.getAsJsonObject(); JsonElement bits1 = dhparamsAsJsonObject.get("bits"); JsonElement prime = dhparamsAsJsonObject.get("prime"); JsonElement publicKey = dhparamsAsJsonObject.get("public_key"); JsonElement generator = dhparamsAsJsonObject.get("generator"); JsonElement fingerprint = dhparamsAsJsonObject.get("fingerprint"); final DiffieHellmanParams diffieHellmanParams = new DiffieHellmanParams(); if (bits1 != null && !bits1.isJsonNull()) { diffieHellmanParams.setBits(bits1.getAsInt()); } if (prime == null || prime.isJsonNull()) { diffieHellmanParams.setPrime("unknown"); } else { diffieHellmanParams.setPrime(prime.getAsString()); } if (publicKey == null || publicKey.isJsonNull()) { diffieHellmanParams.setPublicKey("unknown"); } else { diffieHellmanParams.setPublicKey(publicKey.getAsString()); } if (generator == null || generator.isJsonNull()) { diffieHellmanParams.setGenerator("unknown"); } else { diffieHellmanParams.setGenerator(generator.getAsString()); } if (fingerprint == null || fingerprint.isJsonNull()) { diffieHellmanParams.setFingerprint("unknown"); } else { diffieHellmanParams.setFingerprint(fingerprint.getAsString()); } sslInfo.setDiffieHellmanParams(diffieHellmanParams); } } banner.setSslInfo(sslInfo); if (uptime == null || uptime.isJsonNull()) { banner.setUptime(0); } else { banner.setUptime(uptime.getAsInt()); } if (link == null || link.isJsonNull()) { banner.setLink("unknown"); } else { banner.setLink(link.getAsString()); } if (title == null || title.isJsonNull()) { banner.setTitle("unknown"); } else { banner.setTitle(title.getAsString()); } if (html == null || html.isJsonNull()) { banner.setHtml("unknown"); } else { banner.setHtml(html.getAsString()); } if (product == null || product.isJsonNull()) { banner.setProduct("unknown"); } else { banner.setProduct(product.getAsString()); } if (version == null || version.isJsonNull()) { banner.setVersion("unknown"); } else { banner.setVersion(version.getAsString()); } if (isp == null || isp.isJsonNull()) { banner.setIsp("unknown"); } else { banner.setIsp(isp.getAsString()); } if (os == null || os.isJsonNull()) { banner.setOs("unknown"); } else { banner.setOs(os.getAsString()); } if (transport == null || transport.isJsonNull()) { banner.setTransport("unknown"); } else { banner.setTransport(transport.getAsString()); } if (devicetype == null || devicetype.isJsonNull()) { banner.setDeviceType("unknown"); } else { banner.setDeviceType(devicetype.getAsString()); } if (info == null || info.isJsonNull()) { banner.setInfo("unknown"); } else { banner.setInfo(info.getAsString()); } if (cpe == null || cpe.isJsonNull()) { banner.setCpe(new String[0]); } else { // cpe can be string or string[]. Fix for #4 if (cpe.isJsonObject()) { banner.setCpe(new String[] { cpe.getAsString() }); } else { JsonArray cpeAsJsonArray = cpe.getAsJsonArray(); String[] cpeArray = new String[cpeAsJsonArray.size()]; for (int i = 0; i < cpeAsJsonArray.size(); i++) { cpeArray[i] = cpeAsJsonArray.get(i).getAsString(); } banner.setCpe(cpeArray); } } banners.add(banner); } return banners; }
From source file:com.getperka.client.AuthUtils.java
License:Apache License
private void executeTokenRequest(String payload) throws IOException, StatusCodeException { TokenRequest req = new TokenRequest(api, payload); JsonElement elt = req.execute(); if (elt != null && elt.isJsonObject()) { JsonObject obj = elt.getAsJsonObject(); int statusCode = obj.get("status_code").getAsInt(); if (200 != statusCode) { StatusCodeException sce = new StatusCodeException(statusCode, null); sce.setJsonElement(obj);/*from w w w. j ava 2 s. c o m*/ throw sce; } String expires = getOrNull(obj, "expires_in"); if (expires != null) { setAccessExpiration(DateTime.now().plusSeconds(Integer.valueOf(expires))); } setAccessToken(getOrNull(obj, "access_token")); setRefreshToken(getOrNull(obj, "refresh_token")); String uuid = getOrNull(obj, "uuid"); if (uuid != null) { setUserUuid(UUID.fromString(uuid)); } } }
From source file:com.getperka.flatpack.client.impl.JsonRequestBase.java
License:Apache License
@Override protected JsonElement execute(HttpURLConnection response) throws IOException { int statusCode = response.getResponseCode(); JsonElement toReturn = null; try {//from ww w. jav a 2 s.co m InputStream in = isOk(statusCode) ? response.getInputStream() : response.getErrorStream(); Reader reader = new InputStreamReader(in, FlatPackTypes.UTF8); toReturn = new JsonParser().parse(reader); } catch (JsonParseException ignored) { // Probably a 500 crash page toReturn = new JsonObject(); } if (toReturn.isJsonObject()) { toReturn.getAsJsonObject().addProperty("status_code", statusCode); } return toReturn; }
From source file:com.getperka.flatpack.codexes.DynamicCodex.java
License:Apache License
/** * Attempt to infer the type from the JsonElement presented. * <ul>//from www.ja va 2 s .co m * <li>boolean -> {@link Boolean} * <li>number -> {@link BigDecimal} * <li>string -> {@link HasUuid} or {@link String} * <li>array -> {@link ListCodex} * <li>object -> {@link StringMapCodex} * </ul> */ @Override public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { // Always return numbers as BigDecimals for consistency return primitive.getAsBigDecimal(); } else { String value = primitive.getAsString(); // Interpret UUIDs as entity references if (UUID_PATTERN.matcher(value).matches()) { UUID uuid = UUID.fromString(value); HasUuid entity = context.getEntity(uuid); if (entity != null) { return entity; } } return value; } } else if (element.isJsonArray()) { return listCodex.get().readNotNull(element, context); } else if (element.isJsonObject()) { return mapCodex.get().readNotNull(element, context); } context.fail(new UnsupportedOperationException("Cannot infer data type for " + element.toString())); return null; }
From source file:com.github.api.v2.services.impl.BaseGitHubService.java
License:Apache License
/** * Unmarshall./*w w w . ja va 2 s . co m*/ * * @param jsonContent * the json content * * @return the json object */ protected JsonObject unmarshall(InputStream jsonContent) { try { JsonElement element = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET)); if (element.isJsonObject()) { return element.getAsJsonObject(); } else { throw new GitHubException("Unknown content found in response." + element); } } catch (Exception e) { throw new GitHubException(e); } finally { closeStream(jsonContent); } }
From source file:com.github.autermann.matlab.json.MatlabValueSerializer.java
License:Open Source License
/** * Deserializes an {@link MatlabValue} from a {@link JsonElement}. * * @param element the <code>JsonElement</code> containing a * serialized <code>MatlabValue</code> * * @return the deserialized <code>MatlabValue</code> */// w w w . j a v a 2 s . c om public MatlabValue deserializeValue(JsonElement element) { if (!element.isJsonObject()) { throw new JsonParseException("expected JSON object"); } JsonObject json = element.getAsJsonObject(); MatlabType type = getType(json); JsonElement value = json.get(MatlabJSONConstants.VALUE); switch (type) { case ARRAY: return parseMatlabArray(value); case BOOLEAN: return parseMatlabBoolean(value); case CELL: return parseMatlabCell(value); case FILE: return parseMatlabFile(value); case MATRIX: return parseMatlabMatrix(value); case SCALAR: return parseMatlabScalar(value); case STRING: return parseMatlabString(value); case STRUCT: return parseMatlabStruct(value); case DATE_TIME: return parseMatlabDateTime(value); default: throw new JsonParseException("Unknown type: " + type); } }
From source file:com.github.cc007.knowledgesystem.server.RESTHandler.java
@Override public void run() { Gson gson = new Gson(); JsonParser parser = new JsonParser(); options("/rest", (request, response) -> { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Method", "POST"); response.header("Access-Control-Allow-Headers", "Content-Type"); return ""; });//from w ww . java 2s . c om post("/rest", "application/json", (request, response) -> { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Method", "POST"); response.header("Access-Control-Allow-Headers", "Content-Type"); JsonElement data = parser.parse(request.body()); int id; RESTView view; //Determine the type of request (first visit, inquiry response, stops server) if (data != null && data.isJsonObject()) { if (data.getAsJsonObject().has("stop")) { // stop the server System.out.println("[rest] new stop request"); stop(); return new Object() { private final boolean stopped = true; }; } else if (data.getAsJsonObject().has("id")) { if (!data.getAsJsonObject().has("back")) { System.out.println("[rest] new response request"); // inquiry response ResponseMessage respMsg = new Gson().fromJson(data, ResponseMessage.class); id = respMsg.getId(); view = views.get(id); setNewKnowledge(view, respMsg); } else { System.out.println("[rest] new previous question request"); BackMessage respMsg = new Gson().fromJson(data, BackMessage.class); int oldId = respMsg.getId(); RESTView oldView = views.get(oldId); oldView.setStopped(true); System.out.println("[rest] old id:" + oldId); oldView.setNewRestHandlerData(true); // get the list of previous choises and remove the last choice List<ResponseMessage> choices = oldView.getChoices(); if (choices.size() > 0) { choices.remove(choices.get(choices.size() - 1)); } // start a new session id = getNewId(); Session newSession = new Session(this); Thread t = new Thread(newSession); t.start(); view = newSession.getView(); views.put(id, view); System.out.println("[rest] new id:" + oldId); // recreate the choices from the choice list for (ResponseMessage choice : choices) { waitForKnowledge(view); setNewKnowledge(view, choice); } } } else { System.out.println("[rest] new session request"); // first visit id = getNewId(); Session newSession = new Session(this); Thread t = new Thread(newSession); t.start(); view = newSession.getView(); views.put(id, view); } } else { // unknown request, send error back return new Object() { private final String error = "Unknown request"; }; } waitForKnowledge(view); response.header("Content-Type", "application/json; charset=UTF-8"); Map<String, Object> retVal = new HashMap<>(); retVal.put("id", id); retVal.put("respId", getNewResponseId()); if (!view.isGoalReached()) { //case inquiry retVal.put("type", "inquiry"); retVal.put("knowledge", view.getKnowledge()); } else { //case result retVal.put("type", "result"); retVal.put("goal", view.getKnowledge()); retVal.put("context", view.getContext()); } return retVal; }, gson::toJson); }