List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.ibm.watson.movieapp.dialog.rest.SearchTheMovieDbProxyResource.java
License:Open Source License
/** * Loads an internal cache which gets refreshed periodically. We are depending on a third party system (themoviedb.org) so it is possible that their genres * may change over time or the url used to retrieve posters will change. As a result we periodically (for now daily) check to make sure we have the correct * values for these./*from w w w . j av a 2 s .c o m*/ * * @return a cache which looks up certain values in themoviedb.org */ private static LoadingCache<String, String> loadTheMovieDbCache() { return CacheBuilder.newBuilder().initialCapacity(8).expireAfterWrite(1, TimeUnit.DAYS) // refresh once a day .maximumSize(20).concurrencyLevel(5).build(new CacheLoader<String, String>() { private HashMap<String, String> genresAndIds = new HashMap<>(); @Override public String load(String key) throws Exception { if (IMAGE_CACHE_KEY.equals(key)) { // Get the poster path. String imageBaseURL = null; URI uri = buildUriStringFromParamsHash(new Hashtable<String, String>(), CONFIGURATION); JsonObject tmdbResponse = UtilityFunctions.httpGet(createTMDBHttpClient(), uri); if (tmdbResponse.has("images")) { //$NON-NLS-1$ JsonObject images = tmdbResponse.get("images").getAsJsonObject(); //$NON-NLS-1$ imageBaseURL = UtilityFunctions.getPropValue(images, "base_url"); //$NON-NLS-1$ if (images.has("backdrop_sizes")) { //$NON-NLS-1$ JsonArray sizes = images.get("backdrop_sizes").getAsJsonArray(); //$NON-NLS-1$ String size = sizes.get(0).getAsString(); if (size != null) { imageBaseURL += size; } } return imageBaseURL; } } if (key != null && key.startsWith(GENRE_CACHE_PREFIX)) { if (genresAndIds.isEmpty()) { URI uri = buildUriStringFromParamsHash(null, LIST_GENRES); JsonObject tmdbResponse = UtilityFunctions.httpGet(createTMDBHttpClient(), uri); if (tmdbResponse.has("genres")) { //$NON-NLS-1$ JsonArray genres = tmdbResponse.getAsJsonArray("genres"); //$NON-NLS-1$ for (JsonElement element : genres) { JsonObject genre = element.getAsJsonObject(); genresAndIds.put(genre.get("name").getAsString().toLowerCase(), //$NON-NLS-1$ genre.get("id").getAsString()); //$NON-NLS-1$ } } } String ret = genresAndIds.get(key.substring(GENRE_CACHE_PREFIX.length()).toLowerCase()); return ret != null ? ret : ""; //$NON-NLS-1$ } return null; } }); }
From source file:com.ibm.watson.movieapp.dialog.rest.SearchTheMovieDbProxyResource.java
License:Open Source License
/** * Discovers movies based on the preferences specified * <p>//from w w w .j a va2s .c o m * This will make a HTTP GET request to TMDB server to find movies based on the parameters specified. * * @param genre the genre specified by the user * @param rating the rating specified by the user * @param recency the recency preference specified by the user ("upcoming" or "current") * @param currentIndex the index representing the number of results already shown to the end user * @param pageNum the page number from the set of result pages returned by TMDB for the search query * * See <a href="http://docs.themoviedb.apiary.io/#reference/discover/discovermovie">here</a> for more details * @return the {@code WDSConversationPayload} object containing a list of {@code MoviePayload} objects and a response message from WDS * @throws ClientProtocolException if it is unable to execute the call to TMDB API * @throws IllegalStateException if the HTTP GET method cannot parse the response stream * @throws IOException if it is unable to execute the call to TMDB API * @throws HttpException if the HTTP call responded with a status code other than 200 or 201 * @throws URISyntaxException if the uri being built is in the incorrect format * @throws WatsonTheatersException if the recency parameter is "null" * @throws ParseException if the movie release date cannot be parsed correctly */ public WDSConversationPayload discoverMovies(String genre, String rating, String recency, int currentIndex, int pageNum, boolean searchForward) throws ClientProtocolException, IllegalStateException, IOException, HttpException, URISyntaxException, WatsonTheatersException, ParseException { // Initializes url params to be updated. String errorMessage = null, issue = null; Hashtable<String, String> uriParamsHash = new Hashtable<String, String>(); // Check if recency is null. if (recency.equals("null")) { //$NON-NLS-1$ errorMessage = Messages.getString("SearchTheMovieDbProxyResource.RECENCY_INFO_NEEDED"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.RECENCY_UNSPECIFIED"); //$NON-NLS-1$ throw new WatsonTheatersException(errorMessage, issue); } if (genre != null && !genre.isEmpty()) { uriParamsHash.put("with_genres", getGenreId(genre).toString()); //$NON-NLS-1$ } if (rating != null && !rating.isEmpty()) { uriParamsHash.put("certification_country", "US"); //$NON-NLS-1$ //$NON-NLS-2$ uriParamsHash.put("certification", rating); //$NON-NLS-1$ } // Add the pageNumber and sort in decreasing order of votes_average. uriParamsHash.put("page", String.valueOf(pageNum)); //$NON-NLS-1$ uriParamsHash.put("sort_by", "popularity.desc"); //$NON-NLS-1$ //$NON-NLS-2$ // Add date filters to uriHash depending on recency. uriParamsHash = addDateFilters(recency, uriParamsHash); // Build the URI. URI uri = buildUriStringFromParamsHash(uriParamsHash, DISCOVER); // Make the REST call. JsonObject responseObj = UtilityFunctions.httpGet(createTMDBHttpClient(), uri); JsonArray jArray = responseObj.getAsJsonArray("results"); //$NON-NLS-1$ // If previous search, set the currentIndex in order to extract last set of movies. if (!searchForward) { if (currentIndex % 20 == 0 || currentIndex % 20 > 10) { currentIndex = 0; } else { currentIndex = 10; } } // Get the next 10 movies from the returned payload from themoviedb List<MoviePayload> movies = getResults(jArray, (searchForward ? (currentIndex - ((pageNum - 1) * 20)) : currentIndex)); // Return payload. WDSConversationPayload moviesPayload = new WDSConversationPayload(); moviesPayload.setMovies(movies); moviesPayload.setTotalPages(Integer.parseInt(UtilityFunctions.getPropValue(responseObj, "total_pages"))); //$NON-NLS-1$ moviesPayload.setNumMovies(Integer.parseInt(UtilityFunctions.getPropValue(responseObj, "total_results"))); //$NON-NLS-1$ return moviesPayload; }
From source file:com.ibm.watson.movieapp.dialog.rest.SearchTheMovieDbProxyResource.java
License:Open Source License
/** * Gets the details for the movie selected * <p>//from w ww . j a v a2 s. c om * This will retrieve the following movie info using themoviedb.org's /moviedetails API: * <ul> * <li>releaseDate the movie's release date * <li>releaseDateStr the movie's release date in String format * <li>genre the movie genre * <li>genreId the movie genre id * <li>movieId the movie id * <li>certification the movie certification * <li>certificationCountry the country of certification * <li>popularity the movie popularity (out of 10) * <li>movieName the movie name * <li>overview the brief summary of the movie * <li>runtime the runtime (in minutes) * <li>homepageUrl the url to the movie's homepage * <li>posterPath the path to the movie poster * <li>trailerUrl the url to the movie's trailer * </ul> * * @param movieId the movie id of the movie selected, not null * @param movieName the name of the movie selected * @return a response containing either of these two entities- {@code MoviePayload} or {@code ServerErrorPayload} */ @GET @Path("/getMovieDetails") @Produces(MediaType.APPLICATION_JSON) public Response getMovieDetails(@QueryParam("movieid") String movieId, @QueryParam("moviename") String movieName) { String errorMessage = null, issue = null; try { if (movieId == null) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.MOVIE_NOT_FOUND"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.MOVIE_ID_NOT_SPECIFIED"); //$NON-NLS-1$ throw new WatsonTheatersException(errorMessage, issue); } // Get general movie info. Hashtable<String, String> params = new Hashtable<>(); params.put("append_to_response", "releases,videos"); //Make a single API call to retrieve all the info we need. //$NON-NLS-1$ //$NON-NLS-2$ URI uri = buildUriStringFromParamsHash(params, MOVIE_DETAILS + movieId); JsonObject tmdbResponse = UtilityFunctions.httpGet(createTMDBHttpClient(), uri); MoviePayload moviePayload = new MoviePayload(); moviePayload.setMovieId(Integer.parseInt(tmdbResponse.get("id").toString())); //$NON-NLS-1$ moviePayload.setMovieName(UtilityFunctions.getPropValue(tmdbResponse, "title")); //$NON-NLS-1$ moviePayload.setHomepageUrl(UtilityFunctions.getPropValue(tmdbResponse, "homepage")); //$NON-NLS-1$ moviePayload.setOverview(UtilityFunctions.getPropValue(tmdbResponse, "overview")); //$NON-NLS-1$ moviePayload.setPosterPath(UtilityFunctions.getPropValue(tmdbResponse, "poster_path")); //$NON-NLS-1$ if (Integer.parseInt(UtilityFunctions.getPropValue(tmdbResponse, "vote_count")) >= 10) { moviePayload.setPopularity( Double.parseDouble(UtilityFunctions.getPropValue(tmdbResponse, "vote_average"))); //$NON-NLS-1$ } else { moviePayload.setPopularity(-1.0); //$NON-NLS-1$ } moviePayload.setReleaseDateStr(UtilityFunctions.getPropValue(tmdbResponse, "release_date")); //$NON-NLS-1$ Date rDate = movieDateFormatter.parse(moviePayload.getReleaseDateStr()); moviePayload.setReleaseDate(rDate); String time = UtilityFunctions.getPropValue(tmdbResponse, "runtime"); //$NON-NLS-1$ if (time != null && !time.isEmpty()) { moviePayload.setRuntime(Integer.parseInt(time)); } String path = UtilityFunctions.getPropValue(tmdbResponse, "poster_path"); //$NON-NLS-1$ if (path != null) { try { String imageBaseURL = theMovieDbCache.get("imageUrl"); //$NON-NLS-1$ moviePayload.setPosterPath(imageBaseURL + path); } catch (ExecutionException e) { UtilityFunctions.logger .error(Messages.getString("SearchTheMovieDbProxyResource.CACHE_FAIL_IMAGE_URL"), e); //$NON-NLS-1$ } } // Get the link for the trailer here and add it to payload. JsonObject videos = tmdbResponse.getAsJsonObject("videos"); //$NON-NLS-1$ if (videos != null) { JsonArray jArray = videos.getAsJsonArray("results"); //$NON-NLS-1$ for (int i = 0; i < jArray.size(); i++) { JsonObject obj = jArray.get(i).getAsJsonObject(); String site = UtilityFunctions.getPropValue(obj, "site"); //$NON-NLS-1$ String type = UtilityFunctions.getPropValue(obj, "type"); //$NON-NLS-1$ if ("Trailer".equalsIgnoreCase(type)) { //$NON-NLS-1$ String key = UtilityFunctions.getPropValue(obj, "key"); //$NON-NLS-1$ if (key != null && "youtube".equalsIgnoreCase(site)) { //$NON-NLS-1$ // create youtube url String trailerUrl = "https://www.youtube.com/embed/" + key //$NON-NLS-1$ + "?controls=0&showinfo=0"; //$NON-NLS-1$ moviePayload.setTrailerUrl(trailerUrl); } } } } // Get the certification and release date and add it to the payload. JsonObject releases = tmdbResponse.getAsJsonObject("releases"); //$NON-NLS-1$ if (releases != null) { JsonArray jArray = releases.getAsJsonArray("countries"); //$NON-NLS-1$ for (int i = 0; i < jArray.size(); i++) { JsonObject obj = (JsonObject) jArray.get(i); if (obj.get("iso_3166_1").getAsString().equals("US")) { //$NON-NLS-1$ //$NON-NLS-2$ moviePayload.setCertificationCountry("US"); //$NON-NLS-1$ moviePayload.setCertification(UtilityFunctions.getPropValue(obj, "certification")); //$NON-NLS-1$ break; } } } return Response.ok(moviePayload, MediaType.APPLICATION_JSON_TYPE).build(); } catch (URISyntaxException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.TMDB_INVALID_URL"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.URI_EXCEPTION"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (ClientProtocolException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.TMDB_CALL_FAIL"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.TMDB_HTTP_GET_CLIENT_EXCEPTION"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (IllegalStateException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.TMDB_REQUEST_FAIL"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.TMDB_HTTP_GET_ILLEGAL_STATE_EXCEPTION"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (IOException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.TMDB_REQUEST_FAIL"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.IOEXCEPTION_TMDB_GET"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (HttpException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.TMDB_REQUEST_FAIL"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.TMDB_HTTP_GET_EXCEPTION"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (ParseException e) { errorMessage = Messages.getString("SearchTheMovieDbProxyResource.UNEXPECTED_RESPONSE"); //$NON-NLS-1$ issue = Messages.getString("SearchTheMovieDbProxyResource.HTTPGET_PARSE_EXCEPTION"); //$NON-NLS-1$ UtilityFunctions.logger.error(issue, e); } catch (WatsonTheatersException e) { UtilityFunctions.logger.error(issue, e); } return Response.serverError().entity(new ServerErrorPayload(errorMessage, issue)).build(); }
From source file:com.ibm.watson.WatsonVRTraining.util.PatchedCredentialUtils.java
License:Open Source License
/** * Returns the apiKey from the VCAP_SERVICES or null if doesn't exists. If * plan is specified, then only credentials for the given plan will be * returned.//from ww w . j ava 2 s . c o m * * @param serviceName * the service name * @param plan * the service plan: standard, free or experimental * @return the API key */ public static String getVRAPIKey(String plan) { final JsonObject services = getVCAPServices(); if (services == null) return null; for (final Entry<String, JsonElement> entry : services.entrySet()) { final String key = entry.getKey(); if (key.startsWith(WATSON_VISUAL_RECOGNITION)) { final JsonArray servInstances = services.getAsJsonArray(key); for (final JsonElement instance : servInstances) { final JsonObject service = instance.getAsJsonObject(); final String instancePlan = service.get(PLAN).getAsString(); if (plan == null || plan.equalsIgnoreCase(instancePlan)) { final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS); return credentials.get(APIKEY).getAsString(); } } } } return null; }
From source file:com.ibm.watson.WatsonVRTraining.util.PatchedCredentialUtils.java
License:Open Source License
public static String getVRurl(String plan) { final JsonObject services = getVCAPServices(); if (services == null) return null; for (final Entry<String, JsonElement> entry : services.entrySet()) { final String key = entry.getKey(); if (key.startsWith(WATSON_VISUAL_RECOGNITION)) { final JsonArray servInstances = services.getAsJsonArray(key); for (final JsonElement instance : servInstances) { final JsonObject service = instance.getAsJsonObject(); final String instancePlan = service.get(PLAN).getAsString(); if (plan == null || plan.equalsIgnoreCase(instancePlan)) { final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS); return credentials.get(vr_url_key).getAsString(); }//w w w. j a va 2 s .co m } } } return null; }
From source file:com.ibm.watson.WatsonVRTraining.util.PatchedCredentialUtils.java
License:Open Source License
public static String getDBuname(String plan) { final JsonObject services = getVCAPServices(); if (services == null) return null; for (final Entry<String, JsonElement> entry : services.entrySet()) { final String key = entry.getKey(); if (key.startsWith(WATSON_CLOUDANT_DB)) { final JsonArray servInstances = services.getAsJsonArray(key); for (final JsonElement instance : servInstances) { final JsonObject service = instance.getAsJsonObject(); final String instancePlan = service.get(PLAN).getAsString(); if (plan == null || plan.equalsIgnoreCase(instancePlan)) { final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS); return credentials.get(db_uname_key).getAsString(); }// www . j a v a 2 s .c o m } } } return null; }
From source file:com.ibm.watson.WatsonVRTraining.util.PatchedCredentialUtils.java
License:Open Source License
public static String getDBpass(String plan) { final JsonObject services = getVCAPServices(); if (services == null) return null; for (final Entry<String, JsonElement> entry : services.entrySet()) { final String key = entry.getKey(); if (key.startsWith(WATSON_CLOUDANT_DB)) { final JsonArray servInstances = services.getAsJsonArray(key); for (final JsonElement instance : servInstances) { final JsonObject service = instance.getAsJsonObject(); final String instancePlan = service.get(PLAN).getAsString(); if (plan == null || plan.equalsIgnoreCase(instancePlan)) { final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS); return credentials.get(db_pass_key).getAsString(); }/*from w ww .j a v a 2s. c o m*/ } } } return null; }
From source file:com.ibm.watson.WatsonVRTraining.util.PatchedCredentialUtils.java
License:Open Source License
public static String getDBurl(String plan) { final JsonObject services = getVCAPServices(); if (services == null) return null; for (final Entry<String, JsonElement> entry : services.entrySet()) { final String key = entry.getKey(); if (key.startsWith(WATSON_CLOUDANT_DB)) { final JsonArray servInstances = services.getAsJsonArray(key); for (final JsonElement instance : servInstances) { final JsonObject service = instance.getAsJsonObject(); final String instancePlan = service.get(PLAN).getAsString(); if (plan == null || plan.equalsIgnoreCase(instancePlan)) { final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS); return credentials.get(db_url_key).getAsString(); }//w ww. j a va 2 s . c o m } } } return null; }
From source file:com.imaginea.betterdocs.BetterDocsAction.java
License:Apache License
private ArrayList<Integer> getLineNumbers(Collection<String> imports, String tokens) { ArrayList<Integer> lineNumbers = new ArrayList<Integer>(); JsonReader reader = new JsonReader(new StringReader(tokens)); reader.setLenient(true);//from ww w . j a v a2s.co m JsonArray tokensArray = new JsonParser().parse(reader).getAsJsonArray(); for (JsonElement token : tokensArray) { JsonObject jObject = token.getAsJsonObject(); String importName = jObject.getAsJsonPrimitive(IMPORT_NAME).getAsString(); if (imports.contains(importName)) { JsonArray lineNumbersArray = jObject.getAsJsonArray(LINE_NUMBERS); for (JsonElement lineNumber : lineNumbersArray) { lineNumbers.add(lineNumber.getAsInt()); } } } return lineNumbers; }
From source file:com.imaginea.betterdocs.BetterDocsAction.java
License:Apache License
private String getContentsForFile(String file) { String esFileQueryJson = getJsonForFileContent(file); String esFileResultJson = getESResultJson(esFileQueryJson, esURL + SOURCEFILE_SEARCH); JsonReader reader = new JsonReader(new StringReader(esFileResultJson)); reader.setLenient(true);//from w ww. ja v a 2 s .c o m JsonElement jsonElement = new JsonParser().parse(reader); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject hitsObject = jsonObject.getAsJsonObject(HITS); JsonArray hitsArray = hitsObject.getAsJsonArray(HITS); JsonObject hitObject = hitsArray.get(0).getAsJsonObject(); JsonObject sourceObject = hitObject.getAsJsonObject(SOURCE); //Replacing \r as it's treated as bad end of line character String fileContent = sourceObject.getAsJsonPrimitive(FILE_CONTENT).getAsString().replaceAll("\r", ""); return fileContent; }