public ListItemReader<JsonObject> setResource() throws MalformedURLException { // Date date = new Date(); // String today= new SimpleDateFormat("yyyyMMdd").format(date); // local time이 일치하지 않으므로, 전날 종료된 경기정보 업데이트이므로 date -1 Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String today = new SimpleDateFormat("yyyyMMdd").format(cal.getTime()); URL url = new URL("http://data.nba.com/data//json/nbacom/2015/gameline/" + today + "/games.json"); try (InputStream is = url.openStream(); JsonReader rdr = Json.createReader(is)) { JsonObject obj = rdr.readObject(); if (obj != null && obj.get("games") != null && obj.getJsonArray("games").size() > 0) { for (int idx = 0; idx < obj.getJsonArray("games").size(); idx++) { items.add(obj.getJsonArray("games").getJsonObject(idx)); } } } catch (IOException e) { e.printStackTrace(); } ListItemReader<JsonObject> reader = new ListItemReader<>(this.items); return reader; }
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); } }
public static void dumpJSON(JsonValue tree, String key, String depthPrefix) { if (key != null) logger.info(depthPrefix + "Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: logger.info(depthPrefix + "OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) dumpJSON(object.get(name), name, depthPrefix + " "); break; case ARRAY: logger.info(depthPrefix + "ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) dumpJSON(val, null, depthPrefix + " "); break; case STRING: JsonString st = (JsonString) tree; logger.info(depthPrefix + "STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; logger.info(depthPrefix + "NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: logger.info(depthPrefix + tree.getValueType().toString()); break; } }
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"); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String prenom = request.getParameter("prenom"); String pseudo = request.getParameter("pseudo"); String mdp = request.getParameter("mdp"); Map<String, Object> config = new HashMap<String, Object>(); config.put("javax.json.stream.JsonGenerator.prettyPrinting", Boolean.valueOf(true)); JsonBuilderFactory factory = Json.createBuilderFactory(config); JsonObject value; try { gestionJoueurs.creerJoueur(prenom, pseudo, mdp); } catch (JoueurDejaExistantException e) { value = factory.createObjectBuilder().add("success", "0").add("message", e.getMessage()).build(); response.setContentType("application/json"); response.getWriter().write(value.toString()); return; } HttpSession session = request.getSession(); Joueur nouveauJoueur = new Joueur(prenom, pseudo, mdp); session.setAttribute("joueur", nouveauJoueur); value = factory .createObjectBuilder() .add("success", "1") .add("message", "Inscription avec succès!") .build(); response.setContentType("application/json"); response.getWriter().write(value.toString()); }
public PracticeUserDto(JsonObject obj) { this.id = obj.getInt("api_enemy_id"); this.name = obj.getString("api_enemy_name"); this.comment = obj.getString("api_enemy_comment"); this.level = obj.getInt("api_enemy_level"); this.state = obj.getInt("api_state"); }
private void route(JsonObject message, int fromNode) { String text = message.getString("text", null); int from = message.getInt("from", -1); int to = message.getInt("to", -1); if (fromNode == from && to >= 0 && text != null) { SwingUtilities.invokeLater( () -> { messages.addPacket(from, to, text, getByNode(from).getNetwork()); }); if (to == 0) { for (int i = 0; i < connections.size(); i++) { Connection c = connections.get(i); if (c != null && links.isNeighbour(fromNode, c.getNode())) { send(c, text, from, to); } } } else { Connection c = getByNode(to); if (c != null && links.isNeighbour(from, to)) { send(c, text, from, to); } } } }
private static void readJsonFile() { try (JsonReader jsonReader = Json.createReader( new FileReader( Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) { JsonStructure jsonStructure = jsonReader.read(); JsonValue.ValueType valueType = jsonStructure.getValueType(); if (valueType == JsonValue.ValueType.OBJECT) { JsonObject jsonObject = (JsonObject) jsonStructure; JsonValue firstName = jsonObject.get("firstName"); LOGGER.info("firstName=" + firstName); JsonValue emailAddresses = jsonObject.get("phoneNumbers"); if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) { JsonArray jsonArray = (JsonArray) emailAddresses; for (int i = 0; i < jsonArray.size(); i++) { JsonValue jsonValue = jsonArray.get(i); LOGGER.info("emailAddress(" + i + "): " + jsonValue); } } } else { LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT); } } catch (FileNotFoundException e) { LOGGER.severe("Failed to open file: " + e.getMessage()); } }
public JsonObject processInput(byte[] input) { ByteArrayInputStream byteInStream = new ByteArrayInputStream(input); JsonReader jsonReader = Json.createReader(byteInStream); JsonObject ob = jsonReader.readObject(); PieLogger.info(this.getClass(), String.format("ConnectionText: %s", ob.toString())); return ob; }
/** * @param key * @return JsonObject value or null */ public JsonObject getObject(String key) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null && value.getValueType() == ValueType.OBJECT) { return (JsonObject) value; } return null; }
/** * Get long value out of the message json payload * * @param key Key to find value for * @param defaultValue Default value if key can't be found * @return value in object, or the provided default */ public long getLong(String key, long defaultValue) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null && value.getValueType() == ValueType.NUMBER) { return ((JsonNumber) value).longValue(); } return defaultValue; }
/** * 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); }
@Override public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) { JsonObject data = json.getJsonObject("api_data"); if (data != null) { this.apiBasic(data.getJsonObject("api_basic")); this.apiSlotItem(data.getJsonArray("api_slot_item")); } }
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JsonObject jsonObjectRequest = toolJSON.getJsonObjectRequest(request); String login = jsonObjectRequest.getString(Constants.PARAMETER_LOGIN); String password = toolMD5.generateMD5(jsonObjectRequest.getString(Constants.PARAMETER_PASSWORD)); if (login != null && password != null && login.length() != 0 && password.length() != 0) { user = businessLogicUser.checkExistUserLoginPassword(login, password); } if (null != user) { if (user.getActive()) { Log.debug(this, "User exist in database"); toolSession.addUserSession(request, user); JsonObject jsonObjectResponse = Json.createObjectBuilder() .add(Constants.PARAMETER_IDUSER, user.getId()) .add(Constants.PARAMETER_IDROLE, user.getRole().getId()) .build(); toolJSON.setJsonObjectResponse(response, jsonObjectResponse); } else { JsonObject jsonObjectResponse = Json.createObjectBuilder() .add( Constants.PARAMETER_MESSAGE, textBean.findLocaleTextByKey( Constants.TEXT_MESSAGE_ACTOVE_FALSE, toolCookie.getLocaleName(request))) .add(Constants.PARAMETER_IDUSER, 0) .add(Constants.PARAMETER_IDROLE, 0) .build(); toolJSON.setJsonObjectResponse(response, jsonObjectResponse); } } else { Log.debug(this, "User is not exist in database"); JsonObject jsonObjectResponse = Json.createObjectBuilder() .add( Constants.PARAMETER_MESSAGE, textBean.findLocaleTextByKey( Constants.TEXT_MESSAGE_WRONG_LOGIN_OR_PASSWORD, toolCookie.getLocaleName(request))) .add(Constants.PARAMETER_IDUSER, 0) .add(Constants.PARAMETER_IDROLE, 0) .build(); toolJSON.setJsonObjectResponse(response, jsonObjectResponse); } Log.debug(this, "NO redirects!"); return null; }
private void generateFieldsAndMethods( final Writer writer, final JsonObject object, final String prefix, final Collection<String> imports) throws IOException { final Map<String, JsonObject> nestedTypes = new TreeMap<String, JsonObject>(); { final Iterator<Map.Entry<String, JsonValue>> iterator = object.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, JsonValue> entry = iterator.next(); final String key = entry.getKey(); final String fieldName = toJavaFieldName(key); switch (entry.getValue().getValueType()) { case ARRAY: imports.add("java.util.List"); handleArray(writer, prefix, nestedTypes, entry.getValue(), key, fieldName, 1, imports); break; case OBJECT: final String type = toJavaName(fieldName); nestedTypes.put(type, JsonObject.class.cast(entry.getValue())); fieldGetSetMethods(writer, key, fieldName, type, prefix, 0, imports); break; case TRUE: case FALSE: fieldGetSetMethods(writer, key, fieldName, "Boolean", prefix, 0, imports); break; case NUMBER: fieldGetSetMethods(writer, key, fieldName, "Double", prefix, 0, imports); break; case STRING: fieldGetSetMethods(writer, key, fieldName, "String", prefix, 0, imports); break; case NULL: default: throw new UnsupportedOperationException("Unsupported " + entry.getValue() + "."); } if (iterator.hasNext()) { writer.write("\n"); } } } if (!object.isEmpty() && !nestedTypes.isEmpty()) { writer.write("\n"); } final Iterator<Map.Entry<String, JsonObject>> entries = nestedTypes.entrySet().iterator(); while (entries.hasNext()) { final Map.Entry<String, JsonObject> entry = entries.next(); writer.write(prefix + "public static class " + entry.getKey() + " {\n"); generateFieldsAndMethods(writer, entry.getValue(), " " + prefix, imports); writer.write(prefix + "}\n"); if (entries.hasNext()) { writer.write("\n"); } } }
/** * Get boolean value out of the message json payload * * @param key Key to find value for * @param defaultValue Default value if key can't be found * @return value in object, or the provided default */ public boolean getBoolean(String key, boolean defaultValue) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null) { if (value.getValueType() == ValueType.FALSE) return false; if (value.getValueType() == ValueType.TRUE) return true; } return defaultValue; }
public boolean isValid(JsonObject object) { try { object.getInt(SECS); object.getInt(COUNTER); return true; } catch (NullPointerException | ClassCastException ex) { return false; } }
// Returns the JSON Object representing the album having `id`. private void actionGetAlbum(Router router, Request request, String id) { for (JsonObject album : catalog.getValuesAs(JsonObject.class)) { if (album.getString("id").equals(id)) { router.sendJsonResponse(200, "OK", album); return; } } router.sendJsonError(404, "Not found"); }
@POST @Consumes({"application/json"}) @Produces("text/plain") /** Запись или обновление данных о пользователе с передачей их JSON-потоком */ public String addUserJson( @QueryParam("token") String token, JsonObject userData, @PathParam("schema") String schemaName) { // Проверка клиента UserLogon logon = usersController.getUserLogon(token); if (logon == null) { return "Unknown token: " + token; } // Проверка схемы int schemaID = 0; ConnectionSchema connectionSchema = null; try { connectionSchema = cg.getConnectionSchemaByAlias(schemaName); schemaID = connectionSchema.getId(); } catch (CarabiException ex) { return "Unknown schema: " + schemaName; } catch (Exception ex) { Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex); return ex.getMessage(); } String login = userData.getString("login"); JsonObjectBuilder userDataNew = Utls.jsonObjectToBuilder(userData); // если редактируемый пользователь с таким логином существует -- проверка, что нет коллизии // между базами long userID = usersPercistence.getUserID(login); boolean userIsNew = userID == -1; if (!userIsNew) { try { CarabiUser user = usersController.findUser(login); // пользователь из новой БД должен иметь такой же пароль, чтобы быть принятым автоматически if (!user.getDefaultSchema().getId().equals(schemaID) && !user.getAllowedSchemas().contains(connectionSchema) && !user.getPassword().equals(userData.getString("password"))) { return "user " + login + " already registered with another database"; } userDataNew.add("id", "" + userID); } catch (CarabiException ex) { Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex); } } userDataNew.add("defaultSchemaId", schemaID); JsonArrayBuilder allowedSchemaIds = Json.createArrayBuilder(); allowedSchemaIds.add(schemaID); userDataNew.add("allowedSchemaIds", allowedSchemaIds.build()); try { return admin.saveUser(logon, userDataNew.build(), userIsNew, true).toString(); } catch (Exception ex) { Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex); return ex.getMessage(); } }
@Test public void shouldSaveCommands() { // Given String msg = "{ \n" + " \"messageBroadcast\":{ \n" + " \"cameraInfos\":{ \n" + " \"target\":{ \n" + " \"x\":0,\n" + " \"y\":0,\n" + " \"z\":0\n" + " },\n" + " \"camPos\":{ \n" + " \"x\":2283.8555345202267,\n" + " \"y\":1742.2368392950543,\n" + " \"z\":306.5925754554133\n" + " },\n" + " \"camOrientation\":{ \n" + " \"x\":-0.16153026619659236,\n" + " \"y\":0.9837903505522302,\n" + " \"z\":0.07787502335635015\n" + " },\n" + " \"layers\":\"create layer\",\n" + " \"colourEditedObjects\":true,\n" + " \"clipping\":\"1\",\n" + " \"explode\":\"3\",\n" + " \"smartPath\":[ \n" + " \"9447-9445-9441\",\n" + " \"9447-9445-9443\",\n" + " \"9447-9445-9444\",\n" + " \"9446\"\n" + " ]\n" + " }\n" + " }\n" + "}"; JsonObject jsObj = Json.createReader(new StringReader(msg)).readObject(); JsonObject messageBroadcast = jsObj.containsKey("messageBroadcast") ? jsObj.getJsonObject("messageBroadcast") : null; CollaborativeMessage collaborativeMessage = Mockito.spy( new CollaborativeMessage( ChannelMessagesType.COLLABORATIVE_COMMANDS, "key-12545695-7859-458", messageBroadcast, "slave1")); CollaborativeRoom room = Mockito.spy(new CollaborativeRoom(master)); // When room.addSlave(slave1); room.addSlave(slave2); JsonObject commands = collaborativeMessage.getMessageBroadcast(); room.saveCommand(commands); Assert.assertTrue(room.getCommands().entrySet().size() == 1); }
@Override @NotNull(message = "JSON is never NULL") public JsonObject json() throws IOException { final JsonObject obj = new JsonNode(this.storage.xml().nodes(this.xpath()).get(0)).json(); final JsonObjectBuilder json = Json.createObjectBuilder(); for (final Map.Entry<String, JsonValue> val : obj.entrySet()) { json.add(val.getKey(), val.getValue()); } return json.add("comments", this.storage.xml().nodes(this.comment()).size()).build(); }
/** @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 String toString() { JsonObject json = Json.createObjectBuilder() .add("amount", Json.createObjectBuilder().add("value", amount).build()) .add("radius", Json.createObjectBuilder().add("value", radius).build()) .add("threshold", Json.createObjectBuilder().add("value", threshold).build()) .build(); return "from unsharp: \n" + json.toString(); }
// Update the existing album with `id`. // // Display the deleted album. private void actionDeleteAlbum(Router router, Request request, String id) { for (JsonObject oalbum : catalog.getValuesAs(JsonObject.class)) { if (oalbum.getString("id").equals(id)) { // TODO add model layer and data management router.sendJsonResponse(200, "OK", oalbum); return; } } // No album with this ID found, return error router.sendJsonError(404, "Not found"); }
private void checkFilteredDocuments( final JsonArray filtered, final int size, final String... properties) { assertEquals(size, filtered.size()); final HashSet<String> strings = Sets.newHashSet(properties); for (final JsonObject document : filtered.getValuesAs(JsonObject.class)) { for (final String property : document.keySet()) { assertTrue(strings.contains(property)); } } }
/** * @see org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.smack.packet.Packet) */ @Override public void processPacket(Packet packet) { Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GcmPacketExtension.GCM_NAMESPACE); String json = gcmPacket.getJson(); JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject jsonObject = jsonReader.readObject(); Object messageType = jsonObject.get("message_type"); System.out.println(messageType); }
@DirtiesContext @Test public void helloRouteMustHaveBeenCalled() throws InterruptedException { JsonObject model = Json.createObjectBuilder().add("helloMessage", "toto").build(); Map headers = new HashMap(); headers.put("httpRequestType", Builder.constant("POST")); helloEntryPoint.sendBodyAndHeaders(model.toString(), headers); verify(helloService).persistHello((HelloEntity) anyObject()); helloRouteMock.expectedMessageCount(1); helloRouteMock.assertIsSatisfied(); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); HttpSession user = req.getSession(); PrintWriter out = resp.getWriter(); SpejdResultAnalyser result = null; JsonObject response; JsonReader jsonReader = Json.createReader(new InputStreamReader(req.getInputStream(), StandardCharsets.ISO_8859_1)); JsonObject jsonObject = jsonReader.readObject(); jsonReader.close(); System.out.println("REQUEST"); System.out.println(jsonObject); String originalText = jsonObject.getString("text"); int space = jsonObject.getInt("space"); String xml = getXml(originalText, user.getId()); try { result = new SpejdResultAnalyser(xml.replace("SYSTEM \"xcesAnaIPI.dtd\"", "")); } catch (ParserConfigurationException | SAXException e) { out.println(e.toString()); } assert result != null; /** do analysis of xml spejd result */ SubstantivePairs pairs = result.doAnalysis().makePair(space); /** * create json response { text: ... xml: ... pairs: [ { subst1: ... subst2: ... quantity: ... }, * ...] } */ JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); for (SubstantivePair pair : pairs) { arrayBuilder.add( Json.createObjectBuilder() .add("subst1", pair.getSubst1()) .add("subst2", pair.getSubst2()) .add("quantity", pair.getQuantity())); } Charset.forName("UTF-8").encode(originalText); JsonArray array = arrayBuilder.build(); response = Json.createObjectBuilder() .add("text", originalText) .add("xml", xml) .add("pairs", array) .build(); System.out.println("RESPONSE"); System.out.println(response); out.print(response); }
@Test public void shouldReturnValidMetadataJson() throws JMSException { when(message.getText()).thenReturn(envelopeString()); JsonObject result = toJsonObject(message); assertThat(result.getString("id"), is(A_MESSAGE_ID)); assertThat(result.getString("name"), is(A_NAME)); assertThat(result.getJsonObject("context").getString("user"), is(A_USER_ID)); assertThat(result.getJsonObject("context").getString("session"), is(A_SESSION_ID)); }
/** * Create a new Twist based on the given JSON object. Any missing values will be set to their * defaults. * * @param jsonObject The JSON object to parse. * @return A Twist message based on the given JSON object. */ public static Twist fromJsonObject(JsonObject jsonObject) { // check the fields Vector3 linear = jsonObject.containsKey(Twist.FIELD_LINEAR) ? Vector3.fromJsonObject(jsonObject.getJsonObject(Twist.FIELD_LINEAR)) : new Vector3(); Vector3 angular = jsonObject.containsKey(Twist.FIELD_ANGULAR) ? Vector3.fromJsonObject(jsonObject.getJsonObject(Twist.FIELD_ANGULAR)) : new Vector3(); return new Twist(linear, angular); }