List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:com.google.iosched.model.DataExtractor.java
License:Open Source License
private void setRelatedVideos(JsonObject origin, JsonObject dest) { JsonArray related = getAsArray(origin, VendorAPISource.Topics.related); if (related == null) { return;//from w w w . j a v a 2s . c om } for (JsonElement el : related) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("values")) { continue; } if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO .equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement values = obj.get("values"); if (!values.isJsonArray()) { continue; } // As per the data specification, related content is formatted as // "video1 title1\nvideo2 title2\n..." StringBuilder relatedContentStr = new StringBuilder(); for (JsonElement value : values.getAsJsonArray()) { String relatedSessionId = value.getAsString(); JsonObject relatedVideo = videoSessionsById.get(relatedSessionId); if (relatedVideo != null) { JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid); JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title); if (vid != null && title != null) { relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString()) .append("\n"); } } } set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent); } } }
From source file:com.google.iosched.model.DataModelHelper.java
License:Open Source License
public static JsonArray getAsArray(JsonObject source, Enum<?> sourceProperty) { if (source == null) { return null; }/*from w w w . j ava 2 s .co m*/ JsonElement el = source.get(sourceProperty.name()); if (el == null || !el.isJsonArray()) { return null; } return el.getAsJsonArray(); }
From source file:com.google.iosched.model.DataModelHelper.java
License:Open Source License
public static JsonPrimitive getMapValue(JsonElement map, String key, Converter converter, String defaultValueStr) { JsonPrimitive defaultValue = null;//from w ww. j ava 2s . c om if (defaultValueStr != null) { defaultValue = new JsonPrimitive(defaultValueStr); if (converter != null) defaultValue = converter.convert(defaultValue); } if (map == null || !map.isJsonArray()) { return defaultValue; } for (JsonElement el : map.getAsJsonArray()) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("value")) { continue; } if (key.equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement value = obj.get("value"); if (!value.isJsonPrimitive()) { throw new ConverterException(value, converter, "Expected a JsonPrimitive"); } if (converter != null) value = converter.convert(value); return value.getAsJsonPrimitive(); } } return defaultValue; }
From source file:com.google.iosched.server.input.DataSourceInput.java
License:Open Source License
public JsonArray fetch(EnumType entityType) throws IOException { JsonElement element = getFetcher().fetch(entityType, null); if (element == null) { return null; }//ww w . j a v a 2 s . co m if (element.isJsonArray()) { return element.getAsJsonArray(); } else { throw new JsonParseException( "Invalid response from DataSourceInput. Expected " + "a JsonArray, but fetched " + element.getClass().getName() + ". Entity fetcher is " + getFetcher()); } }
From source file:com.google.mr4c.serialize.json.JsonConfigSerializer.java
License:Open Source License
public LocationsConfig deserializeLocationsConfig(Reader reader) throws IOException { Gson gson = buildGson();//from w ww. j ava 2 s. co m JsonParser parser = new JsonParser(); JsonElement jsonEle = parser.parse(reader); if (jsonEle.isJsonObject()) { Map<String, URI> locationMap = gson.fromJson(jsonEle, new TypeToken<Map<String, URI>>() { }.getType()); return new LocationsConfig(locationMap); } else if (jsonEle.isJsonArray()) { List<URI> locationList = gson.fromJson(jsonEle, new TypeToken<List<URI>>() { }.getType()); return new LocationsConfig(locationList); } else { throw new IllegalArgumentException("Need JSON Array or Object to deserialize LocationsConfig"); } }
From source file:com.google.samples.apps.iosched.server.schedule.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 w w .ja va2s.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(InputJsonKeys.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, InputJsonKeys.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(); // Some sessions require a special ID, so we replace it here... if (title != null && title.isJsonPrimitive() && "after hours".equalsIgnoreCase(title.getAsString())) { set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id); } else { set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id); } set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL); set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, obfuscate ? Converters.OBFUSCATE : null); set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null); set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME); set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME); set(new JsonPrimitive(isFeatured(origin)), dest, OutputJsonKeys.Sessions.isFeatured); JsonElement documents = get(origin, InputJsonKeys.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, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL); } setVideoPropertiesInSession(origin, dest); setRelatedContent(origin, dest); JsonElement mainTag = null; JsonElement hashtag = null; JsonElement mainTagColor = null; JsonArray categories = origin .getAsJsonArray(InputJsonKeys.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, InputJsonKeys.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(InputJsonKeys.VendorAPISource.Topics.sessions.name()); if (sessions != null && sessions.size() > 0) { String roomId = get(sessions.get(0).getAsJsonObject(), InputJsonKeys.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); } } if (Config.DEBUG_FIX_DATA) { DebugDataExtractorHelper.changeSession(dest, usedTags); } result.add(dest); } } return result; }
From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java
License:Open Source License
@Deprecated private void setRelatedVideos(JsonObject origin, JsonObject dest) { JsonArray related = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related); if (related == null) { return;// w w w . j a v a2s . com } for (JsonElement el : related) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("values")) { continue; } if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO .equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement values = obj.get("values"); if (!values.isJsonArray()) { continue; } // As per the data specification, related content is formatted as // "video1 title1\nvideo2 title2\n..." StringBuilder relatedContentStr = new StringBuilder(); for (JsonElement value : values.getAsJsonArray()) { String relatedSessionId = value.getAsString(); JsonObject relatedVideo = videoSessionsById.get(relatedSessionId); if (relatedVideo != null) { JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid); JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title); if (vid != null && title != null) { relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString()) .append("\n"); } } } set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent); } } }
From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java
License:Open Source License
private void setRelatedContent(JsonObject origin, JsonObject dest) { JsonArray related = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related); JsonArray outputArray = new JsonArray(); if (related == null) { return;//from www. j ava 2 s .com } for (JsonElement el : related) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("values")) { continue; } if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_SESSIONS .equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement values = obj.get("topics"); if (!values.isJsonArray()) { continue; } // As per the data specification, related content is formatted as // "video1 title1\nvideo2 title2\n..." for (JsonElement topic : values.getAsJsonArray()) { if (!topic.isJsonObject()) { continue; } JsonObject topicObj = topic.getAsJsonObject(); String id = get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.id).getAsString(); String title = get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.title).getAsString(); if (id != null && title != null) { JsonObject outputObj = new JsonObject(); set(new JsonPrimitive(id), outputObj, OutputJsonKeys.RelatedContent.id); set(new JsonPrimitive(title), outputObj, OutputJsonKeys.RelatedContent.title); outputArray.add(outputObj); } } set(outputArray, dest, OutputJsonKeys.Sessions.relatedContent); } } }
From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java
License:Open Source License
public JsonArray fetchArray(InputJsonKeys.VendorAPISource.MainTypes entityType, int page) throws IOException { HashMap<String, String> params = null; if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics) || entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.speakers)) { params = new HashMap<String, String>(); // Topics and speakers require param "includeinfo=true" to bring extra data params.put("includeinfo", "true"); if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)) { if (extractUnpublished) { params.put("minpublishstatus", "0"); }/*from w ww . j ava 2 s. c o m*/ } } if (page == 0) { page = 1; } else if (page > 1) { if (params == null) { params = new HashMap<String, String>(); } params.put("page", Integer.toString(page)); } JsonElement element = getFetcher().fetch(entityType, params); if (element.isJsonArray()) { return element.getAsJsonArray(); } else if (element.isJsonObject()) { // check if there are extra pages requiring further fetching JsonObject obj = element.getAsJsonObject(); checkPagingConsistency(entityType, page, obj); int pageSize = obj.get("pagesize").getAsInt(); int totalEntities = obj.get("total").getAsInt(); JsonArray elements = getEntities(obj); if (page * pageSize < totalEntities) { // fetch the next page elements.addAll(fetchArray(entityType, page + 1)); } return elements; } else { throw new JsonParseException("Invalid response from Vendor API. Request should return " + "either a JsonArray or a JsonObject, but returned " + element.getClass().getName() + ". Entity fetcher is " + getFetcher()); } }
From source file:com.google.wave.api.RobotSerializer.java
License:Apache License
/** * Deserializes operations. This method supports only the new JSON-RPC style * operations.// ww w . jav a 2 s . c o m * * @param jsonString the operations JSON string to deserialize. * @return a list of {@link OperationRequest},that represents the operations. * @throws InvalidRequestException if there is a problem deserializing the * operations. */ public List<OperationRequest> deserializeOperations(String jsonString) throws InvalidRequestException { if (Util.isEmptyOrWhitespace(jsonString)) { return Collections.emptyList(); } // Parse incoming operations. JsonArray requestsAsJsonArray = null; JsonElement json = null; try { json = jsonParser.parse(jsonString); } catch (JsonParseException e) { throw new InvalidRequestException("Couldn't deserialize incoming operations: " + jsonString, null, e); } if (json.isJsonArray()) { requestsAsJsonArray = json.getAsJsonArray(); } else { requestsAsJsonArray = new JsonArray(); requestsAsJsonArray.add(json); } // Convert incoming operations into a list of JsonRpcRequest. ProtocolVersion protocolVersion = determineProtocolVersion(requestsAsJsonArray); PROTOCOL_VERSION_COUNTERS.get(protocolVersion).incrementAndGet(); List<OperationRequest> requests = new ArrayList<OperationRequest>(requestsAsJsonArray.size()); for (JsonElement requestAsJsonElement : requestsAsJsonArray) { validate(requestAsJsonElement); requests.add(getGson(protocolVersion).fromJson(requestAsJsonElement, OperationRequest.class)); } return requests; }