List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.skyisland.questmanager.fanciful.FancyMessage.java
License:Open Source License
/** * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. * @param json The JSON string which represents a fancy message. * @return A {@code FancyMessage} representing the parameterized JSON message. */// ww w . ja v a 2 s. com public static FancyMessage deserialize(String json) { JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component FancyMessage returnVal = new FancyMessage(); returnVal.messageParts.clear(); for (JsonElement mPrt : extra) { MessagePart component = new MessagePart(); JsonObject messagePart = mPrt.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) { // Deserialize text if (TextualComponent.isTextKey(entry.getKey())) { // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields Map<String, Object> serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance serializedMapForm.put("key", entry.getKey()); if (entry.getValue().isJsonPrimitive()) { // Assume string serializedMapForm.put("value", entry.getValue().getAsString()); } else { // Composite object, but we assume each element is a string for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue() .getAsJsonObject().entrySet()) { serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); } } component.text = TextualComponent.deserialize(serializedMapForm); } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { if (entry.getValue().getAsBoolean()) { component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); } } else if (entry.getKey().equals("color")) { component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); } else if (entry.getKey().equals("clickEvent")) { JsonObject object = entry.getValue().getAsJsonObject(); component.clickActionName = object.get("action").getAsString(); component.clickActionData = object.get("value").getAsString(); } else if (entry.getKey().equals("hoverEvent")) { JsonObject object = entry.getValue().getAsJsonObject(); component.hoverActionName = object.get("action").getAsString(); if (object.get("value").isJsonPrimitive()) { // Assume string component.hoverActionData = new JsonString(object.get("value").getAsString()); } else { // Assume composite type // The only composite type we currently store is another FancyMessage // Therefore, recursion time! component.hoverActionData = deserialize(object.get("value") .toString() /* This should properly serialize the JSON object as a JSON string */); } } else if (entry.getKey().equals("insertion")) { component.insertionData = entry.getValue().getAsString(); } else if (entry.getKey().equals("with")) { for (JsonElement object : entry.getValue().getAsJsonArray()) { if (object.isJsonPrimitive()) { component.translationReplacements.add(new JsonString(object.getAsString())); } else { // Only composite type stored in this array is - again - FancyMessages // Recurse within this function to parse this as a translation replacement component.translationReplacements.add(deserialize(object.toString())); } } } } returnVal.messageParts.add(component); } return returnVal; }
From source file:com.sldeditor.exportdata.esri.MXDParser.java
License:Open Source License
/** * Read layers from intermediate mxd files. * * @param mxdJSON the mxd JSON//from w ww .ja v a2 s. co m * @param outputFormat the output format * @return the MXD info */ public static Map<String, SLDDataInterface> readLayers(String filename, SLDOutputFormatEnum outputFormat) { if (filename == null) { return null; } File intermediateFile = new File(filename); if (!intermediateFile.exists()) { return null; } MXDParser parser = new MXDParser(); MXDInfo mxdInfo = new MXDInfo(); mxdInfo.setIntermediateFile(intermediateFile); JsonObject mxdJSON = convertFileToJSON(filename); // Read mxd filename String mxdFilename = ""; JsonElement mxdFilenameJson = mxdJSON.get("mxd"); if (mxdFilenameJson != null) { mxdFilename = mxdFilenameJson.getAsString(); mxdInfo.setMxdFilename(mxdFilename); } File f = new File(mxdFilename); String mxdName = f.getName(); int pos = mxdName.lastIndexOf("\\"); if (pos > 0) { mxdName = mxdName.substring(pos + 1); } mxdInfo.setMxdName(mxdName); // Read layers Map<String, SLDDataInterface> layerMap = new HashMap<String, SLDDataInterface>(); // Read layers JsonArray layerList = mxdJSON.getAsJsonArray("layers"); for (int index = 0; index < layerList.size(); index++) { JsonObject layer = (JsonObject) layerList.get(index); JsonElement layerNameElement = layer.get("name"); if (layerNameElement != null) { String layerName = layerNameElement.getAsString(); SLDDataInterface sldData = parser.importLayer(layer, outputFormat); layerMap.put(layerName, sldData); } } return layerMap; }
From source file:com.sowhoyou.twitchbot.chatbot.BotHelper.java
License:Open Source License
public String getLatestFollowerToString() { try {/*from w w w.j ava 2s . c o m*/ URL url = new URL(("https://api.twitch.tv/kraken/channels/" + this.getBot().getBotConfig().getBotChannel().toLowerCase().replace("#", "") + "/follows?limit=1")); String jText = IOUtils.toString(url); JsonParser jPhraser = new JsonParser(); JsonObject jo = jPhraser.parse(jText).getAsJsonObject(); JsonArray ja1 = jo.getAsJsonArray("follows"); String s1 = ja1.get(0).toString(); JsonObject jo2 = jPhraser.parse(s1).getAsJsonObject(); JsonObject jo3 = jo2.get("user").getAsJsonObject(); String s2 = jo3.get("name").toString(); return ("Latest Follower: [" + s2.replace('"', ' ').replace(" ", "") + "]"); } catch (Exception e) { } return null; }
From source file:com.splicemachine.tutorials.function.JsonFunction.java
License:Apache License
/** * * Call Method for parsing the string into either a singleton List with a LocatedRow or * an empty list.//from w w w. jav a2s . c o m * * @param s * @return * @throws Exception */ @Override public Iterator<LocatedRow> call(final String jsonString) throws Exception { Iterator<LocatedRow> itr = Collections.<LocatedRow>emptyList().iterator(); if (jsonString == null) { return itr; } JsonElement elem = parser.parse(jsonString); JsonObject root = elem.getAsJsonObject(); JsonArray dataArray = root == null ? null : root.getAsJsonArray("data"); int numRcds = dataArray == null ? 0 : dataArray.size(); if (numRcds == 0) { return itr; } List<LocatedRow> rows = new ArrayList<LocatedRow>(); //Loop through each of the entries in the array for (int i = 0; i < numRcds; i++) { //The definition of the row to be returned ExecRow returnRow = execRow.getClone(); //Reset the column counter int column = 1; JsonObject json = dataArray.get(i).getAsJsonObject(); //Retrieve the properties for each entry Set<Entry<String, JsonElement>> keys = json.entrySet(); for (Map.Entry<String, JsonElement> entry : keys) { String key = entry.getKey(); JsonElement valueElem = json.get(key); DataValueDescriptor dvd = returnRow.getColumn(column); int type = dvd.getTypeFormatId(); String value = valueElem.getAsJsonPrimitive().getAsString(); switch (type) { case StoredFormatIds.SQL_TIME_ID: if (calendar == null) calendar = new GregorianCalendar(); //if (timeFormat == null || value==null){ ((DateTimeDataValue) dvd).setValue(value, calendar); // }else // dvd.setValue(SpliceDateFunctions.TO_TIME(value, timeFormat),calendar); break; case StoredFormatIds.SQL_DATE_ID: if (calendar == null) calendar = new GregorianCalendar(); //if (dateTimeFormat == null || value == null) ((DateTimeDataValue) dvd).setValue(value, calendar); //else // dvd.setValue(SpliceDateFunctions.TO_DATE(value, dateTimeFormat),calendar); break; case StoredFormatIds.SQL_TIMESTAMP_ID: if (calendar == null) calendar = new GregorianCalendar(); //if (timestampFormat == null || value==null) ((DateTimeDataValue) dvd).setValue(value, calendar); //else // dvd.setValue(SpliceDateFunctions.TO_TIMESTAMP(value, timestampFormat),calendar); break; default: dvd.setValue(value); } column++; } rows.add(new LocatedRow(returnRow)); } return rows.iterator(); }
From source file:com.streamsets.pipeline.stage.destination.elasticsearch.ElasticsearchTarget.java
License:Apache License
private List<ErrorItem> extractErrorItems(JsonObject json) { List<ErrorItem> errorItems = new ArrayList<>(); JsonArray items = json.getAsJsonArray("items"); for (int i = 0; i < items.size(); i++) { JsonObject item = items.get(i).getAsJsonObject().entrySet().iterator().next().getValue() .getAsJsonObject();/*from w w w.ja va 2 s .com*/ int status = item.get("status").getAsInt(); if (status >= 400) { Object error = item.get("error"); // In some old versions, "error" is a simple string not a json object. if (error instanceof JsonObject) { errorItems.add(new ErrorItem(i, item.getAsJsonObject("error").get("reason").getAsString())); } else if (error instanceof JsonPrimitive) { errorItems.add(new ErrorItem(i, item.getAsJsonPrimitive("error").getAsString())); } else { // Error would be null if json has no "error" field. errorItems.add(new ErrorItem(i, "")); } } } return errorItems; }
From source file:com.thesmartweb.swebrank.ElasticGetWordList.java
License:Apache License
/** * Method gets all the words of all the documents regardless of topic for the ids passed as input * @param ids It contains all the ids for which the words are going to be captured * @param config_path configuration directory to get the names of the elastic search indexes * @return All the words in a List/*w w w .j av a 2 s .co m*/ */ public List<String> get(List<String> ids, String config_path) { try { //Node node = nodeBuilder().client(true).clusterName("lshrankldacluster").node(); //Client client = node.client(); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "lshrankldacluster") .build(); Client client = new TransportClient(settings) .addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); ReadInput ri = new ReadInput(); List<String> elasticIndexes = ri.GetKeyFile(config_path, "elasticSearchIndexes"); List<String> wordList = new ArrayList<>(); for (String id : ids) { SearchResponse responseSearch = client.prepareSearch(elasticIndexes.get(2)) .setSearchType(SearchType.QUERY_AND_FETCH).setQuery(QueryBuilders.idsQuery().ids(id)) .execute().actionGet(); XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); responseSearch.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); String JSONresponse = builder.string(); JsonParser parser = new JsonParser(); JsonObject JSONobject = (JsonObject) parser.parse(JSONresponse); JsonObject hitsJsonObject = JSONobject.getAsJsonObject("hits"); JsonArray hitsJsonArray = hitsJsonObject.getAsJsonArray("hits"); for (JsonElement hitJsonElement : hitsJsonArray) { JsonObject jsonElementObj = hitJsonElement.getAsJsonObject(); jsonElementObj = jsonElementObj.getAsJsonObject("_source"); JsonArray TopicsArray = jsonElementObj.getAsJsonArray("TopicsWordMap"); for (JsonElement Topic : TopicsArray) { JsonObject TopicObj = Topic.getAsJsonObject(); JsonObject wordsmap = TopicObj.getAsJsonObject("wordsmap"); Set<Map.Entry<String, JsonElement>> entrySet = wordsmap.entrySet(); Iterator<Map.Entry<String, JsonElement>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Map.Entry<String, JsonElement> next = iterator.next(); String word = next.getKey(); wordList.add(word); } } } } //node.close(); client.close(); return wordList; } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); List<String> wordList = new ArrayList<>(); return wordList; } }
From source file:com.thesmartweb.swebrank.ElasticGetWordList.java
License:Apache License
/** * Method gets all the top N max words for each topic of all the documents with their IDs (of the documents) passed as input. * @param ids It contains all the ids for which the words are going to be captured * @param top It contains the number of max words to be returned * @return All the words in a List//from www.j a v a2 s . c o m */ public List<String> getMaxWords(List<String> ids, int top, String config_path) { try { ReadInput ri = new ReadInput(); List<String> elasticIndexes = ri.GetKeyFile(config_path, "elasticSearchIndexes"); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "lshrankldacluster") .build(); Client client = new TransportClient(settings) .addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); //Node node = nodeBuilder().client(true).clusterName("lshrankldacluster").node(); //Client client = node.client(); List<String> MaxwordList = new ArrayList<>(); HashMap<String, Double> wordsMap = new HashMap<>(); SortedSetMultimap<Double, String> wordsMultisorted = TreeMultimap.create(); for (String id : ids) {//for every id loop SearchResponse responseSearch = client.prepareSearch(elasticIndexes.get(2)) .setSearchType(SearchType.QUERY_AND_FETCH).setQuery(QueryBuilders.idsQuery().ids(id)) .execute().actionGet();//search for this id //----build an object with the response XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); responseSearch.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); String JSONresponse = builder.string(); //----parse the JSON response JsonParser parser = new JsonParser(); JsonObject JSONobject = (JsonObject) parser.parse(JSONresponse); JsonObject hitsJsonObject = JSONobject.getAsJsonObject("hits"); JsonArray hitsJsonArray = hitsJsonObject.getAsJsonArray("hits"); //get all the JSON hits (check ElasticSearch typical response format for more) for (JsonElement hitJsonElement : hitsJsonArray) { JsonObject jsonElementObj = hitJsonElement.getAsJsonObject(); jsonElementObj = jsonElementObj.getAsJsonObject("_source"); JsonArray TopicsArray = jsonElementObj.getAsJsonArray("TopicsWordMap");//get the topics word map (every word has a probability for (JsonElement Topic : TopicsArray) {//for every topic I get the word with the max score JsonObject TopicObj = Topic.getAsJsonObject(); JsonObject wordsmap = TopicObj.getAsJsonObject("wordsmap");//get the wordmap Set<Map.Entry<String, JsonElement>> entrySet = wordsmap.entrySet(); Iterator<Map.Entry<String, JsonElement>> iterator = entrySet.iterator(); double max = 0.0; String maxword = ""; while (iterator.hasNext()) { Map.Entry<String, JsonElement> next = iterator.next(); if (next.getValue().getAsDouble() > max) { maxword = next.getKey(); max = next.getValue().getAsDouble(); } } if (wordsMap.containsKey(maxword)) { if (wordsMap.get(maxword) < max) { wordsMap.put(maxword, max); } } else { wordsMap.put(maxword, max); } } } } //we are going to sort all the max words Map<String, Double> wordsMapsorted = new HashMap<>(); wordsMapsorted = sortByValue(wordsMap);//sorts the map in ascending fashion Iterator<Entry<String, Double>> iterator = wordsMapsorted.entrySet().iterator(); //we are going to get the first top words from the list of Max words int beginindex = 0; //===we find the beginning index if (wordsMapsorted.entrySet().size() > top) { beginindex = wordsMapsorted.entrySet().size() - top; } int index = 0; //if the beginning index is larger we try to find the element while (index < beginindex) { iterator.next(); index++; } //while the maxword list size is smaller than the top number and we have an extra value, add this word while (MaxwordList.size() < top && iterator.hasNext()) { String word = iterator.next().getKey(); MaxwordList.add(word); } client.close(); //node.close(); return MaxwordList; } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); List<String> MaxwordList = new ArrayList<>(); return MaxwordList; } }
From source file:com.tpatterson.playground.work.deploy.DeployTool.java
private void callGLR(String host, String releasePid, String accountId, String serviceToken, String endUserAuth) throws Exception { String licenseUrl = lwsHostUrl(host); String cid = UUID.randomUUID().toString(); String requestURL = ServiceUriBuilder.create().withUriBuilder(licenseUrl, "/web/License").withForm("json") .withSchema(2.6).withHttpTrue().withCid(cid).build(); LicenseRequest licenseRequest = new LicenseRequest(); licenseRequest.setAuth(endUserAuth); licenseRequest.setProtectionScheme("widevine"); licenseRequest.setReleasePids(Collections.singletonList(releasePid)); String getLicenseResponseString = "{\"getLicenseResponse\":" + licenseRequest.toJsonString() + "}"; String contents = Executor.newInstance().auth(new UsernamePasswordCredentials(accountId, serviceToken)) .execute(// w w w . j av a2s . c o m Request.Post(requestURL).bodyString(getLicenseResponseString, ContentType.APPLICATION_JSON)) .returnContent().asString(); JsonElement responseBody = new JsonParser().parse(contents); JsonObject jsonResponse = responseBody.getAsJsonObject(); JsonArray getLicenseResponse = jsonResponse.getAsJsonArray("getLicenseResponseResponse"); if (getLicenseResponse.toString().contains("error")) { throw new RuntimeException("Error calling license: " + getLicenseResponse.get(0).getAsJsonObject().getAsJsonPrimitive("error").getAsString()); } }
From source file:com.tsp.solver.Solver.java
public static ArrayList<ArrayList<Double>> getDistancesFromGoogle(List<LatLng> places) { List<String> addresses = places.stream().map(x -> x.toString()).collect(Collectors.toList()); ArrayList<ArrayList<Double>> result = new ArrayList<>(places.size()); for (int i = 0; i < places.size(); ++i) { result.add(new ArrayList<Double>(places.size())); for (int j = 0; j < places.size(); ++j) { result.get(i).add(0.0);/*from w ww. j a v a 2 s .c o m*/ } } String url_start = "https://maps.googleapis.com/maps/api/distancematrix/json?"; String origins = "origins="; String destinations = "&destinations="; String key = "&key=AIzaSyDuEwRXx89RTym5nCtjGmRzsrp4JZV_zS4"; int count = places.size(); for (int i = 0; i <= places.size() / 25; ++i) { int n = Math.min(count, 25); String orig = new String(origins); for (int j = i * 25; j < i * 25 + n; ++j) { if (j != i * 25) orig += "|"; orig += addresses.get(j); } int max_places_for_one_send = 100 / n; int count2 = places.size(); for (int k = 0; k <= places.size() / max_places_for_one_send; ++k) { int m = Math.min(max_places_for_one_send, count2); String dest = new String(destinations); for (int j = k * max_places_for_one_send; j < k * max_places_for_one_send + m; ++j) { if (j != k * max_places_for_one_send) dest += "|"; dest += addresses.get(j); } count2 -= m; String url = url_start + orig + dest + key; log.debug("URL=" + url); try { Thread.sleep(100); InputStreamReader in = new InputStreamReader((new URL(url)).openStream()); JsonElement jelement = new JsonParser().parse(in); JsonObject jobject = jelement.getAsJsonObject(); JsonArray rows = jobject.getAsJsonArray("rows"); int ii = i * 25; for (JsonElement je : rows) { JsonArray elements = je.getAsJsonObject().getAsJsonArray("elements"); int jj = k * max_places_for_one_send; for (JsonElement je2 : elements) { long value = je2.getAsJsonObject().getAsJsonObject("distance").get("value").getAsLong(); result.get(ii).set(jj, value * 1.0); jj++; } ii++; } } catch (Exception ex) { java.util.logging.Logger.getLogger(Solver.class.getName()).log(Level.SEVERE, "Unknown exception :D", ex); } } count -= n; if (count == 0) break; } return result; }
From source file:com.tsp.solver.Solver.java
public static ArrayList<ArrayList<Double>> getDistancesFromMapBox(List<LatLng> places) { List<String> addresses = places.stream().map(x -> x.toLngLat()).collect(Collectors.toList()); ArrayList<ArrayList<Double>> result = new ArrayList<>(places.size()); for (int i = 0; i < places.size(); ++i) { result.add(new ArrayList<Double>(places.size())); for (int j = 0; j < places.size(); ++j) { result.get(i).add(0.0);// ww w. ja v a2 s . c o m } } String url_start = "https://api.mapbox.com/directions-matrix/v1/mapbox/driving/"; String destinations = "&destinations="; String sources = "?sources="; String key = "access_token=pk.eyJ1IjoibGluYXI5NSIsImEiOiJjajNyOHFreXcwMDBwNHVvMmIwdDA3ZTdpIn0.nnpzy7elxJr2cM-gPKaAZQ"; int count = places.size(); if (count <= 25) { String coords = ""; for (int i = 0; i < count; ++i) { if (i != 0) { coords += ";"; } coords += addresses.get(i); } String url = url_start + coords + "?" + key; log.debug("URL=" + url); try { //Thread.sleep(100); InputStreamReader in = new InputStreamReader((new URL(url)).openStream()); JsonElement jelement = new JsonParser().parse(in); JsonObject jobject = jelement.getAsJsonObject(); JsonArray rows = jobject.getAsJsonArray("durations"); int i = 0; for (JsonElement je : rows) { JsonArray elements = je.getAsJsonArray(); int j = 0; for (JsonElement je2 : elements) { double value = je2.getAsDouble(); result.get(i).set(j, value * 1.0); j++; } i++; } } catch (Exception ex) { java.util.logging.Logger.getLogger(Solver.class.getName()).log(Level.SEVERE, "Unknown exception :D", ex); } return result; } //if count > 25 int url_count = 0; int maxSize = 12; //max size of Matrix for one request 12*12 for (int i = 0; i <= places.size() / maxSize; ++i) { int n = Math.min(count, maxSize); String coords1 = ""; String src = new String(sources); for (int j = i * maxSize; j < i * maxSize + n; ++j) { if (j != i * maxSize) { coords1 += ";"; src += ";"; } coords1 += addresses.get(j); src += j - i * maxSize; } int count2 = places.size(); for (int k = 0; k <= places.size() / maxSize; ++k) { int m = Math.min(maxSize, count2); String coords2 = ""; String dst = new String(destinations); for (int j = k * maxSize; j < k * maxSize + m; ++j) { if (j != k * maxSize) { dst += ";"; } dst += j - k * maxSize; coords2 += ";"; coords2 += addresses.get(j); } count2 -= m; String url = url_start + coords1 + coords2 + src + dst + "&" + key; log.debug("URL=" + url); try { if (url_count == 60) { Thread.sleep(60000); url_count = 0; } InputStreamReader in = new InputStreamReader((new URL(url)).openStream()); url_count++; JsonElement jelement = new JsonParser().parse(in); JsonObject jobject = jelement.getAsJsonObject(); JsonArray rows = jobject.getAsJsonArray("durations"); int ii = i * maxSize; for (JsonElement je : rows) { JsonArray elements = je.getAsJsonArray(); int jj = k * maxSize; for (JsonElement je2 : elements) { double value = je2.getAsDouble(); result.get(ii).set(jj, value * 1.0); jj++; } ii++; } } catch (Exception ex) { java.util.logging.Logger.getLogger(Solver.class.getName()).log(Level.SEVERE, "Unknown exception :D", ex); } } count -= n; if (count == 0) break; } return result; }