List of usage examples for com.google.gson JsonElement getAsInt
public int getAsInt()
From source file:io.motown.operatorapi.json.gson.deserializer.EvseIdTypeAdapterDeserializer.java
License:Apache License
@Override public EvseId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { if (!json.isJsonPrimitive()) { throw new JsonParseException("EvseId must be a JSON primitive"); }/*from w ww . ja v a2s . c o m*/ int evseId; try { evseId = json.getAsInt(); } catch (ClassCastException | IllegalStateException | NumberFormatException e) { throw new JsonParseException("EvseId must be a JSON integer", e); } return new EvseId(evseId); }
From source file:io.openvidu.client.internal.JsonRoomUtils.java
License:Apache License
@SuppressWarnings("unchecked") private static <T> T getConverted(JsonElement paramValue, String property, Class<T> type, boolean allowNull) { if (paramValue == null) { if (allowNull) { return null; } else {/* w ww .jav a 2s . co m*/ throw new OpenViduException(Code.TRANSPORT_ERROR_CODE, "Invalid method lacking parameter '" + property + "'"); } } if (type == String.class) { if (paramValue.isJsonPrimitive()) { return (T) paramValue.getAsString(); } } if (type == Integer.class) { if (paramValue.isJsonPrimitive()) { return (T) Integer.valueOf(paramValue.getAsInt()); } } if (type == JsonArray.class) { if (paramValue.isJsonArray()) { return (T) paramValue.getAsJsonArray(); } } throw new OpenViduException(Code.TRANSPORT_ERROR_CODE, "Param '" + property + "' with value '" + paramValue + "' is not a " + type.getName()); }
From source file:io.robusta.rra.representation.implementation.GsonRepresentation.java
License:Apache License
/** * convert a jsonElement into Object/* w ww . j a va2 s . c o m*/ * * @param type * @param element * @return * @throws RepresentationException */ protected <T> T get(Class<T> type, JsonElement element) throws RepresentationException { if (type == Long.class) { return (T) (Long) element.getAsLong(); } else if (type == Integer.class) { return (T) (Integer) element.getAsInt(); } else if (type == Short.class) { return (T) (Short) element.getAsShort(); } else if (type == Byte.class) { return (T) (Byte) element.getAsByte(); } else if (type == BigInteger.class) { return (T) (BigInteger) element.getAsBigInteger(); } else if (type == Double.class) { return (T) (Double) element.getAsDouble(); } else if (type == Float.class) { return (T) (Float) element.getAsFloat(); } else if (type == BigDecimal.class) { return (T) (BigDecimal) element.getAsBigDecimal(); } else if (type == Boolean.class) { return (T) (Boolean) element.getAsBoolean(); } else if (type == String.class) { return (T) element.getAsString(); } else { return (T) gson.fromJson(element, type); } }
From source file:jmm.api.tmdb.TMDBMovieWrapper.java
License:Open Source License
/** * Get the basic movie information for a specific movie id. <br/> * <b>Bold</b> parameters are <b>required</b>. * /*ww w . j a v a2 s . c om*/ * @param id <b>the movie id</b> * @param language ISO 639-1 code. * @param append_to_response Comma separated, any movie method * @return the movie wth the given id <br/>null, if no movie was found with the given id */ public TMDBVideoFile findMovie(String id, String language, String append_to_response) { paramsMap.clear(); //requiered parameters if (id == null) { throw new NullPointerException("Param: " + "id" + "must not be null"); } //optional parameters if (language != null) { paramsMap.put(PARAM_LANGUAGE, language); } if (append_to_response != null) { paramsMap.put(PARAM_APPEND, append_to_response); } String url = buildUrl(API_MOVIE + "/" + id); JsonElement element = callAPI(url); //handle response TMDBVideoFile searchResult = null; if (!element.isJsonNull()) { String title = element.getAsJsonObject().get("title").getAsString(); searchResult = new TMDBVideoFile(title); JsonElement value; value = element.getAsJsonObject().get("adult"); if (!value.isJsonNull()) { searchResult.setAdult(value.getAsBoolean()); if (searchResult.isAdult()) { searchResult.setFsk(VideoFile.FSK.FSK_18); } } value = element.getAsJsonObject().get("backdrop_path"); if (!value.isJsonNull()) { searchResult.setBackdropPath(API_BASE_IMAGEURL + Backdrop_Sizes.w780 + value.getAsString()); } //genres value = element.getAsJsonObject().get("genres"); if (!value.isJsonNull()) { JsonArray genres = value.getAsJsonArray(); if (genres.isJsonArray()) { Iterator<JsonElement> genresIterator = genres.iterator(); while (genresIterator.hasNext()) { JsonElement genreElement = genresIterator.next(); value = genreElement.getAsJsonObject().get("id"); if (!value.isJsonNull()) { int genreID = value.getAsInt(); Genre genre = Genre.getGenreByTMDBID(genreID); if (genre != null) { searchResult.addGenreKey(genre.getGenreKey()); } else { value = genreElement.getAsJsonObject().get("name"); String exceptionString; if (!value.isJsonNull()) { exceptionString = "Missing genre in resource bundle: " + value.getAsString() + " " + genreID; } else { exceptionString = "Missing genre in resource bundle: " + genreID; } LOG.warn(exceptionString); } } // value = genreElement.getAsJsonObject().get("name"); // if(!value.isJsonNull()){ // String localizedGenre = value.getAsString(); // String genreKey = LocaleManager.getInstance().determineGenreKeyByLocale(localizedGenre); // if(genreKey == null){ // MyExceptionHandler.uncaughtExceptionLogger.warning("Missing genre in resource bundle: " + localizedGenre); // }else{ // searchResult.addGenre(genreKey); // } // } } } } value = element.getAsJsonObject().get("id"); if (!value.isJsonNull()) { searchResult.setTmdbID(value.getAsString()); } value = element.getAsJsonObject().get("imdb_id"); if (!value.isJsonNull()) { searchResult.setImdbID(value.getAsString()); } value = element.getAsJsonObject().get("original_title"); if (!value.isJsonNull()) { searchResult.setOriginalTitle(value.getAsString()); } value = element.getAsJsonObject().get("overview"); if (!value.isJsonNull()) { searchResult.setDescription(value.getAsString()); } value = element.getAsJsonObject().get("poster_path"); if (!value.isJsonNull()) { searchResult.setImagePath(API_BASE_IMAGEURL + Poster_Sizes.w342 + value.getAsString()); } //Publisher value = element.getAsJsonObject().get("production_companies"); if (!value.isJsonNull()) { JsonArray publishers = value.getAsJsonArray(); if (publishers.isJsonArray()) { Iterator<JsonElement> publishersIterator = publishers.iterator(); while (publishersIterator.hasNext()) { //Set only the first publisher JsonElement publisherElement = publishersIterator.next(); value = publisherElement.getAsJsonObject().get("name"); if (!value.isJsonNull()) { String publisher = value.getAsString(); searchResult.setPublisher(publisher); break; } } } } value = element.getAsJsonObject().get("runtime"); if (!value.isJsonNull()) { searchResult.setPlaytime(value.getAsInt()); } value = element.getAsJsonObject().get("vote_average"); if (!value.isJsonNull()) { searchResult.setTmdbRating(value.getAsDouble()); searchResult.setOnlineRating(value.getAsDouble()); } //release date value = element.getAsJsonObject().get("release_date"); if (!value.isJsonNull()) { String rlsDateString = value.getAsString(); try { Date date = new SimpleDateFormat("yyyy-mm-dd").parse(rlsDateString); searchResult.setReleaseDate(date); String releaseYear = new SimpleDateFormat("yyyy").format(date); if (!releaseYear.isEmpty()) { searchResult.setReleaseYear(Integer.valueOf(releaseYear)); } } catch (ParseException | NumberFormatException ex) { LOG.warn("Release Year " + rlsDateString + "cannot be parsed into a valid format for title: " + title + ".", ex); searchResult.setReleaseYear(0); } } //{"adult":false,"backdrop_path":"/eZxahf9ATsv3oQPtvZPqSZkAO7V.jpg","belongs_to_collection":{"id":1241,"name":"Harry Potter Collection", //"poster_path":"/fuWOg0iLKPRGTlg7lq4tWDBt5tu.jpg","backdrop_path":"/tpDcuXZGqEoU6CxuJ7e4S2NTIoS.jpg"},"budget":250000000, //"genres":[{"id":12,"name":"Abenteuer"},{"id":18,"name":"Drama"},{"id":14,"name":"Fantasy"},{"id":10751,"name":"Familie"}], //"homepage":"http://harrypotter.warnerbros.de/hp7a/","id":12444,"imdb_id":"tt0926084","original_title":"Harry Potter and the Deathly Hallows: Part 1", //"overview":"Harry sieht sich einer vollkommen vernderten Welt gegenber. Die Todesesser haben das Zauberministerium unter ihre Kontrolle gebracht und es tobt ein offener Kampf zwischen den Mchten des Guten und Bsen. Harry hat sich mit Hermine (Emma Watson) und Ron (Rupert Grint) auf die Suche nach den Horkuxen, magischen Objekten, die die Unsterblichkeit von Lord Voldemort (Ralph Fiennes) garantieren und zerstrt werden mssen. Der dunkle Lord hat seinerseits ein Kopfgeld auf Harry ausgesetzt, dener will sich das Vergngen den Jungen der lebte mit den eigenen Hnden zu tten, nicht nehmen lassen. Unterdessen stt Harry auf die Legende von den Heiligtmern des Todes, die ihm im Kampf gegen seinen Erzfeind das Leben retten knnte. Und so strebt alles unaufhaltsam der finalen Konfrontation zwischen den beiden Magiern entegegen, auf die Harry sich seit Beginn seiner Schullaufbahn vorbereitet hat.", //"popularity":305437.691,"poster_path":"/3ssNt5cCFYGne7OrBFkFFUVq8Cx.jpg","production_companies":[{"name":"Warner Bros. Pictures","id":174}], //"production_countries":[{"iso_3166_1":"US","name":"United States of America"},{"iso_3166_1":"GB","name":"United Kingdom"}], //"release_date":"2010-11-19","revenue":954305868,"runtime":146, //"spoken_languages":[{"iso_639_1":"en","name":"English"},{"iso_639_1":"fr","name":"Franais"},{"iso_639_1":"ja","name":"???"}], //"status":"Released","tagline":"","title":"Harry Potter und die Heiligtmer des Todes - Teil 1","vote_average":8.3,"vote_count":74} if (append_to_response != null && append_to_response.equalsIgnoreCase("casts")) { addActorsAndDirector(element, searchResult); } } return searchResult; }
From source file:jmm.api.tmdb.TMDBMovieWrapper.java
License:Open Source License
private void addActorsAndDirector(JsonElement rootElement, TMDBVideoFile videoFile) { //handle response if (!rootElement.isJsonNull()) { JsonElement value; //Publisher value = rootElement.getAsJsonObject().get("casts"); if (value != null && !value.isJsonNull()) { value = value.getAsJsonObject().get("cast"); if (value.isJsonArray()) { JsonArray cast = value.getAsJsonArray(); Iterator<JsonElement> castIterator = cast.iterator(); while (castIterator.hasNext()) { JsonElement actorElement = castIterator.next(); value = actorElement.getAsJsonObject().get("name"); if (!value.isJsonNull()) { Actor actor = new Actor(value.getAsString()); value = actorElement.getAsJsonObject().get("id"); if (!value.isJsonNull()) { actor.setTmdbID(value.getAsInt()); }//from ww w .j ava 2 s .c o m value = actorElement.getAsJsonObject().get("profile_path"); if (!value.isJsonNull()) { actor.setProfilePicturePath( API_BASE_IMAGEURL + Profile_Sizes.w185 + value.getAsString()); } videoFile.addActor(actor); } } } value = rootElement.getAsJsonObject().get("casts"); value = value.getAsJsonObject().get("crew"); if (value.isJsonArray()) { JsonArray crew = value.getAsJsonArray(); //Look for director Iterator<JsonElement> crewIterator = crew.iterator(); while (crewIterator.hasNext()) { JsonElement crewElement = crewIterator.next(); value = crewElement.getAsJsonObject().get("job"); if (!value.isJsonNull() && (value.getAsString().equalsIgnoreCase("Director"))) { value = crewElement.getAsJsonObject().get("name"); if (!value.isJsonNull()) { videoFile.setDirector(value.getAsString()); } } } } } } }
From source file:me.grapebaba.hyperledger.fabric.ChaincodeSpecTypeEnumTypeAdapter.java
License:Apache License
@Override public ChaincodeSpec.Type deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return ChaincodeSpec.Type.values()[json.getAsInt()]; }
From source file:me.grapebaba.hyperledger.fabric.ConfidentialityLevelEnumTypeAdapter.java
License:Apache License
@Override public ConfidentialityLevel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return ConfidentialityLevel.values()[json.getAsInt()]; }
From source file:me.grapebaba.hyperledger.fabric.PeerEndpointTypeEnumTypeAdapter.java
License:Apache License
@Override public PeerEndpoint.Type deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return PeerEndpoint.Type.values()[json.getAsInt()]; }
From source file:me.grapebaba.hyperledger.fabric.TransactionTypeEnumTypeAdapter.java
License:Apache License
@Override public Transaction.Type deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Transaction.Type.values()[json.getAsInt()]; }
From source file:net.creativeparkour.GameManager.java
License:Open Source License
/** * <em>Third-party plugins cannot use this method through CreativeParkour's API (it will throw an {@code InvalidQueryResponseException}).</em><br> * Method called when <a href="https://creativeparkour.net" target="_blank">creativeparkour.net</a> responds to a query. * @param json/* www. j a v a 2 s. co m*/ * @param rep * @param sender * @throws InvalidQueryResponseException If the {@code Request} has not been registered before. */ public static void reponseListe(JsonObject json, String rep, CommandSender sender) throws InvalidQueryResponseException { if (CPRequest.verifMethode("reponseListe") && !CreativeParkour.erreurRequete(json, sender) && json.get("data") != null) { Bukkit.getScheduler().runTaskAsynchronously(CreativeParkour.getPlugin(), new Runnable() { public void run() { mapsTelechargeables.clear(); // Liste des maps tlchargeables if (json.get("data").isJsonObject()) { JsonElement o = json.get("data").getAsJsonObject().get("maps"); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement m : liste) { JsonObject map = m.getAsJsonObject(); if (map.get("verConversion").getAsInt() <= CreativeParkour.getServVersion()) // We only want compatible maps mapsTelechargeables.add(new CPMap(map.get("id").getAsString(), map.get("createur").getAsString(), map.get("nom").getAsString(), map.get("difficulte").getAsFloat(), map.get("qualite").getAsFloat(), map.get("versionMin").getAsInt(), map.get("verConversion").getAsInt())); } // Mise jour des inventaires de slection de maps des joueurs qui l'ont ouvert if (!mapsTelechargeables.isEmpty()) { Bukkit.getScheduler().scheduleSyncDelayedTask(CreativeParkour.getPlugin(), new Runnable() { public void run() { for (Joueur j : joueurs) { if (j.invSelection != null && j.getPlayer() .hasPermission("creativeparkour.download")) j.invSelection.mettreAJourTelechargeables(); } } }); } } // Liste des maps partages par le serveur, pour la suite... o = json.get("data").getAsJsonObject().get("mapsPartagees"); List<String> mapsPartagees = new ArrayList<String>(); if (o != null && o.isJsonArray()) { Type listType = new TypeToken<List<String>>() { }.getType(); mapsPartagees = new Gson().fromJson(o, listType); } // Mise jour des votes, et remplissage d'une liste pour envoyer les votes locaux StringBuffer notesAEnvoyer = new StringBuffer(); o = json.get("data").getAsJsonObject().get("notes"); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement e : liste) { JsonObject obj = e.getAsJsonObject(); CPMap m = getMap(UUID.fromString(obj.get("uuidMap").getAsString())); if (m != null && (m.getState() == CPMapState.DOWNLOADED || mapsPartagees.contains(m.getUUID().toString()))) { m.setDifficulty(obj.get("d").getAsFloat()); m.setQuality(obj.get("q").getAsFloat()); m.sauvegarder(); // Votes envoyer for (Entry<String, Vote> entry : m.getVotes().entrySet()) { if (entry.getValue().getDifficulty() > 0 || entry.getValue().getQuality() > 0) notesAEnvoyer.append(m.getUUID().toString()).append('_') .append(entry.getKey()).append(':') .append(entry.getValue().toConfigString()).append(";"); } } } } if (notesAEnvoyer.length() > 0) notesAEnvoyer.deleteCharAt(notesAEnvoyer.length() - 1); // Mise jour des noms des joueurs o = json.get("data").getAsJsonObject().get("nomsChanges"); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement e : liste) { JsonObject obj = e.getAsJsonObject(); String uuid = obj.get("uuid").getAsString(); String nom = obj.get("nom").getAsString(); String nom2 = Bukkit.getOfflinePlayer(UUID.fromString(uuid)).getName(); if (nom2 == null || nom2.isEmpty()) // Il ne faut pas mettre jour les joueurs qui sont sur ce serveur { NameManager.enregistrerNomJoueur(uuid, nom); } } } Set<CPMap> mapsAMettreAJour = new HashSet<CPMap>(); // Suppression des fantmes supprimer o = json.get("data").getAsJsonObject().get("fantomesASupprimer"); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement e : liste) { String nomFantome = e.getAsString(); UUID uuidMap = UUID.fromString(nomFantome.split("_")[0]); CPMap map = getMap(uuidMap); if (map != null) { File f = getFichierTemps(nomFantome); if (f != null) { CPTime t = map.getTempsAvecFichier(f); if (t != null && t.etat != EtatTemps.LOCAL) { supprimerFichiersTemps(t.playerUUID, uuidMap, false); mapsAMettreAJour.add(map); } } } } } // Enregistrement des fantmes envoys (en partie) par le site if (Config.getConfig().getBoolean("online.download ghosts")) { o = json.get("data").getAsJsonObject().get("fantomesATelecharger"); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement e : liste) { JsonObject obj = e.getAsJsonObject(); CPMap m = getMap(UUID.fromString(obj.get("uuidMap").getAsString())); if (m != null && m.isPlayable()) { CPTime t = new CPTime(UUID.fromString(obj.get("uuidJoueur").getAsString()), m, obj.get("ticks").getAsInt()); t.etat = EtatTemps.TO_DOWNLOAD; t.realMilliseconds = obj.get("millisecondes").getAsLong(); t.sauvegarder(new Date(obj.get("date").getAsLong())); mapsAMettreAJour.add(m); NameManager.enregistrerNomJoueur(obj.get("uuidJoueur").getAsString(), obj.get("nomJoueur").getAsString()); } } } } // Mise jour des temps dans les maps Set<CPMap> mapsAvecPanneau = Panneau.getMapsAvecPanneauClassement(); for (CPMap m : mapsAMettreAJour) { List<Joueur> joueursMap = getJoueurs(m.getUUID()); if (!joueursMap.isEmpty() || mapsAvecPanneau.contains(m)) { m.getListeTemps(true); Bukkit.getScheduler().scheduleSyncDelayedTask(CreativeParkour.getPlugin(), new Runnable() { public void run() { if (mapsAvecPanneau.contains(m)) Panneau.majClassements(m); // Mise jour des leaderboard des joueurs for (Joueur j : joueursMap) { j.calculerScoreboard(); j.choixFantomesPreferes(); j.majTeteFantomes(); } } }); } } // Enregistrement du nombre de tricheurs o = json.get("data").getAsJsonObject().get("nbTricheurs"); if (o != null) { nbTricheurs = o.getAsInt(); // Enregistrement des joueurs qui peuvent recevoir des notifications de triche o = json.get("data").getAsJsonObject().get("receveursNotifsTriche"); receveursNotifsTriche = new ArrayList<UUID>(); if (o != null && o.isJsonArray()) { JsonArray liste = o.getAsJsonArray(); for (JsonElement e : liste) { receveursNotifsTriche.add(UUID.fromString(e.getAsString())); } } } /* // Envoi des notes et des fantmes Map<String, String> paramsPost = new HashMap<String, String>(); if (notesAEnvoyer.length() > 0) paramsPost.put("notes", notesAEnvoyer.toString()); // Traitement des fantmes envoyer Map<String, Boolean> autorisationsJoueurs = new HashMap<String, Boolean>(); o = json.get("data").getAsJsonObject().get("fantomesAEnvoyer"); if (o != null && o.isJsonArray() && Config.getConfig().getBoolean("online.upload ghosts")) { JsonArray liste = o.getAsJsonArray(); int i = 0; for (JsonElement e : liste) { String nomFantome = e.getAsString(); CPMap m = getMap(CPUtils.timeFileUUIDs(nomFantome).get("map")); if (m != null) { CPTime t = m.getTempsAvecFichier(getFichierTemps(nomFantome)); String uuidJoueur = t.playerUUID.toString(); if (!autorisationsJoueurs.containsKey(uuidJoueur)) autorisationsJoueurs.put(uuidJoueur, Config.getConfJoueur(uuidJoueur).getBoolean(PlayerSetting.ENVOYER_FANTOMES.path())); if (autorisationsJoueurs.get(uuidJoueur)) // Si le joueur a autoris l'envoi de fantmes paramsPost.put("fantome-" + i, t.getJson().toString()); i++; } } } if (paramsPost.size() > 0) { try { CPRequest.effectuerRequete("data.php", paramsPost, null, null, null); } catch (SecurityException e) { CreativeParkour.erreur("DATA", e, true); } } */ vidangeMemoire(); } if (sender != null) sender.sendMessage( Config.prefix() + ChatColor.GREEN + Langues.getMessage("commands.sync done")); } }); } }