List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java
License:Apache License
private JsonArray buildRoles(final JsonObject rootObject) { final Map<String, JsonObject> roleMap = new HashMap<>(); fillReservedResources(roleMap, rootObject.getAsJsonObject("reserved_resources_full")); fillUsedResources(roleMap, rootObject.getAsJsonArray("used_resources_full")); fillOfferedResources(roleMap, rootObject.getAsJsonArray("offered_resources_full")); JsonArray result = new JsonArray(); for (JsonObject each : roleMap.values()) { result.add(each);//from w w w .j a va 2 s . c o m } return result; }
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
License:Apache License
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();/* ww w. j a va 2 s . c o m*/ final Date timestamp = gson.fromJson(request.get(TIMESTAMP), Date.class); final String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)) .map(JsonElement::getAsString).orElse(null); final Set<String> names = gson.fromJson(request.getAsJsonArray(NAMES), JsonTypes.STRING_SET_TYPE); Set<String> devices = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session); devices = prepareActualList(devices, deviceId); List<DeviceVO> actualDevices; if (devices != null) { actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal); if (actualDevices.size() != devices.size()) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN); } } else { actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createCommandInsertMessage(command, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService.sendSubscribeRequest(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection .forEach(cmd -> sendMessage(ServerResponsesFactory.createCommandInsertMessage(cmd, pair.getLeft()), session))); logger.debug("command/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft()); WebSocketResponse response = new WebSocketResponse(); response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null); return response; }
From source file:com.devicehive.websockets.handlers.CommandHandlers.java
License:Apache License
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_COMMAND')") public WebSocketResponse processCommandUnsubscribe(JsonObject request, WebSocketSession session) { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//from w ww .j a v a 2 s .c o m final Optional<String> subscriptionId = Optional.ofNullable(request.get(SUBSCRIPTION_ID)) .map(JsonElement::getAsString); Set<String> guids = gson.fromJson(request.getAsJsonArray(DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); logger.debug("command/unsubscribe action. Session {} ", session.getId()); if (!subscriptionId.isPresent() && guids == null) { List<DeviceVO> actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); guids = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); commandService.sendUnsubscribeRequest(null, guids); } else if (subscriptionId.isPresent()) { commandService.sendUnsubscribeRequest(subscriptionId.get(), guids); } else { commandService.sendUnsubscribeRequest(null, guids); } ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).remove(subscriptionId); return new WebSocketResponse(); }
From source file:com.distance.DistanceServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . ja va2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); if (request.getParameter("zip1") != null && request.getParameter("zip2") != null) { try { String type = request.getParameter("type") == null ? "mi" : request.getParameter("type"); URL url = new URL("http://api.geonames.org/postalCodeLookupJSON?postalcode=" + request.getParameter("zip1") + "&country=US&username=nailyusupov"); URLConnection conn = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = br.readLine(); JsonElement jelement = new JsonParser().parse(line); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonArray("postalcodes").get(0).getAsJsonObject(); String lng1 = jobject.get("lng").toString(); String lat1 = jobject.get("lat").toString(); url = new URL("http://api.geonames.org/postalCodeLookupJSON?postalcode=" + request.getParameter("zip2") + "&country=US&username=nailyusupov"); conn = url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = br.readLine(); jelement = new JsonParser().parse(line); jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonArray("postalcodes").get(0).getAsJsonObject(); String lng2 = jobject.get("lng").toString(); String lat2 = jobject.get("lat").toString(); br.close(); response.getWriter() .write(new Gson().toJson(String.format("%.2f", haversine(Double.valueOf(lat1), Double.valueOf(lng1), Double.valueOf(lat2), Double.valueOf(lng2), type.equals("km") ? 6371 : 3959)))); } catch (Exception e) { response.getWriter().write(new Gson().toJson("Invalid parameters")); } } else { response.getWriter().write(new Gson().toJson( "/distance?zip1=xxxxx&zip2=xxxxx\n\ndistance between zip codes is calculated in miles use type=km for kilometers")); } }
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 w w .ja v a 2 s . c o m*/ } return returnList; }
From source file:com.eddy.malupdater.MalAPI.java
License:Open Source License
public static AnimeList getAnimeList(String username) { try {/*from w w w. ja v a2 s . c om*/ String jsonResponse = GET("http://mal-api.com/animelist/" + username); JsonObject object = jsonParser.parse(jsonResponse).getAsJsonObject(); return jsonToAnimeList(object.getAsJsonArray("anime")); } catch (UniformInterfaceException e) { return new AnimeList(); } }
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 {/* ww w. java 2 s . c o m*/ 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.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 ww . ja v a2s . 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.fb.marveltest.CharacterListController.java
/** * Creates a new instance of CharacterListController */// w w w.j av a 2 s . c om public CharacterListController() { final String json = Cache.getInstance().getResource().queryParam("ts", "1").queryParam("limit", "100") .queryParam("offset", String.valueOf(offset)) .queryParam("apikey", "7a4c44e4becce8ad14abb4f92544dc45") .queryParam("hash", "2553dc60bbf63062a13e64194ae026f5").accept(MediaType.APPLICATION_JSON) .get(String.class); JsonElement jelement = new JsonParser().parse(json); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("data"); JsonArray jarray = jobject.getAsJsonArray("results"); for (JsonElement obj : jarray) { names.add(obj.getAsJsonObject().get("name").toString().replace("\"", "")); } }
From source file:com.fb.marveltest.CharacterListController.java
public Character getCharacter() { final Cache cache = Cache.getInstance(); character = cache.getCharacter(selectedName); if (character == null) { final String json = cache.getResource().queryParam("ts", "1").queryParam("name", selectedName) .queryParam("apikey", "7a4c44e4becce8ad14abb4f92544dc45") .queryParam("hash", "2553dc60bbf63062a13e64194ae026f5").accept(MediaType.APPLICATION_JSON) .get(String.class); JsonElement jelement = new JsonParser().parse(json); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("data"); JsonArray jarray = jobject.getAsJsonArray("results"); jobject = jarray.get(0).getAsJsonObject(); character = cache.addCharacter(jobject); }// w w w. java 2 s .com return character; }