List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.google.cloud.das.languagecheck.Translate.java
License:Apache License
public Hashtable<String, String> getLanguagesFromAPI() { String response;/*from w ww . j av a 2 s. c o m*/ String path = "/languages"; String query = "?target=" + target + "&key=" + key; String url = baseurl + path + query; Hashtable<String, String> hash = new Hashtable<String, String>(); try { response = sendGet(url); //System.out.println(response); } catch (Exception e) { //do something clever with the exception response = "{}"; System.out.println(e.getMessage()); } JsonParser jsonParser = new JsonParser(); JsonArray arr = jsonParser.parse(response).getAsJsonObject().getAsJsonObject("data") .getAsJsonArray("languages"); for (int i = 0; i < arr.size(); i++) { JsonElement el = arr.get(i).getAsJsonObject(); hash.put(el.getAsJsonObject().get("language").getAsString(), el.getAsJsonObject().get("name").getAsString()); } return hash; }
From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceRetriever.java
License:Open Source License
/** * Parses the response, which contains all information about the running VMs. Extracts only the * IPs and names, as they are all that the orchstrator needs. Adjust this implementation to suit * your needs if necessary.//w ww . j a v a 2 s.c o m * * @param instanceResponse the string containing the response from queriying "instances" for the * given project. * @param instancePrefix returns only instances with name that starts with the prefix as specified * in the configuration properties. * @return the extracted IP, or null if it can't be found. */ static Map<String, String> extractIpsAndInstanceNames(String instanceResponse, String instancePrefix) { JsonParser parser = new JsonParser(); JsonObject jsonObject = (JsonObject) parser.parse(instanceResponse); Map<String, String> gceIpsAndInstanceNames = new HashMap<String, String>(); JsonArray items = jsonObject.getAsJsonArray("items"); if (items != null) { for (int i = 0; i < items.size(); i++) { String natIp = items.get(i).getAsJsonObject().getAsJsonArray("networkInterfaces").get(0) .getAsJsonObject().getAsJsonArray("accessConfigs").get(0).getAsJsonObject().get("natIP") .getAsString(); String name = items.get(i).getAsJsonObject().get("name").getAsString(); if (name.startsWith(instancePrefix)) { gceIpsAndInstanceNames.put(natIp, name); } } } return gceIpsAndInstanceNames; }
From source file:com.google.debugging.sourcemap.SourceMapConsumerV3.java
License:Apache License
/** * @param sourceMapRoot//w ww . j av a2s.com * @throws SourceMapParseException */ private void parseMetaMap(JsonObject sourceMapRoot, SourceMapSupplier sectionSupplier) throws SourceMapParseException { if (sectionSupplier == null) { sectionSupplier = new DefaultSourceMapSupplier(); } try { // Check basic assertions about the format. int version = sourceMapRoot.get("version").getAsInt(); if (version != 3) { throw new SourceMapParseException("Unknown version: " + version); } String file = sourceMapRoot.get("file").getAsString(); if (file.isEmpty()) { throw new SourceMapParseException("File entry is missing or empty"); } if (sourceMapRoot.has("lineCount") || sourceMapRoot.has("mappings") || sourceMapRoot.has("sources") || sourceMapRoot.has("names")) { throw new SourceMapParseException("Invalid map format"); } SourceMapGeneratorV3 generator = new SourceMapGeneratorV3(); JsonArray sections = sourceMapRoot.get("sections").getAsJsonArray(); for (int i = 0, count = sections.size(); i < count; i++) { JsonObject section = sections.get(i).getAsJsonObject(); if (section.has("map") && section.has("url")) { throw new SourceMapParseException( "Invalid map format: section may not have both 'map' and 'url'"); } JsonObject offset = section.get("offset").getAsJsonObject(); int line = offset.get("line").getAsInt(); int column = offset.get("column").getAsInt(); String mapSectionContents; if (section.has("url")) { String url = section.get("url").getAsString(); mapSectionContents = sectionSupplier.getSourceMap(url); if (mapSectionContents == null) { throw new SourceMapParseException("Unable to retrieve: " + url); } } else if (section.has("map")) { mapSectionContents = section.get("map").toString(); } else { throw new SourceMapParseException( "Invalid map format: section must have either 'map' or 'url'"); } generator.mergeMapSection(line, column, mapSectionContents); } StringBuilder sb = new StringBuilder(); try { generator.appendTo(sb, file); } catch (IOException e) { // Can't happen. throw new RuntimeException(e); } parse(sb.toString()); } catch (IOException ex) { throw new SourceMapParseException("IO exception: " + ex); } catch (JsonParseException ex) { throw new SourceMapParseException("JSON parse exception: " + ex); } }
From source file:com.google.debugging.sourcemap.SourceMapConsumerV3.java
License:Apache License
private String[] getJavaStringArray(JsonArray array) throws JsonParseException { int len = array.size(); String[] result = new String[len]; for (int i = 0; i < len; i++) { result[i] = array.get(i).getAsString(); }/*from ww w . j av a 2 s . c o m*/ return result; }
From source file:com.google.debugging.sourcemap.SourceMapObject.java
License:Apache License
private static String[] getJavaStringArray(JsonElement element) throws JsonParseException { if (element == null) { return null; }/*from ww w .ja v a2 s . c o m*/ JsonArray array = element.getAsJsonArray(); int len = array.size(); String[] result = new String[len]; for (int i = 0; i < len; i++) { result[i] = array.get(i).getAsString(); } return result; }
From source file:com.google.debugging.sourcemap.SourceMapObjectParser.java
License:Apache License
private static String[] getJavaStringArray(JsonElement element) { if (element == null) { return null; }/*from w w w . ja v a2 s. co m*/ JsonArray array = element.getAsJsonArray(); int len = array.size(); String[] result = new String[len]; for (int i = 0; i < len; i++) { result[i] = array.get(i).getAsString(); } return result; }
From source file:com.google.gms.googleservices.GoogleServicesTask.java
License:Apache License
/** * find an item in the "client" array that match the package name of the app * @param jsonObject the root json object. * @return a JsonObject representing the client entry or null if no match is found. *///from ww w . j a v a 2 s .c om private JsonObject getClientForPackageName(JsonObject jsonObject) { JsonArray array = jsonObject.getAsJsonArray("client"); if (array != null) { final int count = array.size(); for (int i = 0; i < count; i++) { JsonElement clientElement = array.get(i); if (clientElement == null || !clientElement.isJsonObject()) { continue; } JsonObject clientObject = clientElement.getAsJsonObject(); JsonObject clientInfo = clientObject.getAsJsonObject("client_info"); if (clientInfo == null) continue; JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info"); if (androidClientInfo == null) continue; JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name"); if (clientPackageName == null) continue; if (packageName.equals(clientPackageName.getAsString())) { return clientObject; } } } return null; }
From source file:com.google.gwtjsonrpc.server.CallDeserializer.java
License:Apache License
public CallType deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException, NoSuchRemoteMethodException { if (!json.isJsonObject()) { throw new JsonParseException("Expected object"); }/*from ww w . j a v a 2s .c om*/ final JsonObject in = json.getAsJsonObject(); req.id = in.get("id"); final JsonElement jsonrpc = in.get("jsonrpc"); final JsonElement version = in.get("version"); if (isString(jsonrpc) && version == null) { final String v = jsonrpc.getAsString(); if ("2.0".equals(v)) { req.versionName = "jsonrpc"; req.versionValue = jsonrpc; } else { throw new JsonParseException("Expected jsonrpc=2.0"); } } else if (isString(version) && jsonrpc == null) { final String v = version.getAsString(); if ("1.1".equals(v)) { req.versionName = "version"; req.versionValue = version; } else { throw new JsonParseException("Expected version=1.1"); } } else { throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0"); } final JsonElement method = in.get("method"); if (!isString(method)) { throw new JsonParseException("Expected method name as string"); } req.method = server.lookupMethod(method.getAsString()); if (req.method == null) { throw new NoSuchRemoteMethodException(); } final JsonElement callback = in.get("callback"); if (callback != null) { if (!isString(callback)) { throw new JsonParseException("Expected callback as string"); } req.callback = callback.getAsString(); } final JsonElement xsrfKey = in.get("xsrfKey"); if (xsrfKey != null) { if (!isString(xsrfKey)) { throw new JsonParseException("Expected xsrfKey as string"); } req.xsrfKeyIn = xsrfKey.getAsString(); } final Type[] paramTypes = req.method.getParamTypes(); final JsonElement params = in.get("params"); if (params != null) { if (!params.isJsonArray()) { throw new JsonParseException("Expected params array"); } final JsonArray paramsArray = params.getAsJsonArray(); if (paramsArray.size() != paramTypes.length) { throw new JsonParseException("Expected " + paramTypes.length + " parameter values in params array"); } final Object[] r = new Object[paramTypes.length]; for (int i = 0; i < r.length; i++) { final JsonElement v = paramsArray.get(i); if (v != null) { r[i] = context.deserialize(v, paramTypes[i]); } } req.params = r; } else { if (paramTypes.length != 0) { throw new JsonParseException("Expected params array"); } req.params = JsonServlet.NO_PARAMS; } return req; }
From source file:com.google.identitytoolkit.GitkitUser.java
License:Open Source License
public GitkitUser setProviders(JsonArray providers) { List<ProviderInfo> providerInfo = new ArrayList<ProviderInfo>(); if (providers != null) { for (int i = 0; i < providers.size(); i++) { JsonObject provider = providers.get(i).getAsJsonObject(); JsonElement displayNameElement = provider.get("displayName"); JsonElement photoUrlElement = provider.get("photoUrl"); providerInfo.add(new ProviderInfo(provider.get("providerId").getAsString(), provider.get("federatedId").getAsString(), (displayNameElement == null) ? "" : displayNameElement.getAsString(), (photoUrlElement == null) ? "" : photoUrlElement.getAsString())); }/*from w w w . j a v a 2 s . co m*/ } this.providers = providerInfo; return this; }
From source file:com.google.iosched.model.DataExtractor.java
License:Open Source License
public JsonArray extractSessions(JsonDataSources sources) { if (videoSessionsById == null) { throw new IllegalStateException( "You need to extract video sessions before attempting to extract sessions"); }/*w ww . ja va 2s . co m*/ if (categoryToTagMap == null) { throw new IllegalStateException("You need to extract tags before attempting to extract sessions"); } JsonArray result = new JsonArray(); JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.topics.name()); if (source != null) { for (JsonObject origin : source) { if (isVideoSession(origin)) { // Sessions with the Video tag are processed as video library content continue; } if (isHiddenSession(origin)) { // Sessions with a "Hidden from schedule" flag should be ignored continue; } JsonElement title = get(origin, VendorAPISource.Topics.title); // Since the CMS returns an empty keynote as a session, we need to ignore it if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) { continue; } JsonObject dest = new JsonObject(); set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id); set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL); set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, null); set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, null); set(origin, VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME); set(origin, VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME); JsonElement documents = get(origin, VendorAPISource.Topics.documents); if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) { // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original // photo URL, because that will be processed by an offline cron script, resizing the // photos and saving them to a known location with the entity ID as its base name. set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL); } setVideoPropertiesInSession(origin, dest); setRelatedVideos(origin, dest); JsonElement mainTag = null; JsonElement hashtag = null; JsonElement mainTagColor = null; JsonArray categories = origin.getAsJsonArray(VendorAPISource.Topics.categoryids.name()); JsonArray tags = new JsonArray(); for (JsonElement category : categories) { JsonObject tag = categoryToTagMap.get(category.getAsString()); if (tag != null) { JsonElement tagName = get(tag, OutputJsonKeys.Tags.tag); tags.add(tagName); usedTags.add(tagName.getAsString()); if (mainTag == null) { // check if the tag is from a "default" category. For example, if THEME is the default // category, all sessions will have a "mainTag" property set to the first tag of type THEME JsonElement tagCategory = get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC if (tagCategory.equals(mainCategory)) { mainTag = tagName; mainTagColor = get(tag, OutputJsonKeys.Tags.color); } if (hashtag == null && isHashtag(tag)) { hashtag = get(tag, OutputJsonKeys.Tags.hashtag); if (hashtag == null || hashtag.getAsString() == null || hashtag.getAsString().isEmpty()) { // If no hashtag set in the tagsconf file, we will convert the tagname to find one: hashtag = new JsonPrimitive( get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME).getAsString() .toLowerCase()); } } } } } set(tags, dest, OutputJsonKeys.Sessions.tags); if (mainTag != null) { set(mainTag, dest, OutputJsonKeys.Sessions.mainTag); } if (mainTagColor != null) { set(mainTagColor, dest, OutputJsonKeys.Sessions.color); } if (hashtag != null) { set(hashtag, dest, OutputJsonKeys.Sessions.hashtag); } JsonArray speakers = getAsArray(origin, VendorAPISource.Topics.speakerids); if (speakers != null) for (JsonElement speaker : speakers) { String speakerId = speaker.getAsString(); usedSpeakers.add(speakerId); } set(speakers, dest, OutputJsonKeys.Sessions.speakers); JsonArray sessions = origin.getAsJsonArray(VendorAPISource.Topics.sessions.name()); if (sessions != null && sessions.size() > 0) { String roomId = get(sessions.get(0).getAsJsonObject(), VendorAPISource.Sessions.roomid) .getAsString(); roomId = Config.ROOM_MAPPING.getRoomId(roomId); set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room); // captions URL is set based on the session room, so keep it here. String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId); if (captionsURL != null) { set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl); } } result.add(dest); } } return result; }