List of usage examples for com.google.gson JsonObject getAsJsonObject
public JsonObject getAsJsonObject(String memberName)
From source file:com.frostwire.search.archiveorg.ArchiveorgSearchPerformer.java
License:Open Source License
private List<ArchiveorgFile> readFiles(String json) throws Exception { List<ArchiveorgFile> result = new LinkedList<>(); JsonElement element = new JsonParser().parse(json); JsonObject obj = element.getAsJsonObject(); JsonObject files = obj.getAsJsonObject("files"); Iterator<Map.Entry<String, JsonElement>> it = files.entrySet().iterator(); while (it.hasNext() && !isStopped()) { Map.Entry<String, JsonElement> e = it.next(); String name = e.getKey(); String value = e.getValue().toString(); ArchiveorgFile file = JsonUtils.toObject(value, ArchiveorgFile.class); if (filter(file)) { file.filename = cleanName(name); result.add(file);//ww w. j a v a 2 s .co m } } return result; }
From source file:com.geecko.QuickLyric.Genius.java
License:Open Source License
public static ArrayList<Lyrics> search(String query) { ArrayList<Lyrics> results = new ArrayList<>(); query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");/*ww w . j a v a2s .c om*/ JsonObject response = null; try { URL queryURL = new URL( String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8"))); Connection connection = Jsoup.connect(queryURL.toExternalForm()) .header("Authorization", "Bearer " + GENIUS).timeout(0).ignoreContentType(true); Document document = connection.userAgent(Net.USER_AGENT).get(); response = new JsonParser().parse(document.text()).getAsJsonObject(); } catch (IOException e) { e.printStackTrace(); } if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200) return results; JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits"); int processed = 0; while (processed < hits.size()) { Lyrics l = new Lyrics(Lyrics.SEARCH_ITEM); results.add(l); processed++; } return results; }
From source file:com.geecko.QuickLyric.lyrics.Genius.java
License:Open Source License
public static ArrayList<Lyrics> search(String query) { ArrayList<Lyrics> results = new ArrayList<>(); query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");//from w ww. java 2s . c o m JsonObject response = null; try { URL queryURL = new URL( String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8"))); Connection connection = Jsoup.connect(queryURL.toExternalForm()) .header("Authorization", "Bearer " + Keys.GENIUS).timeout(0).ignoreContentType(true); Document document = connection.userAgent(Net.USER_AGENT).get(); response = new JsonParser().parse(document.text()).getAsJsonObject(); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200) return results; JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits"); int processed = 0; while (processed < hits.size()) { JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result"); String artist = song.getAsJsonObject("primary_artist").get("name").getAsString(); String title = song.get("title").getAsString(); String url = "http://genius.com/songs/" + song.get("id").getAsString(); Lyrics l = new Lyrics(Lyrics.SEARCH_ITEM); l.setArtist(artist); l.setTitle(title); l.setURL(url); l.setSource("Genius"); results.add(l); processed++; } return results; }
From source file:com.geecko.QuickLyric.tasks.IdDecoder.java
License:Open Source License
@Override protected Lyrics doInBackground(String... strings) { String url = strings[0];/*from ww w .ja va2s.c o m*/ String artist; String track; if (url == null) return new Lyrics(ERROR); if (url.contains("//www.soundhound.com/")) { try { // todo switch to Jsoup String html = getUrlAsString(url); int preceding = html.indexOf("root.App.trackDa") + 19; int following = html.substring(preceding).indexOf(";"); String data = html.substring(preceding, preceding + following); JsonObject jsonData = new JsonParser().parse(data).getAsJsonObject(); artist = jsonData.get("artist_display_name").getAsString(); track = jsonData.get("track_name").getAsString(); } catch (Exception e) { e.printStackTrace(); return new Lyrics(ERROR); } } else if (url.contains("//shz.am/")) { String id = url.split(".am/t")[1]; url = "https://www.shazam.com/discovery/v1/en/US/web/-/track/" + id; try { String jsonString = Net.getUrlAsString(url); JsonObject jsonData = new JsonParser().parse(jsonString).getAsJsonObject(); jsonData = jsonData.getAsJsonObject("heading"); artist = jsonData.get("subtitle").getAsString(); track = jsonData.get("title").getAsString(); } catch (Exception e) { e.printStackTrace(); return new Lyrics(ERROR); } } else if (url.contains("//play.google.com/store/music/")) { String docID = url.substring(url.indexOf("&tid=") + 5); try { Document doc = Jsoup.connect(url).get(); Element playCell = doc.getElementsByAttributeValue("data-track-docid", docID).get(0); artist = doc.getElementsByClass("primary").text(); track = playCell.parent().parent().child(1).getElementsByClass("title").text(); } catch (Exception e) { e.printStackTrace(); return new Lyrics(ERROR); } } else return new Lyrics(ERROR); Lyrics res = new Lyrics(Lyrics.SEARCH_ITEM); res.setArtist(artist); res.setTitle(track); return res; }
From source file:com.ghjansen.cas.ui.desktop.swing.SimulationParameterJsonAdapter.java
License:Open Source License
public final T deserialize(final JsonElement elem, final Type interfaceType, final JsonDeserializationContext context) throws JsonParseException { final JsonObject member = (JsonObject) elem; final JsonObject ruleTypeParameterJson = member.getAsJsonObject("ruleTypeParameter"); final JsonObject ruleConfigurationParameterJson = member.getAsJsonObject("ruleConfigurationParameter"); final JsonArray stateValuesJson = ruleConfigurationParameterJson.get("stateValues").getAsJsonArray(); final JsonObject limitsParameterJson = member.getAsJsonObject("limitsParameter"); final JsonObject initialConditionParameterJson = member.getAsJsonObject("initialConditionParameter"); final JsonArray sequencesJson = initialConditionParameterJson.get("sequences").getAsJsonArray(); UnidimensionalRuleTypeParameter ruleTypeParameter = new UnidimensionalRuleTypeParameter( ruleTypeParameterJson.get("elementar").getAsBoolean()); int[] stateValues = new int[stateValuesJson.size()]; for (int i = 0; i < stateValuesJson.size(); i++) { stateValues[i] = stateValuesJson.get(i).getAsInt(); }//from w w w. ja v a 2s. c o m UnidimensionalRuleConfigurationParameter ruleConfigurationParameter = new UnidimensionalRuleConfigurationParameter( stateValues[7], stateValues[6], stateValues[5], stateValues[4], stateValues[3], stateValues[2], stateValues[1], stateValues[0]); UnidimensionalLimitsParameter limitsParameter = new UnidimensionalLimitsParameter( limitsParameterJson.get("cells").getAsInt(), limitsParameterJson.get("iterations").getAsInt()); UnidimensionalSequenceParameter sequences[] = new UnidimensionalSequenceParameter[sequencesJson.size()]; for (int i = 0; i < sequencesJson.size(); i++) { JsonObject s = sequencesJson.get(i).getAsJsonObject(); UnidimensionalSequenceParameter sequence = new UnidimensionalSequenceParameter( s.get("initialPosition").getAsInt(), s.get("finalPosition").getAsInt(), s.get("value").getAsInt()); sequences[i] = sequence; } UnidimensionalInitialConditionParameter initialConditionParameter = new UnidimensionalInitialConditionParameter( sequences); try { return (T) new UnidimensionalSimulationParameter(ruleTypeParameter, ruleConfigurationParameter, limitsParameter, initialConditionParameter); } catch (InvalidSimulationParameterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.github.cc007.headsweeper.controller.HeadSweeperGame.java
License:Open Source License
public HeadSweeperGame(JsonObject input, Plugin plugin) { this.plugin = plugin; x = input.getAsJsonPrimitive("x").getAsInt(); y = input.getAsJsonPrimitive("y").getAsInt(); z = input.getAsJsonPrimitive("z").getAsInt(); game = new MineSweeper(true); game.deserialize(input.getAsJsonObject("game")); world = null;// w w w. j av a2 s . c om try { UUID worldUID = UUID.fromString(input.getAsJsonPrimitive("world").getAsString()); world = Bukkit.getServer().getWorld(worldUID); } catch (IllegalArgumentException e) { world = Bukkit.getServer().getWorld(input.getAsJsonPrimitive("world").getAsString()); } initMetaData(); }
From source file:com.github.consiliens.harv.gson.IRequestLogRecordDeserializer.java
License:Open Source License
@Override public IRequestLogRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Follow same order as serializer for sanity. IRequestLogRecord record = null;//www .j av a2s.co m final JsonObject recordJson = json.getAsJsonObject(); final long requestId = recordJson.get(R.requestId).getAsLong(); final long requestTimestamp = recordJson.get(R.timestamp).getAsLong(); final long requestMilliseconds = recordJson.get(R.requestMilliseconds).getAsLong(); // HttpHost JsonObject hostJson = recordJson.getAsJsonObject(R.httpHost); final String hostName = hostJson.get(R.hostName).getAsString(); final int port = hostJson.get(R.port).getAsInt(); final String schemeName = hostJson.get(R.schemeName).getAsString(); final HttpHost host = new HttpHost(hostName, port, schemeName); // Request final JsonObject requestJson = recordJson.getAsJsonObject(R.request); String requestEntityString = ""; HttpRequest httpRequest = null; if (requestJson.has(R.entity)) { requestEntityString = requestJson.get(R.entity).getAsString(); } // Must parse headers here. final Header[] requestHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders)); // Request params final HttpParams requestHttpParams = new BasicHttpParams(); setParamsFromJson(requestHttpParams, requestJson); // Request RequestLine final JsonObject requestLineJson = requestJson.getAsJsonObject(R.requestLine); // Request RequestLine Protocol final ProtocolVersion requestProtocol = getProtocolVersion( requestLineJson.getAsJsonObject(R.protocolVersion)); final String method = requestLineJson.get(R.method).getAsString(); final String uri = requestLineJson.get(R.uri).getAsString(); // Request is finished. Build the HttpRequest Object. if (requestEntityString.isEmpty()) { // non-entity request httpRequest = new BasicHttpRequest(method, uri, requestProtocol); } else { httpRequest = new BasicHttpEntityEnclosingRequest(method, uri, requestProtocol); ByteArrayEntity requestEntity = null; if (entitiesExternalPath.isEmpty()) { // From internal string. try { requestEntity = new ByteArrayEntity(requestEntityString.getBytes(UTF8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { // From file. final String fileName = getEntityFileName(requestEntityString); try { requestEntity = new ByteArrayEntity( Files.toByteArray(new File(entitiesExternalPath, fileName))); } catch (Exception e) { e.printStackTrace(); } } ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(requestEntity); } httpRequest.setHeaders(requestHeaders); httpRequest.setParams(requestHttpParams); // HttpResponse final JsonObject responseJson = recordJson.getAsJsonObject(R.response); final Header[] responseHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders)); // Response Entity String responseEntityString = ""; if (responseJson.has(R.entity)) { responseEntityString = responseJson.get(R.entity).getAsString(); } // Locale JsonObject localeJson = responseJson.getAsJsonObject(R.locale); final String language = localeJson.get(R.language).getAsString(); final String country = localeJson.get(R.country).getAsString(); String variant = ""; // Variant might not exist. if (localeJson.has(R.variant)) variant = localeJson.get(R.variant).getAsString(); Locale locale = new Locale(language, country, variant); // Response params final HttpParams responseHttpParams = new BasicHttpParams(); setParamsFromJson(responseHttpParams, responseJson); // StatusLine JsonObject statusLineJson = responseJson.getAsJsonObject(R.statusLine); // StatusLine Protocol Version final ProtocolVersion responseProtocol = getProtocolVersion( statusLineJson.getAsJsonObject(R.protocolVersion)); final int statusCode = statusLineJson.get(R.statusCode).getAsInt(); final String reasonPhrase = statusLineJson.get(R.reasonPhrase).getAsString(); StatusLine responseStatus = new BasicStatusLine(responseProtocol, statusCode, reasonPhrase); // Default to using EnglishReasonPhraseCatalog final HttpResponse httpResponse = new BasicHttpResponse(responseStatus, EnglishReasonPhraseCatalog.INSTANCE, locale); httpResponse.setHeaders(responseHeaders); httpResponse.setParams(responseHttpParams); // Ensure entity exists before processing. if (!requestEntityString.isEmpty()) { ByteArrayEntity responseEntity = null; try { if (entitiesExternalPath.isEmpty()) { // From internal string. responseEntity = new ByteArrayEntity(responseEntityString.getBytes(UTF8)); } else { // From file. final String fileName = getEntityFileName(requestEntityString); responseEntity = new ByteArrayEntity( Files.toByteArray(new File(entitiesExternalPath, fileName))); } } catch (Exception e1) { e1.printStackTrace(); } httpResponse.setEntity(responseEntity); } // RequestLogRecord's constructors are package private so use // reflection. try { final Constructor<RequestLogRecord> construct = RequestLogRecord.class.getDeclaredConstructor( long.class, HttpRequest.class, HttpResponse.class, HttpHost.class, long.class); construct.setAccessible(true); record = (RequestLogRecord) construct.newInstance(requestId, httpRequest, httpResponse, host, requestMilliseconds); // There's no get or set timestamp so use reflection. final Field timestampField = RequestLogRecord.class.getDeclaredField(R.timestamp); timestampField.setAccessible(true); timestampField.set(record, requestTimestamp); } catch (Exception e) { e.printStackTrace(); } return record; }
From source file:com.github.daytron.daytronmoney.conversion.ConversionClient.java
License:Open Source License
/** * Retrieves the latest exchange rates with USD as its base currency in the * form of JsonObject. Throws NullPointerException if the JsonObject is * deemed null./*from w ww . j a v a2s . c o m*/ * * @return Resulting JSON object as <code>JsonObject</code> */ static JsonObject getLatestRatesJsonObject() throws MoneyConversionException { JsonObject rootObject = extractJsonElement(API_URL + API_LATEST_PARAM); validateJsonObject(rootObject, RATES_JSON_MEMBER); JsonObject ratesObject = rootObject.getAsJsonObject(RATES_JSON_MEMBER); validateJsonObject(ratesObject, "GBP"); // Can be any other code except // USD - since this is the base currency return ratesObject; }
From source file:com.github.daytron.daytronmoney.conversion.ConversionClient.java
License:Open Source License
/** * Retrieves the latest particular exchange rate with given base currency * code in Money object, the currency code to be converted to and a date. * Useful converting Money with historical exchange rate. Throws * NullPointerException if the JsonObject is deemed null. The extracted rate * is return as String object.//from w w w . jav a 2 s .co m * * @param baseCurrency Base currency * @param toCurrency The outcome currency code * @param date date at which point the rate is retrieved * @return String value of the rate extracted * @throws MoneyConversionException For any error encountered */ static String getCurrencyRate(String baseCurrency, String toCurrency, LocalDateTime date) throws MoneyConversionException { baseCurrency = baseCurrency.trim(); toCurrency = toCurrency.trim(); if (baseCurrency.equalsIgnoreCase(toCurrency)) { return "1"; } String urlString; if (date == null) { // Example //http://api.fixer.io/latest?base=CAD¤cies=GBP urlString = API_URL + API_LATEST_PARAM + API_BASED_PARAM + baseCurrency + "&" + API_CURRENCY_PARAM + toCurrency; } else { String month; int monthVal = date.getMonthValue(); if (monthVal < 10) { month = "0" + monthVal; } else { month = "" + monthVal; } String day; int dayVal = date.getDayOfMonth(); if (dayVal < 10) { day = "0" + dayVal; } else { day = "" + dayVal; } // Example //http://api.fixer.io/2000-01-03?currencies=GBP&base=CAD urlString = API_URL + API_BASED_PARAM + date.getYear() + "-" + month + "-" + day + "?" + API_CURRENCY_PARAM + toCurrency + "&" + API_BASED_PARAM + baseCurrency; } JsonObject rootObj = extractJsonElement(urlString); validateJsonObject(rootObj, RATES_JSON_MEMBER); JsonObject ratesObject = rootObj.getAsJsonObject(RATES_JSON_MEMBER); validateJsonObject(ratesObject, toCurrency); return ratesObject.get(toCurrency).toString(); }
From source file:com.github.ithildir.airbot.util.ApiAiUtil.java
License:Open Source License
public static double[] getResponseCoordinates(JsonObject responseJsonObject) { JsonObject originalRequestJsonObject = responseJsonObject.getAsJsonObject("originalRequest"); JsonObject dataJsonObject = originalRequestJsonObject.getAsJsonObject("data"); JsonObject deviceJsonObject = dataJsonObject.getAsJsonObject("device"); if (deviceJsonObject == null) { return null; }/*from w w w .j av a 2s . c o m*/ JsonObject locationJsonObject = deviceJsonObject.getAsJsonObject("location"); if (locationJsonObject == null) { return null; } JsonObject coordinatesJsonObject = locationJsonObject.getAsJsonObject("coordinates"); if (coordinatesJsonObject == null) { return null; } JsonElement latitudeJsonElement = coordinatesJsonObject.get("latitude"); JsonElement longitudeJsonElement = coordinatesJsonObject.get("longitude"); return new double[] { latitudeJsonElement.getAsDouble(), longitudeJsonElement.getAsDouble() }; }