List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.dozersoftware.snap.PosRepProcessor.java
License:Open Source License
public Message http(Message message) throws ActionProcessingException { System.out.println("&&&&&&&&&&&&&&&& PosRepProcessor &&&&&&&&&&&&&&&&&&&&&"); System.out.println(""); System.out.println("Service: " + service); System.out.println(""); // System.out.println("------------Http Request Info (XStream Encoded)-------------------"); // HttpRequest requestInfo = HttpRequest.getRequest(message); // String requestInfoXML; // XStream xstream = new XStream(); // requestInfoXML = xstream.toXML(requestInfo); // System.out.println(requestInfoXML); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); try {// w w w . j a v a2 s. c o m StringWriter sw = new StringWriter(); final Kml kml = new Kml(); Map<URI, Message> msgs = messageStore.getAllMessages("PosRep"); Iterator<URI> it = msgs.keySet().iterator(); System.out.println("Tracking for :" + msgs.size() + " records"); while (it.hasNext()) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); String raw = (String) msgs.get(it.next()).getBody().get(); Document doc = dBuilder.parse(new ByteArrayInputStream(raw.getBytes())); doc.getDocumentElement().normalize(); NodeList body = doc.getElementsByTagName("BODY"); String handle = doc.getDocumentElement().getAttribute("sender"); Node e = body.item(0); System.out.println("SNAP: " + handle + "'s PosRep -> " + e.getTextContent()); JsonElement jse = new JsonParser().parse(e.getTextContent()); if (jse.isJsonObject()) { System.out.println("We got the right thing: " + jse.toString()); JsonArray ja = jse.getAsJsonObject().getAsJsonArray("POSREP"); // {"POSREP": // [16,"Aug 17, 2010 3:11:00 AM","31.74","-111.11"]} Double lat = ja.get(2).getAsDouble(); Double lng = ja.get(3).getAsDouble(); kml.createAndSetPlacemark().withName(handle).withOpen(Boolean.TRUE).createAndSetPoint() .addToCoordinates(lng, lat); } else { System.out.println("Not an Array!"); } } System.out.println("Processed all positions..."); kml.marshal(sw); message.getBody().add(sw.toString()); } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessageStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return message; }
From source file:com.dryver.Controllers.ElasticSearchController.java
License:Open Source License
/** * Gets requests with a certain search_string * * @param search_string//ww w . ja v a 2 s . c o m * @return */ private static ArrayList<Request> getRequests(String search_string) { Log.i("trace", "ElasticSearchController().getRequests()"); verifySettings(); Search search = new Search.Builder(search_string).addIndex(INDEX).addType(REQUEST).build(); ArrayList<Request> requests = new ArrayList<Request>(); try { JestResult result = client.execute(search); if (result.isSucceeded()) { requests.addAll(result.getSourceAsObjectList(Request.class)); JsonObject resultObj = result.getJsonObject(); JsonArray hitsArray = resultObj.get("hits").getAsJsonObject().get("hits").getAsJsonArray(); for (int i = 0; i < hitsArray.size(); i++) { requests.get(i) .setId(hitsArray.get(i).getAsJsonObject().get("_id").toString().replace("\"", "")); } return requests; } } catch (IOException e) { e.printStackTrace(); } return requests; }
From source file:com.dvdprime.mobile.android.util.GsonUtil.java
License:Apache License
/** * Json String? ? /*from ww w . jav a2s .c o m*/ * * @param json * json string * @param clazz * class * @return */ public static <T> List<T> getArrayList(String json, Class<T> clazz) { List<T> mResult = null; JsonArray jsonArray = getAsJsonArray(json); if (jsonArray != null && !jsonArray.isJsonNull()) { mResult = new ArrayList<T>(); for (int i = 0; i < jsonArray.size(); i++) { mResult.add(gson.fromJson(jsonArray.get(i), clazz)); } } return mResult; }
From source file:com.easycode.visualisation_1.JSONtoEarthquake.java
public ArrayList<Earthquake> createEarthquakeArrayList(JsonObject earthquakes) throws IOException { JsonArray values = earthquakes.getAsJsonArray("results"); ArrayList<Earthquake> returnList = new ArrayList<>(); for (int i = 0; i < values.size(); i++) { JsonObject earthquake = values.get(i).getAsJsonObject(); Float latitude = earthquake.get("latitude").getAsFloat(); Float longitude = earthquake.get("longitude").getAsFloat(); Float depth = earthquake.get("depth").getAsFloat(); Float size = earthquake.get("size").getAsFloat(); String str_timestamp = earthquake.get("timestamp").getAsString(); Timestamp timeStampDate = Utilities.convertStringToTimestamp(str_timestamp); Earthquake EQ = new Earthquake(latitude, longitude, depth, size, timeStampDate); returnList.add(EQ);/*from w ww. j a v a2 s .com*/ } return returnList; }
From source file:com.esotericsoftware.spine.SkeletonJson.java
License:Open Source License
void readCurve(CurveTimeline timeline, int frameIndex, JsonObject valueMap) { JsonElement curve = valueMap.has("curve") ? valueMap.get("curve") : null; if (curve == null) return;/*from w w w.j a va2 s.c om*/ if (curve.isJsonPrimitive() && curve.getAsString().equals("stepped")) timeline.setStepped(frameIndex); else if (curve.isJsonArray()) { JsonArray curveArray = curve.getAsJsonArray(); timeline.setCurve(frameIndex, curveArray.get(0).getAsFloat(), curveArray.get(1).getAsFloat(), curveArray.get(2).getAsFloat(), curveArray.get(3).getAsFloat()); } }
From source file:com.evandroid.musica.lyrics.Bollywood.java
License:Open Source License
public static ArrayList<Lyrics> search(String query) { ArrayList<Lyrics> results = new ArrayList<>(); String searchUrl = "http://quicklyric.azurewebsites.net/bollywood/search.php?q=%s"; try {/*from w ww. java 2s . c om*/ String jsonText; jsonText = Net.getUrlAsString(String.format(searchUrl, URLEncoder.encode(query, "utf-8"))); JsonObject jsonResponse = new JsonParser().parse(jsonText).getAsJsonObject(); JsonArray lyricsResults = jsonResponse.getAsJsonArray("lyrics"); for (int i = 0; i < lyricsResults.size(); ++i) { JsonObject lyricsResult = lyricsResults.get(i).getAsJsonObject(); JsonArray tags = lyricsResult.get("tags").getAsJsonArray(); Lyrics lyrics = new Lyrics(Lyrics.SEARCH_ITEM); lyrics.setTitle(lyricsResult.get("name").getAsString()); for (int j = 0; i < tags.size(); ++j) { JsonObject tag = tags.get(j).getAsJsonObject(); if (tag.get("tag_type").getAsString().equals("Singer")) { lyrics.setArtist(tag.get("name").getAsString().trim()); break; } } lyrics.setURL("http://quicklyric.azurewebsites.net/bollywood/get.php?id=" + lyricsResult.get("id").getAsInt()); results.add(lyrics); } } catch (IOException | JsonParseException e) { e.printStackTrace(); } return results; }
From source file:com.evandroid.musica.lyrics.MetalArchives.java
License:Open Source License
@Reflection public static Lyrics fromMetaData(String artist, String title) { String baseURL = "http://www.metal-archives.com/search/ajax-advanced/searching/songs/?bandName=%s&songTitle=%s&releaseType[]=1&exactSongMatch=1&exactBandMatch=1"; String urlArtist = artist.replaceAll("\\s", "+"); String urlTitle = title.replaceAll("\\s", "+"); String url;// w w w .j a v a 2 s . c om String text; try { String response = Net.getUrlAsString(String.format(baseURL, urlArtist, urlTitle)); JsonObject jsonResponse = new JsonParser().parse(response).getAsJsonObject(); JsonArray track = jsonResponse.getAsJsonArray("aaData").get(0).getAsJsonArray(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < track.size(); i++) builder.append(track.get(i).getAsString()); Document trackDocument = Jsoup.parse(builder.toString()); url = trackDocument.getElementsByTag("a").get(1).attr("href"); String id = trackDocument.getElementsByClass("viewLyrics").get(0).id().substring(11); text = Jsoup.connect("http://www.metal-archives.com/release/ajax-view-lyrics/id/" + id).get().body() .html(); } catch (IOException e) { return new Lyrics(Lyrics.ERROR); } catch (JsonParseException e) { return new Lyrics(Lyrics.NO_RESULT); } Lyrics lyrics = new Lyrics(Lyrics.POSITIVE_RESULT); lyrics.setArtist(artist); lyrics.setTitle(title); lyrics.setText(text); lyrics.setSource(domain); lyrics.setURL(url); return lyrics; }
From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java
License:Apache License
public String serializeAsPacketModel() { JsonObject model = new JsonObject(); model.add("protocols", new JsonArray()); JsonObject fieldEngine = new JsonObject(); fieldEngine.add("instructions", new JsonArray()); fieldEngine.add("global_parameters", new JsonObject()); model.add("field_engine", fieldEngine); Map<String, AddressDataBinding> l3Binds = new HashMap<>(); l3Binds.put("Ether", macDB); boolean isIPv4 = protocolSelection.getIpv4Property().get(); if (isIPv4) { l3Binds.put("IP", ipv4DB); }//from w w w .j a v a 2 s. c o m l3Binds.entrySet().stream().forEach(entry -> { JsonObject proto = new JsonObject(); String protoID = entry.getKey(); proto.add("id", new JsonPrimitive(protoID)); JsonArray fields = new JsonArray(); AddressDataBinding binding = entry.getValue(); String srcMode = entry.getValue().getDestination().getModeProperty().get(); String dstMode = entry.getValue().getSource().getModeProperty().get(); if (!MODE_TREX_CONFIG.equals(srcMode)) { fields.add(buildProtoField("src", binding.getSource().getAddressProperty().getValue())); } if (!MODE_TREX_CONFIG.equals(dstMode)) { fields.add(buildProtoField("dst", binding.getDestination().getAddressProperty().getValue())); } if (protoID.equals("Ether") && ethernetDB.getOverrideProperty().get()) { fields.add(buildProtoField("type", ethernetDB.getTypeProperty().getValue())); } proto.add("fields", fields); model.getAsJsonArray("protocols").add(proto); if (!MODE_FIXED.equals(binding.getSource().getModeProperty().get()) && !MODE_TREX_CONFIG.equals(binding.getSource().getModeProperty().get())) { fieldEngine.getAsJsonArray("instructions") .addAll(buildVMInstructions(protoID, "src", binding.getSource())); } if (!MODE_FIXED.equals(binding.getDestination().getModeProperty().get()) && !MODE_TREX_CONFIG.equals(binding.getDestination().getModeProperty().get())) { fieldEngine.getAsJsonArray("instructions") .addAll(buildVMInstructions(protoID, "dst", binding.getDestination())); } }); boolean isVLAN = protocolSelection.getTaggedVlanProperty().get(); String pktLenName = "pkt_len"; String frameLenghtType = protocolSelection.getFrameLengthType(); boolean pktSizeChanged = !frameLenghtType.equals("Fixed"); if (pktSizeChanged) { LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>(); String operation = PacketBuilderHelper.getOperationFromType(frameLenghtType); Integer minLength = Integer.valueOf(protocolSelection.getMinLength()) - 4; Integer maxLength = Integer.valueOf(protocolSelection.getMaxLength()) - 4; instructionParam.put("init_value", minLength.toString()); instructionParam.put("max_value", maxLength.toString()); instructionParam.put("min_value", minLength.toString()); instructionParam.put("name", pktLenName); instructionParam.put("op", operation); instructionParam.put("size", "2"); instructionParam.put("step", "1"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFlowVar", instructionParam)); instructionParam.clear(); instructionParam.put("fv_name", pktLenName); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmTrimPktSize", instructionParam)); instructionParam.clear(); instructionParam.put("add_val", isVLAN ? "-18" : "-14"); instructionParam.put("is_big", "true"); instructionParam.put("fv_name", pktLenName); instructionParam.put("pkt_offset", isVLAN ? "20" : "16"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmWrFlowVar", instructionParam)); } if (isVLAN) { JsonObject dot1QProto = new JsonObject(); dot1QProto.add("id", new JsonPrimitive("Dot1Q")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("prio", vlanDB.getPriorityProperty().getValue()); fieldsMap.put("id", vlanDB.getCfiProperty().getValue()); fieldsMap.put("vlan", vlanDB.getVIdProperty().getValue()); dot1QProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); JsonArray protocols = model.getAsJsonArray("protocols"); if (protocols.size() == 2) { JsonElement ipv4 = protocols.get(1); protocols.set(1, dot1QProto); protocols.add(ipv4); } else { model.getAsJsonArray("protocols").add(dot1QProto); } if (vlanDB.getOverrideTPIdProperty().getValue()) { JsonArray etherFields = ((JsonObject) model.getAsJsonArray("protocols").get(0)).get("fields") .getAsJsonArray(); if (etherFields.size() == 3) { etherFields.remove(2); } etherFields.add(buildProtoField("type", vlanDB.getTpIdProperty().getValue())); } } boolean isTCP = protocolSelection.getTcpProperty().get(); if (isTCP) { JsonObject tcpProto = new JsonObject(); tcpProto.add("id", new JsonPrimitive("TCP")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("sport", tcpProtocolDB.getSrcPortProperty().getValue()); fieldsMap.put("dport", tcpProtocolDB.getDstPortProperty().getValue()); fieldsMap.put("chksum", "0x" + tcpProtocolDB.getChecksumProperty().getValue()); fieldsMap.put("seq", tcpProtocolDB.getSequenceNumberProperty().getValue()); fieldsMap.put("urgptr", tcpProtocolDB.getUrgentPointerProperty().getValue()); fieldsMap.put("ack", tcpProtocolDB.getAckNumberProperty().getValue()); int tcp_flags = 0; if (tcpProtocolDB.getUrgProperty().get()) { tcp_flags = tcp_flags | (1 << 5); } if (tcpProtocolDB.getAckProperty().get()) { tcp_flags = tcp_flags | (1 << 4); } if (tcpProtocolDB.getPshProperty().get()) { tcp_flags = tcp_flags | (1 << 3); } if (tcpProtocolDB.getRstProperty().get()) { tcp_flags = tcp_flags | (1 << 2); } if (tcpProtocolDB.getSynProperty().get()) { tcp_flags = tcp_flags | (1 << 1); } if (tcpProtocolDB.getFinProperty().get()) { tcp_flags = tcp_flags | 1; } fieldsMap.put("flags", String.valueOf(tcp_flags)); tcpProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); model.getAsJsonArray("protocols").add(tcpProto); } // Field Engine instructions String cache_size = "5000"; if ("Enable".equals(advancedPropertiesDB.getCacheSizeTypeProperty().getValue())) { cache_size = advancedPropertiesDB.getCacheValueProperty().getValue(); } fieldEngine.getAsJsonObject("global_parameters").add("cache_size", new JsonPrimitive(cache_size)); boolean isUDP = protocolSelection.getUdpProperty().get(); if (isUDP) { JsonObject udpProto = new JsonObject(); udpProto.add("id", new JsonPrimitive("UDP")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("sport", udpProtocolDB.getSrcPortProperty().getValue()); fieldsMap.put("dport", udpProtocolDB.getDstPortProperty().getValue()); fieldsMap.put("len", udpProtocolDB.getLengthProperty().getValue()); udpProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); model.getAsJsonArray("protocols").add(udpProto); if (pktSizeChanged) { LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>(); instructionParam.put("add_val", isVLAN ? "-38" : "-34"); instructionParam.put("is_big", "true"); instructionParam.put("fv_name", pktLenName); instructionParam.put("pkt_offset", isVLAN ? "42" : "38"); fieldEngine.getAsJsonArray("instructions") .add(buildInstruction("STLVmWrFlowVar", instructionParam)); } } if (ipv4DB.hasInstructions() || pktSizeChanged) { Map<String, String> flowWrVarParameters = new HashMap<>(); flowWrVarParameters.put("offset", "IP"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFixIpv4", flowWrVarParameters)); } return model.toString(); }
From source file:com.example.mediastock.activities.MusicPlayerActivity.java
/** * Thread to add the info of the music to database * * @param path the path where the music is stored * @param musicID the id of the music//w ww . jav a 2 s .c om * @param title the title of the music */ private void addMusicInfoToDB(final String path, final int musicID, final String title) { new ExecuteExecutor(this, 2, new ExecuteExecutor.CallableAsyncTask(this) { @Override public String call() { MusicPlayerActivity context = (MusicPlayerActivity) getContextRef(); HttpURLConnection con = null; InputStream is = null; String genre = ""; // first, get the genre of the music try { URL url = new URL("https://api.shutterstock.com/v2/audio/" + context.musicID); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Authorization", "Basic " + Utilities.getLicenseKey()); con.setConnectTimeout(25000); con.setReadTimeout(25000); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = Utilities.readAll(rd); rd.close(); JsonElement json = new JsonParser().parse(jsonText); JsonObject o = json.getAsJsonObject(); JsonArray array = o.get("genres") != null ? o.get("genres").getAsJsonArray() : null; if (array != null) { if (array.size() > 0) genre += array.get(0) != null ? array.get(0).getAsString() : " - "; } // save music info to database context.db.insertMusicInfo(path, musicID, title, genre); } } catch (SocketTimeoutException e) { if (con != null) con.disconnect(); } catch (IOException e) { e.printStackTrace(); } finally { // and finally we close the objects try { if (is != null) { con.disconnect(); is.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } }); }
From source file:com.example.mediastock.activities.VideoPlayerActivity.java
/** * Thread to add to database the videos info * * @param path the path where the video is stored * @param videoID the id of the video * @param description the description of the video *///from w w w . java2 s . com private void addVideoInfoToDB(final String path, final int videoID, final String description) { new ExecuteExecutor(this, 2, new ExecuteExecutor.CallableAsyncTask(this) { @Override public String call() { VideoPlayerActivity context = (VideoPlayerActivity) getContextRef(); HttpURLConnection con = null; InputStream is = null; String category = ""; // first, get the category of the video try { URL url = new URL("https://api.shutterstock.com/v2/videos/" + context.videoID); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Authorization", "Basic " + Utilities.getLicenseKey()); con.setConnectTimeout(25000); con.setReadTimeout(25000); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = Utilities.readAll(rd); rd.close(); JsonElement json = new JsonParser().parse(jsonText); JsonObject o = json.getAsJsonObject(); JsonArray array = o.get("categories") != null ? o.get("categories").getAsJsonArray() : null; if (array != null) { if (array.size() > 0) category += array.get(0).getAsJsonObject().get("name") != null ? array.get(0).getAsJsonObject().get("name").getAsString() : " - "; } // save video info to database context.db.insertVideoInfo(path, videoID, description, category); } } catch (SocketTimeoutException e) { if (con != null) con.disconnect(); } catch (IOException e) { e.printStackTrace(); } finally { // clean the objects try { if (is != null) { con.disconnect(); is.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } }); }