private void initUserSelectionMap() { try { String jsonString = readFromFile(NEWS_CAT_FILE); Crashlytics.log(Log.INFO, LOG_TAG, "jsonString - " + jsonString); fullJsonMap = JsonHelper.toMap(new JSONObject(jsonString)); Crashlytics.log(Log.INFO, LOG_TAG, "fullJsonMap - " + fullJsonMap.toString()); userSelectionMap = getUserFeedMapFromJsonMap(fullJsonMap); Crashlytics.log(Log.INFO, LOG_TAG, "UserSelectionMap - " + userSelectionMap.toString()); } catch (JSONException e) { Crashlytics.logException(e); } }
public void updateNewsCatFileWithNewAssets() { try { String jsonString = readFromFile(NEWS_CAT_FILE, true); Crashlytics.log(Log.INFO, LOG_TAG, "newJsonString - " + jsonString); Map<String, Object> newFullJsonMap = JsonHelper.toMap(new JSONObject(jsonString)); Crashlytics.log(Log.INFO, LOG_TAG, "newFullJsonMap - " + newFullJsonMap.toString()); convertUserFeedMapToJsonMap(newFullJsonMap); Map<String, List<String>> newUserSelectionMap = getUserFeedMapFromJsonMap(newFullJsonMap); Crashlytics.log(Log.INFO, LOG_TAG, "newUserSelectionMap - " + newUserSelectionMap); setUserSelectionMap(newUserSelectionMap); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void shouldKeepParametersCase() { Person p = Person.create("name", "Joe", "last_name", "Schmoe"); Map map = JsonHelper.toMap(p.toJson(true)); a(map.get("name")).shouldBeEqual("Joe"); a(map.get("last_name")).shouldBeEqual("Schmoe"); map = JsonHelper.toMap(p.toJson(true, "Name", "Last_Name")); a(map.get("Name")).shouldBeEqual("Joe"); a(map.get("Last_Name")).shouldBeEqual("Schmoe"); }
@Test public void testRoundTrip1() throws Exception { System.out.println("testRoundTrip1()"); BasicDBObject expected = new BasicDBObject().append("stuff", true).append("stuff1", 1234.0); String json = JsonHelper.toJson(expected); Assert.assertEquals("{\"stuff\":true,\"stuff1\":1234.0}", json); BasicDBObject actual = JsonHelper.toJavaMap(json); Assert.assertEquals(expected, actual); Assert.assertEquals(actual, expected); }
/** * Executes a batch of queries. You define the queries to execute by calling 'beginBatch' and then * invoking the desired API methods that you want to execute as part of your batch as normal. * Invoking this method will then execute the API calls you made in the interim as a single batch * query. * * @param serial set to true, and your batch queries will always execute serially, in the same * order in which your specified them. If set to false, the Facebook API server may execute * your queries in parallel and/or out of order in order to improve performance. * @return a list containing the results of the batch execution. The list will be ordered such * that the first element corresponds to the result of the first query in the batch, and the * second element corresponds to the result of the second query, and so on. The types of the * objects in the list will match the type normally returned by the API call being invoked (so * calling users_getLoggedInUser as part of a batch will place a Long in the list, and calling * friends_get will place a Document in the list, etc.). * <p>The list may be empty, it will never be null. * @throws FacebookException * @throws IOException */ public List<? extends Object> executeBatch(boolean serial) throws FacebookException { List<String> clientResults = client.executeBatch(serial); List<Object> result = new ArrayList<Object>(); for (String clientResult : clientResults) { JSONArray doc; try { // Must ensure that JSONArray(String) constructor // is called. JSONArray(Object) behaves differently. doc = new JSONArray(clientResult); } catch (JSONException ex) { throw new RuntimeException("Error parsing client result", ex); } for (int count = 0; count < doc.length(); count++) { try { String response = (String) doc.get(count); Object responseObject = JsonHelper.parseCallResult(response); result.add(responseObject); } catch (Exception ignored) { result.add(null); } } } return result; }
@Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { this._callbackContext = callbackContext; if (ACTION_INIT.equals(action)) { return init(args.getString(0), args.getString(1), args.getString(2)); } else if (ACTION_LOGIN.equals(action)) { JSONArray permissions = args.optJSONArray(0); return login(permissions, callbackContext); } else if (ACTION_SHARE.equals(action)) { return shareOrLogin(args.getString(0), args.getString(1)); } else if (ACTION_FRIENDS_GET.equals(action)) { return friendsGet(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_FRIENDS_GET_ONLINE.equals(action)) { return friendsGetOnline(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_STREAM_PUBLISH.equals(action)) { // TODO } else if (ACTION_USERS_GET_INFO.equals(action)) { return usersGetInfo(args.getString(0), args.getString(1), callbackContext); } else if (ACTION_CALL_API_METHOD.equals(action)) { String method = args.getString(0); JSONObject params = args.getJSONObject(1); return callApiMethod(method, JsonHelper.toMap(params), callbackContext); } Log.e(TAG, "Unknown action: " + action); _callbackContext.sendPluginResult( new PluginResult(PluginResult.Status.ERROR, "Unimplemented method: " + action)); _callbackContext.error("Unimplemented method: " + action); return true; }
@Override public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonHelper helper = new JsonHelper(json); String name = helper.getString("name"); int amount = helper.getNullableInteger("amount", 1); int meta = helper.getNullableInteger("meta", 0); return new ItemStack( GameData.getItemRegistry().containsKey(new ResourceLocation(name)) ? GameData.getItemRegistry().getObject(new ResourceLocation(name)) : null, amount, meta); }
@Override protected JSONObject doInBackground(String... params) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://jthcloudproject.elasticbeanstalk.com/api/v1/vacations"); List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); nameValuePair.add(new BasicNameValuePair("title", title)); nameValuePair.add(new BasicNameValuePair("description", Description)); nameValuePair.add(new BasicNameValuePair("place", place)); nameValuePair.add(new BasicNameValuePair("start", start)); nameValuePair.add(new BasicNameValuePair("end", end)); try { SharedPreferences myS = con.getSharedPreferences("token", Context.MODE_PRIVATE); String t = myS.getString("access_token", ""); httppost.addHeader("authorization", "bearer " + t); httppost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httppost); Statues1 = response.getEntity().toString(); statuscode = response.getStatusLine().getStatusCode(); return JsonHelper.parseJSONObjectResponse(response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
@Test public void shouldGenerateFromList() { deleteAndPopulateTables("users", "addresses"); LazyList<User> personList = User.findAll().orderBy("id").include(Address.class); String json = personList.toJson(false); JsonHelper.readTree(json); // validate }
@Test public void testRoundTrip2() throws Exception { System.out.println("testRoundTrip2()"); BasicDBList list = new BasicDBList(); list.add("hello"); list.add("cool"); BasicDBObject expected = new BasicDBObject().append("stuff", true).append("stuff4", list); String json = JsonHelper.toJson(expected); Assert.assertEquals("{\"stuff\":true,\"stuff4\":[\"hello\",\"cool\"]}", json); BasicDBObject actual = JsonHelper.toJavaMap(json); Assert.assertEquals(expected, actual); Assert.assertEquals(actual, expected); }
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer output = new OutputStreamWriter(resp.getOutputStream(), "utf-8"); Reader input = new InputStreamReader(req.getInputStream(), "utf-8"); resp.setContentType("application/json; charset=utf-8"); try { String path = req.getPathInfo(); String search = req.getParameter("search"); if (path.startsWith("/customers")) { String id = path.length() >= 11 ? URLDecoder.decode(path.substring("/customers/".length()), "utf-8") : ""; if (!id.isEmpty() && "GET".equals(req.getMethod())) { StoredCustomer customer = getXmlStore().findCustomerById(id); if (customer != null) { JsonHelper.instance().toJson(customer, output); } else { resp.setStatus(404); } } else if ("POST".equals(req.getMethod())) { Customer customer = JsonHelper.instance().fromJson(input); StoredCustomer stored = getXmlStore().addCustomer(customer); JsonHelper.instance().toJson(stored, output); } else if (!id.isEmpty() && "PUT".equals(req.getMethod())) { Customer customer = JsonHelper.instance().fromJson(input); if (!getXmlStore().updateCustomerById(id, customer)) { resp.setStatus(404); } else { JsonHelper.instance().toJson(customer, output); } } else if (!id.isEmpty() && "DELETE".equals(req.getMethod())) { if (!getXmlStore().deleteCustomerById(id)) resp.setStatus(404); } else if (search != null) { Collection<StoredCustomer> customers = getXmlStore().findCustomersByText(search); JsonHelper.instance().toJson(customers, output); } else { Collection<StoredCustomer> customers = getXmlStore().findAllCustomers(); JsonHelper.instance().toJson(customers, output); } } else if ("/types".equals(path)) { JsonHelper.instance().toJsonTypes(output); } else { resp.setStatus(404); } } catch (Throwable e) { resp.setStatus(500); error(output, "Exception: " + e); } output.flush(); }
@Test public void shouldInjectCustomContentIntoJson() { deleteAndPopulateTable("posts"); Post p = Post.findById(1); String json = p.toJson(true, "title"); Map map = JsonHelper.toMap(json); Map injected = (Map) map.get("injected"); a(injected.get("secret_name")).shouldBeEqual("Secret Name"); }
public void doBench(int TEST_TO, BasicDBObject expected) { { long start = System.currentTimeMillis(); for (int i = 0; i < TEST_TO; i++) { JsonHelper.toJson(expected); } long finish = System.currentTimeMillis(); System.out.println(String.format("time for %s toJson's: %sms", TEST_TO, (finish - start))); } { String deserializing = JsonHelper.toJson(expected); long start = System.currentTimeMillis(); for (int i = 0; i < TEST_TO; i++) { JsonHelper.toJavaMap(deserializing); } long finish = System.currentTimeMillis(); System.out.println(String.format("time for %s toJavaMap's: %sms", TEST_TO, (finish - start))); } }
@Test public void shouldIncludeOnlyProvidedAttributes() { deleteAndPopulateTables("users", "addresses"); User u = User.findById(1); String json = u.toJson(true, "email", "last_name"); JsonHelper.readTree(json); // validate the(json) .shouldBeEqual( "{\n" + " \"email\":\"[email protected]\",\n" + " \"last_name\":\"Monroe\"\n" + "}"); }
@Test public void shouldEscapeDoubleQuote() { Page p = new Page(); p.set("description", "bad \"/description\""); JsonNode node = JsonHelper.readTree(p.toJson(true)); a(node.get("description").toString()).shouldBeEqual("\"bad \\\"/description\\\"\""); // ensure no NPE: p = new Page(); p.set("description", null); p.toJson(true); }
@Test public void shouldGenerateSimpleJson() { deleteAndPopulateTable("people"); Person p = Person.findFirst("name = ? and last_name = ? ", "John", "Smith"); // test no indent String json = p.toJson(false, "name", "last_name", "dob"); Map map = JsonHelper.toMap(json); a(map.get("name")).shouldBeEqual("John"); a(map.get("last_name")).shouldBeEqual("Smith"); a(map.get("dob")).shouldBeEqual("1934-12-01"); }
@SuppressWarnings("unchecked") protected <T> T parseCallResult(Class<T> type, Object rawResponse) throws FacebookException { log.debug("Facebook response: " + rawResponse); Object out = JsonHelper.parseCallResult(rawResponse); if (type == JSONArray.class && out instanceof JSONObject) { JSONArray arr = new JSONArray(); JSONObject json = (JSONObject) out; if (json.length() > 0) { arr.put(json); } out = arr; } return (T) out; }
@Test public void testRoundTrip3() throws Exception { System.out.println("testRoundTrip3()"); BasicDBList list = new BasicDBList(); list.add(new BasicDBObject().append("first1", 1234.0).append("first2", "hello")); list.add(new BasicDBObject().append("first1", 2345.0).append("first2", "hello2")); BasicDBObject expected = new BasicDBObject().append("stuff", true).append("stuff4", list); String json = JsonHelper.toJson(expected); Assert.assertEquals( "{\"stuff\":true,\"stuff4\":[" + "{\"first1\":1234.0,\"first2\":\"hello\"}," + "{\"first1\":2345.0,\"first2\":\"hello2\"}" + "]" + "}", json); BasicDBObject actual = JsonHelper.toJavaMap(json); Assert.assertEquals(expected, actual); Assert.assertEquals(actual, expected); }
// TODO: make it private public void saveUserSelectionToJsonFile(Map<String, Object> newFullJsonMap) { try { fullJsonMap = newFullJsonMap; Object jsonString = JsonHelper.toJSON(newFullJsonMap); Crashlytics.log(Log.INFO, LOG_TAG, "Updating fullJson - " + jsonString.toString()); userSelectionMap = getUserFeedMapFromJsonMap(fullJsonMap); Crashlytics.log( Log.INFO, LOG_TAG, "Updated UserSelectionMap - " + userSelectionMap.toString()); writeToInternalStorage(jsonString.toString(), NEWS_CAT_FILE); } catch (JSONException e) { e.printStackTrace(); } }
@Test public void testRoundTrip4() throws Exception { System.out.println("testRoundTrip4()"); BasicDBObject expected = new BasicDBObject() .append("stuff", true) .append("stuff1", 1234.0) .append("thank", "you") .append("_id", new ObjectId("123412341234123412341234")); String json = JsonHelper.toJson(expected); Assert.assertEquals( "{\"stuff\":true," + "\"stuff1\":1234.0," + "\"thank\":\"you\"," + "\"_id\":\"123412341234123412341234\"}", json); BasicDBObject actual = JsonHelper.toJavaMap(json); Assert.assertEquals(expected, actual); Assert.assertEquals(actual, expected); }
/** * Get details for this tag * * @param tagData * @throws IOException * @throws JSONException */ public void fetchTag(final TagData tagData) throws IOException, JSONException { JSONObject result; if (!checkForToken()) return; if (tagData.getValue(TagData.REMOTE_ID) == 0) result = actFmInvoker.invoke("tag_show", "name", tagData.getValue(TagData.NAME), "token", token); else result = actFmInvoker.invoke( "tag_show", "id", tagData.getValue(TagData.REMOTE_ID), "token", token); JsonHelper.tagFromJson(result, tagData); Flags.set(Flags.SUPPRESS_SYNC); tagDataService.save(tagData); }
@Test public void shouldReturnSecondsInDateTime() throws ParseException { Person p = new Person(); p.set("name", "john", "last_name", "doe").saveIt(); p.refresh(); String json = p.toJson(true); System.out.println(json); @SuppressWarnings("unchecked") Map<String, String> map = JsonHelper.toMap(json); Date d = new ISO8601DateFormat().parse(map.get("created_at")); // difference between date in Json and in original model instance should be less than 1000 // milliseconds a(Math.abs(d.getTime() - p.getTimestamp("created_at").getTime()) < 1000L).shouldBeTrue(); }
@Test public void shouldIncludeUglyChildren() { deleteAndPopulateTables("users", "addresses"); List<User> personList = User.findAll().orderBy("id").include(Address.class); User u = personList.get(0); String json = u.toJson(false); Map m = JsonHelper.toMap(json); a(m.get("first_name")).shouldBeEqual("Marilyn"); a(m.get("last_name")).shouldBeEqual("Monroe"); Map children = (Map) m.get("children"); List<Map> addresses = (List<Map>) children.get("addresses"); the(addresses.size()).shouldBeEqual(3); // at this point, no need to verify, since the order of addresses is not guaranteed.. or is it?? }
@Test @SuppressWarnings("unchecked") public void shouldIncludeParent() { deleteAndPopulateTables("libraries", "books", "readers"); List<Book> books = Book.findAll() .orderBy(Book.getMetaModel().getIdName()) .include(Reader.class, Library.class); Map book = JsonHelper.toMap(books.get(0).toJson(true)); Map parents = (Map) book.get("parents"); the(parents.size()).shouldBeEqual(1); List<Map> libraries = (List<Map>) parents.get("libraries"); the(libraries.size()).shouldBeEqual(1); Map library = libraries.get(0); a(library.get("address")).shouldBeEqual("124 Pine Street"); }
@Test @SuppressWarnings("unchecked") public void shouldGenerateJsonForPolymorphicChildren() { deleteAndPopulateTables("articles", "comments", "tags"); Article a = Article.findFirst("title = ?", "ActiveJDBC polymorphic associations"); a.add(Comment.create("author", "igor", "content", "this is just a test comment text")); a.add(Tag.create("content", "orm")); LazyList<Article> articles = Article.where("title = ?", "ActiveJDBC polymorphic associations") .include(Tag.class, Comment.class); Map[] maps = JsonHelper.toMaps(articles.toJson(true)); the(maps.length).shouldBeEqual(1); Map article = maps[0]; List<Map> comments = (List<Map>) ((Map) article.get("children")).get("comments"); List<Map> tags = (List<Map>) ((Map) article.get("children")).get("tags"); the(comments.size()).shouldBeEqual(1); the(comments.get(0).get("content")).shouldBeEqual("this is just a test comment text"); the(tags.size()).shouldBeEqual(1); the(tags.get(0).get("content")).shouldBeEqual("orm"); }
@Override public String toJson() { return JsonHelper.toJson(this); }
public WebsocketTransport(Messages.JoinWebsocket join) { this.out = join.out; this.in = join.in; this.context = join.context; final ActorRef self = getContext().self(); in.onClose( () -> { signalJActor.tell(new Messages.Quit(context.connectionId), self); self.tell(PoisonPill.getInstance(), self); }); in.onMessage( json -> { Logger.debug("Message from user: "******" : " + json); signalJActor.tell(new Messages.Execute(context, json), self); }); context() .setReceiveTimeout( Duration.create( SignalJPlugin.getConfiguration().getKeepAliveTimeout() / 2, TimeUnit.SECONDS)); receive( ReceiveBuilder.match( Messages.JoinWebsocket.class, r -> out.write(JsonHelper.writeConnect(prefix))) .match( Messages.MethodReturn.class, methodReturn -> { out.write(JsonHelper.writeMethodReturn(methodReturn)); sendAck(methodReturn); }) .match( Messages.ClientFunctionCall.class, clientFunctionCall -> { out.write(JsonHelper.writeClientFunctionCall(clientFunctionCall, prefix)); sendAck(clientFunctionCall); }) .match( Messages.ClientCallEnd.class, clientCallEnd -> { out.write(JsonHelper.writeConfirm(clientCallEnd.context)); sendAck(clientCallEnd); }) .match(ReceiveTimeout.class, r -> out.write(JsonHelper.writeHeartbeat())) .match( Messages.ReconnectWebsocket.class, r -> Logger.debug("Reconnect Websocket " + r.context.connectionId)) .match( Messages.StateChange.class, state -> { out.write(JsonHelper.writeState(state)); sendAck(state); }) .match( Messages.Error.class, error -> { out.write(JsonHelper.writeError(error)); sendAck(error); }) .build()); }
/** Synchronize with server when data changes */ public void pushTaskOnSave(Task task, ContentValues values) { long remoteId; if (task.containsValue(Task.REMOTE_ID)) remoteId = task.getValue(Task.REMOTE_ID); else { Task taskForRemote = taskService.fetchById(task.getId(), Task.REMOTE_ID); if (taskForRemote == null) return; remoteId = taskForRemote.getValue(Task.REMOTE_ID); } boolean newlyCreated = remoteId == 0; ArrayList<Object> params = new ArrayList<Object>(); if (values.containsKey(Task.TITLE.name)) { params.add("title"); params.add(task.getValue(Task.TITLE)); } if (values.containsKey(Task.DUE_DATE.name)) { params.add("due"); params.add(task.getValue(Task.DUE_DATE) / 1000L); params.add("has_due_time"); params.add(task.hasDueTime() ? 1 : 0); } if (values.containsKey(Task.NOTES.name)) { params.add("notes"); params.add(task.getValue(Task.NOTES)); } if (values.containsKey(Task.DELETION_DATE.name)) { params.add("deleted_at"); params.add(task.getValue(Task.DELETION_DATE) / 1000L); } if (values.containsKey(Task.COMPLETION_DATE.name)) { params.add("completed"); params.add(task.getValue(Task.COMPLETION_DATE) / 1000L); } if (values.containsKey(Task.IMPORTANCE.name)) { params.add("importance"); params.add(task.getValue(Task.IMPORTANCE)); } if (values.containsKey(Task.RECURRENCE.name)) { params.add("repeat"); params.add(task.getValue(Task.RECURRENCE)); } if (values.containsKey(Task.USER_ID.name) && task.getValue(Task.USER_ID) >= 0) { params.add("user_id"); if (task.getValue(Task.USER_ID) == 0) params.add(ActFmPreferenceService.userId()); else params.add(task.getValue(Task.USER_ID)); } if (Flags.checkAndClear(Flags.TAGS_CHANGED) || newlyCreated) { TodorooCursor<Metadata> cursor = TagService.getInstance().getTags(task.getId()); try { if (cursor.getCount() == 0) { params.add("tags"); params.add(""); } else { Metadata metadata = new Metadata(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { metadata.readFromCursor(cursor); if (metadata.containsNonNullValue(TagService.REMOTE_ID) && metadata.getValue(TagService.REMOTE_ID) > 0) { params.add("tag_ids[]"); params.add(metadata.getValue(TagService.REMOTE_ID)); } else { params.add("tags[]"); params.add(metadata.getValue(TagService.TAG)); } } } } finally { cursor.close(); } } if (params.size() == 0 || !checkForToken()) return; System.err.println("PUSHN ON SAVE: " + task.getMergedValues()); System.err.println("SETVALUES: " + values); if (!newlyCreated) { params.add("id"); params.add(remoteId); } else if (!params.contains(Task.TITLE.name)) return; try { params.add("token"); params.add(token); JSONObject result = actFmInvoker.invoke("task_save", params.toArray(new Object[params.size()])); ArrayList<Metadata> metadata = new ArrayList<Metadata>(); JsonHelper.taskFromJson(result, task, metadata); task.setValue(Task.MODIFICATION_DATE, DateUtilities.now()); task.setValue(Task.LAST_SYNC, DateUtilities.now()); Flags.set(Flags.SUPPRESS_SYNC); taskDao.saveExisting(task); } catch (JSONException e) { handleException("task-save-json", e); } catch (IOException e) { handleException("task-save-io", e); } }
private void error(Writer output, String error) { JsonHelper.instance().errorJson(error, output); }
@Test public void testGetString() { LoginForm form = JsonHelper.get(dummyJson, LoginForm.class); assertEquals("developer", form.getLogin()); assertEquals("newbie", form.getPassword()); }