/** * Parse a json message collection to create a Message * * @param arg json collection * @return Message */ public static Message readMessage(String arg) { JsonReader jsonReader = Json.createReader(new StringReader(arg)); JsonObject msgValues = jsonReader.readObject(); jsonReader.close(); if (null == msgValues.getJsonArray(ATTACHMENTS)) { return new Message( msgValues.getString(ID), msgValues.getString(SENDER), msgValues.getString(TOPIC), msgValues.getJsonNumber(TIMESTAMP).longValue(), msgValues.getString(CONTENT)); } else { JsonArray attachmentsJson = msgValues.getJsonArray(ATTACHMENTS); Byte[] attachmentByte = new Byte[attachmentsJson.size()]; for (int i = 0; i < attachmentByte.length; i++) { attachmentByte[i] = Byte.valueOf(attachmentsJson.getString(i)); } return new Message( msgValues.getString(ID), msgValues.getString(SENDER), msgValues.getString(TOPIC), msgValues.getJsonNumber(TIMESTAMP).longValue(), msgValues.getString(CONTENT), attachmentByte); } }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("USAGE : java -jar GoEuroTest.jar <CITY_NAME>"); System.exit(1); } String urlStr = "http://api.goeuro.com/api/v2/position/suggest/en/"; urlStr = urlStr + URLEncoder.encode(args[0], "UTF-8"); URL url = new URL(urlStr); String lines = ""; String fileHeader = "_id,name,type,latitude,longitude\r\n"; // out csv file header lines += fileHeader; try { InputStream inputStream = url.openStream(); JsonReader jsonReader = Json.createReader(inputStream); JsonArray results = jsonReader.readArray(); if (results.isEmpty()) { System.out.println("INFO: City '" + args[0] + "' returned 0 results."); return; } for (JsonObject result : results.getValuesAs(JsonObject.class)) { lines += result.getJsonNumber("_id") + ","; lines += result.getString("name") + ","; lines += result.getString("type") + ","; lines += result.getJsonObject("geo_position").getJsonNumber("latitude") + ","; lines += result.getJsonObject("geo_position").getJsonNumber("longitude") + "\r\n"; } Files.write(Paths.get("./out.csv"), lines.getBytes()); System.out.println("INFO: Wrote results to 'out.csv'."); } catch (Throwable e) { System.out.println("ERROR: Could not write CSV File 'out.csv'. Error: " + e); } }
/** * Create a new Point32 based on the given JSON object. Any missing values will be set to their * defaults. * * @param jsonObject The JSON object to parse. * @return A Point32 message based on the given JSON object. */ public static Point32 fromJsonObject(JsonObject jsonObject) { // check the fields float x = jsonObject.containsKey(Point32.FIELD_X) ? (float) jsonObject.getJsonNumber(Point32.FIELD_X).doubleValue() : 0.0f; float y = jsonObject.containsKey(Point32.FIELD_Y) ? (float) jsonObject.getJsonNumber(Point32.FIELD_Y).doubleValue() : 0.0f; float z = jsonObject.containsKey(Point32.FIELD_Z) ? (float) jsonObject.getJsonNumber(Point32.FIELD_Z).doubleValue() : 0.0f; return new Point32(x, y, z); }
@Override public Photo readFrom( Class<Photo> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try (JsonReader in = Json.createReader(entityStream)) { JsonObject jsonPhoto = in.readObject(); Photo p = new Photo(); p.setId(jsonPhoto.getInt("id")); p.setTitle(jsonPhoto.getString("title", null)); p.setUrl(jsonPhoto.getString("url", null)); p.setuComment(jsonPhoto.getString("uComment", null)); p.setDate(new Date(jsonPhoto.getJsonNumber("date").longValue())); User u = em.find(User.class, jsonPhoto.getString("uId")); p.setUser(u); return p; } catch (JsonException | ClassCastException ex) { throw new BadRequestException("Ongeldige JSON invoer"); } }
public void fromJsonObject(JsonObject jsonObject) { id = Long.valueOf(jsonObject.getJsonNumber("kid").longValue()); name = jsonObject.getString("nachname"); vname = jsonObject.getString("vorname"); email = jsonObject.getString("email"); bestellungURI = jsonObject.getString("bestellungenUri"); }
/** * Create a new Int64 based on the given JSON object. Any missing values will be set to their * defaults. * * @param jsonObject The JSON object to parse. * @return A Int64 message based on the given JSON object. */ public static Int64 fromJsonObject(JsonObject jsonObject) { // check the fields long data = jsonObject.containsKey(Int64.FIELD_DATA) ? jsonObject.getJsonNumber(Int64.FIELD_DATA).longValue() : 0L; return new Int64(data); }
/** @return equipType */ public List<Boolean> getEquipType() { List<Boolean> equipType = new ArrayList<Boolean>(); JsonObject json_equip_type = this.json.getJsonObject("api_equip_type"); for (int i = 1; ; ++i) { JsonNumber number = json_equip_type.getJsonNumber(String.valueOf(i)); if (number == null) break; equipType.add(number.intValue() != 0); } return equipType; }
@Override public JsonObject changeFilterState(JsonObject newFilterState) { if (newFilterState != null) { // new value of amount JsonObject amountJson = newFilterState.getJsonObject("amount"); setAmount((float) amountJson.getJsonNumber("value").doubleValue()); JsonObject sizeJson = newFilterState.getJsonObject("radius"); setRadius(sizeJson.getJsonNumber("value").intValue()); JsonObject thresholdJson = newFilterState.getJsonObject("threshold"); setThreshold(thresholdJson.getJsonNumber("value").intValue()); Main.debug(id.toString() + " \n" + toString()); return newFilterState; } return null; }
public static <T extends Factory> T objectFromJson(JsonObject json, T prototype) throws ParseException { T object = (T) prototype.create(); Method[] methods = object.getClass().getMethods(); for (final Method method : methods) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) { final String name = Introspector.decapitalize(method.getName().substring(3)); Class<?> parameterType = method.getParameterTypes()[0]; if (json.containsKey(name)) try { if (parameterType.equals(boolean.class)) { method.invoke(object, json.getBoolean(name)); } else if (parameterType.equals(int.class)) { method.invoke(object, json.getJsonNumber(name).intValue()); } else if (parameterType.equals(long.class)) { if (json.get(name).getValueType() == JsonValue.ValueType.NUMBER) { method.invoke(object, json.getJsonNumber(name).longValue()); } } else if (parameterType.equals(double.class)) { method.invoke(object, json.getJsonNumber(name).doubleValue()); } else if (parameterType.equals(String.class)) { method.invoke(object, json.getString(name)); } else if (parameterType.equals(Date.class)) { method.invoke(object, dateFormat.parse(json.getString(name))); } else if (parameterType.equals(Map.class)) { method.invoke(object, MiscFormatter.fromJson(json.getJsonObject(name))); } } catch (IllegalAccessException | InvocationTargetException error) { } } } return object; }
@Test public void convertFilledListToJson() { final List<Registration> registrations = new ArrayList<>(); final Registration expected = mock(Registration.class); when(expected.getId()).thenReturn(42l); registrations.add(expected); mockQuery(Registration.findAll, registrations); final JsonArray result = this.cut.allAsJson(); assertNotNull(result); assertThat(result.size(), is(1)); final JsonObject actual = result.getJsonObject(0); final JsonNumber actualId = actual.getJsonNumber(Registrations.CONFIRMATION_ID); assertThat(expected.getId(), is(actualId.longValue())); }
@Override public void onClientData(final JsonObject instruction) { if (instruction.containsKey(ClientToServerModel.HANDLER_SELECTION.toStringValue())) { final int widgetId = instruction .getJsonNumber(ClientToServerModel.HANDLER_SELECTION.toStringValue()) .intValue(); final PSelectionEvent<PTreeItem> selectionEvent = new PSelectionEvent<>(this, UIContext.get().getObject(widgetId)); for (final PSelectionHandler<PTreeItem> handler : selectionHandlers) { handler.onSelection(selectionEvent); } } else { super.onClientData(instruction); } }
@Test public void should_return_notFound_if_attempt_doesnt_exist() { final String uri = String.format(URI, "type", "key"); Response response = invoke(uri).get(); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); JsonObject token1 = response.readEntity(JsonObject.class); JsonArray jsonArray = token1.getJsonObject("errors").getJsonArray("messages"); for (int i = 0; jsonArray.size() > i; i++) { JsonObject item = jsonArray.getJsonObject(i); assertEquals( NotFoundEnum.ATTEMPT.getCode().longValue(), item.getJsonNumber("code").longValue()); assertNull(item.getJsonString("field")); assertEquals("attempt_not_found", item.getJsonString("message").getString()); } }
ObservableList<Question> getObservableList() throws IOException { String url = "http://api.stackexchange.com/2.2/search?tagged=javafx&site=stackoverflow"; URL host = new URL(url); JsonReader jr = Json.createReader(new GZIPInputStream(host.openConnection().getInputStream())); JsonObject jsonObject = jr.readObject(); JsonArray jsonArray = jsonObject.getJsonArray("items"); ObservableList<Question> answer = FXCollections.observableArrayList(); jsonArray .iterator() .forEachRemaining( (JsonValue e) -> { JsonObject obj = (JsonObject) e; JsonString name = obj.getJsonObject("owner").getJsonString("display_name"); JsonString quest = obj.getJsonString("title"); JsonNumber jsonNumber = obj.getJsonNumber("creation_date"); Question q = new Question(name.getString(), quest.getString(), jsonNumber.longValue() * 1000); answer.add(q); }); return answer; }
private static boolean loadATMSwitchConfig(String connId) throws Exception { InputStream is = null; boolean isLoadedFlag = false; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); is = classLoader.getResource(atmSwitchConfigFileName).openStream(); if (is == null) { throw new Exception("Unable to load config file - " + atmSwitchConfigFileName); } try { JsonReader jsonReader = Json.createReader(is); JsonObject allConfigs = jsonReader.readObject(); JsonString logFileLocation = allConfigs.getJsonString(logFileLocationKey); if (logFileLocation == null) { throw new Exception(logFileLocationKey + " parameter missing in the configuration...."); } if ("".equals(connId)) logger = (new AsynchLogger(logFileLocation.toString() + "/ISOSysLog", Level.INFO)) .getLogger("ISOSysLog"); JsonArray serverConfigs = allConfigs.getJsonArray(serverConfigKey); if (serverConfigs == null) { throw new Exception( serverConfigKey + " parameter missing. No server Configurations specified...."); } logger.info("Initializing ATM Switch Configuration...."); if (manifestAttrs != null && "".equals(connId)) { logger.info( "Build version " + manifestAttrs.getValue("Implementation-Version") + " Build Date " + manifestAttrs.getValue("Build-Time")); } for (int i = 0; i < serverConfigs.size(); i++) { JsonObject serverConfig = serverConfigs.getJsonObject(i); JsonString host = serverConfig.getJsonString(serverHostKey); JsonNumber port = serverConfig.getJsonNumber(portKey); JsonNumber connTimeOut = serverConfig.getJsonNumber(connTimeOutKey); JsonNumber readTimeOut = serverConfig.getJsonNumber(readTimeOutKey); JsonNumber retry = serverConfig.getJsonNumber(retryKey); JsonNumber threadTimeOut = serverConfig.getJsonNumber(threadTimeOutKey); JsonString logLevelJson = serverConfig.getJsonString(loglevelKey); JsonNumber echoTimeInterval = serverConfig.getJsonNumber(echoTimeIntervalKey); JsonString uidFormat = serverConfig.getJsonString("uidFormat"); if (host == null || port == null) { logger.error( serverConfig + " Bad configuration for connection ( Host OR Port is missing ). Not Loading this connection...."); continue; } if (uidFormat == null) { logger.error( serverConfig + " Bad configuration for connection ( uidFormat is missing ). Not Loading this connection...."); continue; } Level level = null; if (logLevelJson == null) { level = Level.INFO; } else { String logLevel = logLevelJson.getString(); if (logLevel.equalsIgnoreCase("TRACE")) { level = Level.TRACE; } else if (logLevel.equalsIgnoreCase("DEBUG")) { level = Level.DEBUG; } else { level = Level.INFO; } } MessageUIDGenerator messageUIDGenerator = MessageUIDGeneratorFactory.getMessageUIDGenerator(uidFormat.toString()); if (!"".equals(connId)) { if (!connId.equalsIgnoreCase(host.getString() + "_" + port.intValue())) { continue; } } ATMSwitchTCPHandler.manualStopPool.put( host.getString() + "_" + String.valueOf(port.intValue()), Boolean.FALSE); ConnectionBean bean = new ConnectionBean( host.getString(), port.intValue(), (connTimeOut == null ? 8000 : connTimeOut.intValue()), (readTimeOut == null ? 8000 : readTimeOut.intValue()), (threadTimeOut == null ? 5000 : threadTimeOut.intValue()), (retry == null ? 3 : retry.intValue()), (echoTimeInterval == null ? 0 : echoTimeInterval.intValue())); ServerContainer container = new ServerContainer(bean, logFileLocation.getString(), level, messageUIDGenerator); try { if (container.connect(false)) { logger.info(bean.toString() + " Loaded...."); isLoadedFlag = true; } else { logger.warn(bean.toString() + " could not be loaded...."); } } catch (InterruptedException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) Interrupted Exception", e); } catch (ExecutionException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) ExecutionException", e); } catch (IOException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) IOException", e); } catch (Exception e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) Exception", e); } } } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.error("IOException in closing the stream for JSON config property file....", e); } } } return isLoadedFlag; }
private void readJson() { // 艦娘一覧 JsonArray apiMstShip = this.json.getJsonArray("api_mst_ship"); if (apiMstShip != null) { this.ships.clear(); for (int i = 0; i < apiMstShip.size(); i++) { JsonObject object = (JsonObject) apiMstShip.get(i); String id = object.getJsonNumber("api_id").toString(); this.ships.put(id, this.toShipInfoDto(object)); } } // 装備一覧 JsonArray apiMstSlotitem = this.json.getJsonArray("api_mst_slotitem"); if (apiMstSlotitem != null) { this.items.clear(); for (int i = 0; i < apiMstSlotitem.size(); i++) { JsonObject object = (JsonObject) apiMstSlotitem.get(i); ItemInfoDto item = new ItemInfoDto(object); int id = object.getJsonNumber("api_id").intValue(); this.items.put(id, item); } } JsonArray json_maparea = this.json.getJsonArray("api_mst_maparea"); if (json_maparea != null) { this.maparea.clear(); for (JsonValue elem : json_maparea) { this.maparea.add(new MapAreaDto((JsonObject) elem)); } } JsonArray json_mapinfo = this.json.getJsonArray("api_mst_mapinfo"); if (json_mapinfo != null) { this.mapinfo.clear(); for (JsonValue elem : json_mapinfo) { MapInfoDto dto = new MapInfoDto((JsonObject) elem); this.mapinfo.put(dto.getId(), dto); } } JsonArray json_mission = this.json.getJsonArray("api_mst_mission"); if (json_mission != null) { this.mission.clear(); for (JsonValue elem : json_mission) { MissionDto dto = new MissionDto((JsonObject) elem); this.mission.put(dto.getId(), dto); } } JsonArray json_stype = this.json.getJsonArray("api_mst_stype"); if (json_stype != null) { this.stype.clear(); for (JsonValue elem : json_stype) { this.stype.add(new ShipTypeDto((JsonObject) elem)); } } JsonArray json_useitem = this.json.getJsonArray("api_mst_useitem"); if (json_useitem != null) { this.useItem.clear(); for (JsonValue elem : json_useitem) { UseItemInfoDto dto = new UseItemInfoDto((JsonObject) elem); this.useItem.put(dto.getId(), dto); } } this.time = new Date(); }
@OnMessage public void message( @PathParam("gameidentifier") String gameIdentifier, String message, Session client) throws IOException, EncodeException { JsonObject jsonObj = Json.createReader(new StringReader(message)).readObject(); String command = jsonObj.getString("command"); if (command.equals("getPlayers")) { JsonArrayBuilder arrayBuilder = getCouchStorage().playersList(gameIdentifier); JsonObjectBuilder objectBuilder = Json.createObjectBuilder().add("players", arrayBuilder).add("command", "loadPlayers"); client.getBasicRemote().sendText(objectBuilder.build().toString()); } else if (command.equals("addPlayer")) { String playerUUID = jsonObj.getString("playerID"); Point position = new Point(jsonObj.getJsonNumber("positionX"), jsonObj.getJsonNumber("positionY")); getCouchStorage().addPlayer(playerUUID, position, gameIdentifier); JsonObjectBuilder objectBuilderForAdd = Json.createObjectBuilder() .add("command", "addedPlayer") .add( "data", Json.createObjectBuilder() .add("PlayerID", playerUUID) .add("positionX", position.getPointX()) .add("positionY", position.getPointY())); String jsonString = objectBuilderForAdd.build().toString(); for (Session peer : client.getOpenSessions()) { peer.getBasicRemote().sendText(jsonString); } } else if (command.equals("movePlayer")) { JsonObject jsonMoveData = Json.createReader(new StringReader(message)).readObject().getJsonObject("data"); JsonObjectBuilder objectBuilder = Json.createObjectBuilder().add("command", "playerMoved").add("data", jsonMoveData); String playerId = jsonMoveData.getString("PlayerID"); Point position = new Point( jsonMoveData.getJsonNumber("positionX"), jsonMoveData.getJsonNumber("positionY")); Point targetPosition = new Point( jsonMoveData.getJsonNumber("targetPositionX"), jsonMoveData.getJsonNumber("targetPositionY")); int direction = jsonMoveData.getInt("direction"); getCouchStorage().updatePlayer(playerId, position, direction, targetPosition); String jsonString = objectBuilder.build().toString(); for (Session peer : client.getOpenSessions()) { peer.getBasicRemote().sendText(jsonString); } } else if (command.equals("synchronize")) { JsonArray items = Json.createReader(new StringReader(message)).readObject().getJsonArray("data"); getCouchStorage().synchronizePlayers(items); JsonArrayBuilder arrayBuilder = getCouchStorage().playersList(gameIdentifier); JsonObjectBuilder objectBuilder = Json.createObjectBuilder().add("players", arrayBuilder).add("command", "synchronize"); String jsonString = objectBuilder.build().toString(); for (Session peer : client.getOpenSessions()) { peer.getBasicRemote().sendText(jsonString); } } }
public Phase( BattleExDto battle, JsonObject object, BattlePhaseKind kind, int[] beforeFriendHp, int[] beforeFriendHpCombined, int[] beforeEnemyHp) { boolean isCombined = (beforeFriendHpCombined != null); this.kind = kind; this.isNight = kind.isNight(); this.nowFriendHp = beforeFriendHp.clone(); this.nowEnemyHp = beforeEnemyHp.clone(); if (isCombined) { this.nowFriendHpCombined = beforeFriendHpCombined.clone(); } else { this.nowFriendHpCombined = null; } // 夜間触接 JsonValue jsonTouchPlane = object.get("api_touch_plane"); if ((jsonTouchPlane != null) && (jsonTouchPlane != JsonValue.NULL)) { this.touchPlane = JsonUtils.getIntArray(object, "api_touch_plane"); } // 照明弾発射艦 JsonValue jsonFlarePos = object.get("api_flare_pos"); if ((jsonFlarePos != null) && (jsonFlarePos != JsonValue.NULL)) { this.flarePos = JsonUtils.getIntArray(object, "api_flare_pos"); } // 攻撃シーケンスを読み取る // // 航空戦(通常) JsonObject kouku = object.getJsonObject("api_kouku"); if (kouku != null) { this.air = new AirBattleDto(kouku, isCombined); // 昼戦の触接はここ this.touchPlane = this.air.touchPlane; // 制空はここから取る this.seiku = this.air.seiku; } // 支援艦隊 JsonNumber support_flag = object.getJsonNumber("api_support_flag"); if ((support_flag != null) && (support_flag.intValue() != 0)) { JsonObject support = object.getJsonObject("api_support_info"); JsonValue support_hourai = support.get("api_support_hourai"); JsonValue support_air = support.get("api_support_airatack"); if ((support_hourai != null) && (support_hourai != JsonValue.NULL)) { JsonArray edam = ((JsonObject) support_hourai).getJsonArray("api_damage"); if (edam != null) { this.support = BattleAtackDto.makeSupport(edam); } } else if ((support_air != null) && (support_air != JsonValue.NULL)) { JsonValue stage3 = ((JsonObject) support_air).get("api_stage3"); if ((stage3 != null) && (stage3 != JsonValue.NULL)) { this.support = BattleAtackDto.makeSupport(((JsonObject) stage3).getJsonArray("api_edam")); } } this.supportType = toSupport(support_flag.intValue()); } else { this.supportType = ""; } // 航空戦(連合艦隊のみ?) JsonObject kouku2 = object.getJsonObject("api_kouku2"); if (kouku2 != null) this.air2 = new AirBattleDto(kouku2, isCombined); // 開幕 this.opening = BattleAtackDto.makeRaigeki(object.get("api_opening_atack"), kind.isOpeningSecond()); // 砲撃 this.hougeki = BattleAtackDto.makeHougeki(object.get("api_hougeki"), kind.isHougekiSecond()); // 夜戦 this.hougeki1 = BattleAtackDto.makeHougeki(object.get("api_hougeki1"), kind.isHougeki1Second()); this.hougeki2 = BattleAtackDto.makeHougeki(object.get("api_hougeki2"), kind.isHougeki2Second()); this.hougeki3 = BattleAtackDto.makeHougeki(object.get("api_hougeki3"), kind.isHougeki3Second()); // 雷撃 this.raigeki = BattleAtackDto.makeRaigeki(object.get("api_raigeki"), kind.isRaigekiSecond()); // ダメージを反映 // if (this.air != null) this.doAtack(this.air.atacks); this.doAtack(this.support); if (this.air2 != null) this.doAtack(this.air2.atacks); this.doAtack(this.opening); this.doAtack(this.hougeki); this.doAtack(this.hougeki1); this.doAtack(this.raigeki); this.doAtack(this.hougeki2); this.doAtack(this.hougeki3); this.json = object.toString(); }