List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
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"); }/*from w w w. j a v a 2 s . c om*/ 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; }
From source file:com.google.iosched.model.DataExtractor.java
License:Open Source License
public JsonArray extractVideoSessions(JsonDataSources sources) { videoSessionsById = new HashMap<String, JsonObject>(); if (categoryToTagMap == null) { throw new IllegalStateException("You need to extract tags before attempting to extract video sessions"); }/*www . ja v a 2 s .c o m*/ if (speakersById == null) { throw new IllegalStateException( "You need to extract speakers before attempting to extract video sessions"); } JsonArray result = new JsonArray(); JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.topics.name()); if (source != null) { for (JsonObject origin : source) { if (!isVideoSession(origin)) { continue; } if (isHiddenSession(origin)) { // Sessions with a "Hidden from schedule" flag should be ignored continue; } JsonObject dest = new JsonObject(); JsonPrimitive vid = setVideoForVideoSession(origin, dest); JsonElement id = get(origin, VendorAPISource.Topics.id); // video library id must be the Youtube video id set(vid, dest, OutputJsonKeys.VideoLibrary.id); set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.VideoLibrary.title, null); set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.VideoLibrary.desc, null); set(new JsonPrimitive(Config.CONFERENCE_YEAR), dest, OutputJsonKeys.VideoLibrary.year); JsonElement videoTopic = null; JsonArray categories = origin.getAsJsonArray(VendorAPISource.Topics.categoryids.name()); for (JsonElement category : categories) { JsonObject tag = categoryToTagMap.get(category.getAsString()); if (tag != null) { if (isHashtag(tag)) { videoTopic = get(tag, OutputJsonKeys.Tags.name); // by definition, the first tag that can be a hashtag (usually a TOPIC) is considered the video tag break; } } } if (videoTopic != null) { set(videoTopic, dest, OutputJsonKeys.VideoLibrary.topic); } // Concatenate speakers: JsonArray speakers = getAsArray(origin, VendorAPISource.Topics.speakerids); StringBuilder sb = new StringBuilder(); if (speakers != null) for (int i = 0; i < speakers.size(); i++) { String speakerId = speakers.get(i).getAsString(); usedSpeakers.add(speakerId); JsonObject speaker = speakersById.get(speakerId); if (speaker != null) { sb.append(get(speaker, OutputJsonKeys.Speakers.name).getAsString()); if (i < speakers.size() - 1) sb.append(", "); } } set(new JsonPrimitive(sb.toString()), dest, OutputJsonKeys.VideoLibrary.speakers); videoSessionsById.put(id.getAsString(), dest); result.add(dest); } } return result; }
From source file:com.google.iosched.server.servlet.LogDataServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); UpdateRunLogger logger = new UpdateRunLogger(); JsonObject response = new JsonObject(); int limitElements = 10; if (req.getParameter("limit") != null) { limitElements = Integer.parseInt(req.getParameter("limit")); }/* w w w .j a v a 2 s . c o m*/ List<Entity> lastRunsEntities = logger.getMostRecentRuns(limitElements); JsonArray lastRuns = new JsonArray(); for (Entity run : lastRunsEntities) { JsonObject obj = new JsonObject(); JsonObject timings = new JsonObject(); TreeMap<String, Object> sortedMap = new TreeMap<String, Object>(run.getProperties()); for (Entry<String, Object> property : sortedMap.entrySet()) { Object value = property.getValue(); String key = property.getKey(); if (key.startsWith("time_")) { timings.add(key.substring("time_".length()), new JsonPrimitive((Number) value)); } else { JsonPrimitive converted = null; if (value instanceof ShortBlob) { converted = new JsonPrimitive(bytesToHex(((ShortBlob) value).getBytes())); } else if (value instanceof String) { converted = new JsonPrimitive((String) value); } else if (value instanceof Number) { converted = new JsonPrimitive((Number) value); } else if (value instanceof Boolean) { converted = new JsonPrimitive((Boolean) value); } else if (value instanceof Character) { converted = new JsonPrimitive((Character) value); } else if (value instanceof Date) { converted = new JsonPrimitive(DateFormat.getDateTimeInstance().format((Date) value)); } if (converted != null) { obj.add(key, converted); } } } obj.add("timings", timings); lastRuns.add(obj); } response.add("lastruns", lastRuns); CloudFileManager cloudManager = new CloudFileManager(); response.add("bucket", new JsonPrimitive(cloudManager.getBucketName())); response.add("productionManifest", new JsonPrimitive(cloudManager.getProductionManifestURL())); response.add("stagingManifest", new JsonPrimitive(cloudManager.getStagingManifestURL())); new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(response, resp.getWriter()); }
From source file:com.google.java.wob.ClassListServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json; charset=utf-8"); // Get issuer ID from client String issuerId = req.getParameter("issuerId"); if (Strings.isNullOrEmpty(issuerId)) { log.warning("No issuer id"); return;/*from w ww.java 2 s .c om*/ } Long id; try { id = Long.valueOf(issuerId); } catch (NumberFormatException e) { log.warning("Unable to parse issuer ID: " + e.getMessage()); return; } Walletobjects client = ClientMethods.getClientForId(issuerId); if (client == null) { log.warning("Unable to get client for issuer id " + issuerId + "."); return; } // Add all classes to class list OfferClassListResponse offerClassList; LoyaltyClassListResponse loyaltyClassList; GenericClassListResponse genericClassList; try { offerClassList = client.offerclass().list(id).execute(); loyaltyClassList = client.loyaltyclass().list(id).execute(); genericClassList = client.genericclass().list(id).execute(); } catch (GoogleJsonResponseException e) { log.warning("Class list failed " + e.getMessage()); resp.getWriter().write(ClientMethods.createError("Something went wrong, please refresh and try again")); return; } List<GenericJson> classList = new ArrayList<GenericJson>(); if (offerClassList.getResources() != null) { classList.addAll(offerClassList.getResources()); } if (loyaltyClassList.getResources() != null) { classList.addAll(loyaltyClassList.getResources()); } if (genericClassList.getResources() != null) { classList.addAll(genericClassList.getResources()); } // Write the class' JSON as a list for client side // gson.toJson cannot be used due to differences in how the JSON is created JsonFactory jsonFactory = new GsonFactory(); JsonArray array = new JsonArray(); JsonParser parser = new JsonParser(); for (int i = 0; i < classList.size(); i++) { GenericJson theClass = classList.get(i); theClass.setFactory(jsonFactory); array.add(parser.parse(theClass.toString())); } resp.getWriter().write(array.toString()); }
From source file:com.google.java.wob.ObjectListServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json; charset=utf-8"); // Add all objects of kind "kind" and with class id "id" String kind = req.getParameter("kind"); String id = req.getParameter("id"); if (Strings.isNullOrEmpty(kind) || Strings.isNullOrEmpty(id)) { log.warning("Unable to retrieve objects without both kind and id"); resp.getWriter().write(ClientMethods.createError(null)); return;//from ww w.j av a 2s. c o m } String issuerId; try { issuerId = id.substring(0, id.indexOf(".")); } catch (StringIndexOutOfBoundsException e) { log.warning("Invalid issuer id"); resp.getWriter().write(ClientMethods.createError(null)); return; } Walletobjects client = ClientMethods.getClientForId(issuerId); if (client == null) { log.warning("Unable to get client for issuer id " + issuerId + "."); resp.getWriter().write(ClientMethods.createError(null)); return; } List<GenericJson> objList = new ArrayList<GenericJson>(); GenericJson theClass = null; try { if (kind.contains("offer")) { // Attempt to list objects OfferObjectListResponse offerList = client.offerobject().list(id).execute(); // If no objects exist, retrieve the class if (offerList.getResources() != null) { objList.addAll(offerList.getResources()); } else { theClass = client.offerclass().get(id).execute(); } } else if (kind.contains("loyalty")) { // Attempt to list objects LoyaltyObjectListResponse loyaltyList = client.loyaltyobject().list(id).execute(); // If no objects exist, retrieve the class if (loyaltyList.getResources() != null) { objList.addAll(loyaltyList.getResources()); } else { theClass = client.loyaltyclass().get(id).execute(); } } else if (kind.contains("generic")) { // Attempt to list objects GenericObjectListResponse genericList = client.genericobject().list(id).execute(); // If no objects exist, retrieve the class if (genericList.getResources() != null) { objList.addAll(genericList.getResources()); } else { theClass = client.genericclass().get(id).execute(); } } else { log.warning("Unable to retrieve objects with invalid kind " + kind + "."); resp.getWriter().write(ClientMethods.createError(null)); return; } } catch (GoogleJsonResponseException e) { log.warning("Object list failed: " + e.getMessage()); resp.getWriter().write(ClientMethods.createError("Something went wrong, please refresh and try again")); return; } JsonFactory jsonFactory = new GsonFactory(); if (objList.size() > 0) { // Write the object's JSON as a list for client side // gson.toJson cannot be used due to differences in how the JSON is created JsonArray array = new JsonArray(); JsonParser parser = new JsonParser(); for (int i = 0; i < objList.size(); i++) { GenericJson theObj = objList.get(i); theObj.setFactory(jsonFactory); array.add(parser.parse(theObj.toString())); } resp.getWriter().write(array.toString()); } else { // Write the class if there are no objects present so that the user // may still create an object and have a class to build on top of theClass.setFactory(jsonFactory); resp.getWriter().write(theClass.toString()); } }
From source file:com.google.java.wob.SearchServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json; charset=utf-8"); String issuerId = req.getParameter("issuerId"); Walletobjects client = ClientMethods.getClientForId(issuerId); if (client == null) { log.warning("Unable to get client for issuer id " + issuerId + "."); resp.getWriter().write(ClientMethods.createError(null)); return;//from www . ja va 2 s.co m } String query = issuerId + "." + req.getParameter("query"); String kind = req.getParameter("kind"); if (Strings.isNullOrEmpty(kind)) { log.warning("Unable to continue without kind of class or object."); resp.getWriter().write(ClientMethods.createError(null)); return; } // Attempt to find class or object with specified id GenericJson result = null; JsonArray array = new JsonArray(); JsonFactory jsonFactory = new GsonFactory(); JsonParser parser = new JsonParser(); if (kind.equals("class")) { try { result = client.offerclass().get(query).execute(); } catch (GoogleJsonResponseException e) { } try { result = client.loyaltyclass().get(query).execute(); } catch (GoogleJsonResponseException e) { } try { result = client.genericclass().get(query).execute(); } catch (GoogleJsonResponseException e) { } } else if (kind.equals("object")) { try { result = client.offerobject().get(query).execute(); } catch (GoogleJsonResponseException e) { } try { result = client.loyaltyobject().get(query).execute(); } catch (GoogleJsonResponseException e) { } try { result = client.genericobject().get(query).execute(); } catch (GoogleJsonResponseException e) { } } else { log.warning("Unknown kind " + kind); resp.getWriter().write(ClientMethods.createError(null)); } if (result != null) { result.setFactory(jsonFactory); array.add(parser.parse(result.toString())); resp.getWriter().write(array.toString()); } }
From source file:com.google.javascript.jscomp.JSModuleGraph.java
License:Apache License
/** * Returns a JSON representation of the JSModuleGraph. Specifically a * JsonArray of "Modules" where each module has a * - "name"/*w w w .jav a2s . c o m*/ * - "dependencies" (list of module names) * - "transitive-dependencies" (list of module names, deepest first) * - "inputs" (list of file names) * @return List of module JSONObjects. */ @GwtIncompatible("com.google.gson") JsonArray toJson() { JsonArray modules = new JsonArray(); for (JSModule module : getAllModules()) { JsonObject node = new JsonObject(); try { node.add("name", new JsonPrimitive(module.getName())); JsonArray deps = new JsonArray(); node.add("dependencies", deps); for (JSModule m : module.getDependencies()) { deps.add(new JsonPrimitive(m.getName())); } JsonArray transitiveDeps = new JsonArray(); node.add("transitive-dependencies", transitiveDeps); for (JSModule m : getTransitiveDepsDeepestFirst(module)) { transitiveDeps.add(new JsonPrimitive(m.getName())); } JsonArray inputs = new JsonArray(); node.add("inputs", inputs); for (CompilerInput input : module.getInputs()) { inputs.add(new JsonPrimitive(input.getSourceFile().getOriginalPath())); } modules.add(node); } catch (JsonParseException e) { Throwables.propagate(e); } } return modules; }
From source file:com.google.jstestdriver.config.YamlParser.java
License:Apache License
@SuppressWarnings("unchecked") private void copyDataToGatewayConfig(Map<Object, Object> data, String key, JsonArray gatewayConfig) { for (Map<Object, Object> value : (List<Map<Object, Object>>) data.get(key)) { JsonObject entry = new JsonObject(); if (value.containsKey(GatewayConfiguration.MATCHER)) { entry.addProperty(GatewayConfiguration.MATCHER, (String) value.get(GatewayConfiguration.MATCHER)); }// www.j av a2 s . c om if (value.containsKey(GatewayConfiguration.SERVER)) { entry.addProperty(GatewayConfiguration.SERVER, (String) value.get(GatewayConfiguration.SERVER)); } if (value.containsKey(MockResponse.STATUS)) { entry.addProperty(MockResponse.STATUS, (Number) value.get(MockResponse.STATUS)); } if (value.containsKey(MockResponse.RESPONSE_HEADERS)) { Map<String, String> responseHeaders = (Map<String, String>) value .get(MockResponse.RESPONSE_HEADERS); JsonObject jsonHeaders = new JsonObject(); for (Entry<String, String> jsonEntry : responseHeaders.entrySet()) { jsonHeaders.addProperty(jsonEntry.getKey(), jsonEntry.getValue()); } entry.add(MockResponse.RESPONSE_HEADERS, jsonHeaders); } if (value.containsKey(MockResponse.CONTENT_TYPE)) { entry.addProperty(MockResponse.CONTENT_TYPE, (String) value.get(MockResponse.CONTENT_TYPE)); } if (value.containsKey(MockResponse.RESPONSE_TEXT)) { entry.addProperty(MockResponse.RESPONSE_TEXT, (String) value.get(MockResponse.RESPONSE_TEXT)); } gatewayConfig.add(entry); } }
From source file:com.google.jstestdriver.requesthandlers.DefaultGatewayConfigurationFilter.java
License:Apache License
public JsonArray filter(JsonArray gatewayConfig) { if (destination == null) { return gatewayConfig; } else {/*from ww w.j a v a 2 s . c om*/ final JsonArray newGatewayConfig = new JsonArray(); newGatewayConfig.addAll(gatewayConfig); final JsonObject entry = new JsonObject(); entry.addProperty("matcher", "*"); entry.addProperty("server", destination.getDestinationAddress()); newGatewayConfig.add(entry); return newGatewayConfig; } }
From source file:com.google.nigori.common.TypeAdapterProtobuf.java
License:Apache License
@Override public JsonElement serialize(GeneratedMessage src, Type typeOfSrc, JsonSerializationContext context) { JsonObject ret = new JsonObject(); final Map<FieldDescriptor, Object> fields = src.getAllFields(); for (Map.Entry<FieldDescriptor, Object> fieldPair : fields.entrySet()) { final FieldDescriptor desc = fieldPair.getKey(); if (desc.isRepeated()) { List<?> fieldList = (List<?>) fieldPair.getValue(); if (fieldList.size() != 0) { JsonArray array = new JsonArray(); for (Object o : fieldList) { array.add(serializeWithEnumRewrite(context, o)); }/* ww w.j a va2 s . c o m*/ ret.add(desc.getName(), array); } } else { ret.add(desc.getName(), serializeWithEnumRewrite(context, fieldPair.getValue())); } } return ret; }