List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:com.samsung.appengine.web.server.RemindMeServlet.java
@JsonRpcMethod(method = RemindMeProtocol.AlertsList.METHOD, requires_login = true) public JSONObject notesList(final CallContext context) throws JSONException, JsonRpcException { UserInfo userInfo = getCurrentUserInfo(context); // Note: this would be inefficient for large note collections Query query = context.getPersistenceManager().newQuery(Alert.class); query.setFilter("ownerKey == ownerKeyParam && pendingDelete == false"); query.declareParameters(Key.class.getName() + " ownerKeyParam"); @SuppressWarnings("unchecked") List<Alert> alerts = (List<Alert>) query.execute(userInfo.getKey()); JSONObject responseJson = new JSONObject(); try {//from w ww .ja v a2 s .com JSONArray notesJson = new JSONArray(); for (Alert note : alerts) { notesJson.put(note.toJSON()); } responseJson.put(RemindMeProtocol.AlertsList.RET_NOTES, notesJson); } catch (JSONException e) { throw new JsonRpcException(500, "Error serializing response.", e); } return responseJson; }
From source file:com.samsung.appengine.web.server.RemindMeServlet.java
@JsonRpcMethod(method = RemindMeProtocol.AlertsSync.METHOD, requires_login = true) public JSONObject notesSync(final CallContext context) throws JSONException, JsonRpcException { // This method should return a list of updated notes since a current // date, optionally reconciling/merging a set of a local notes. String clientDeviceId = null; UserInfo userInfo = getCurrentUserInfo(context); Date sinceDate;/*from w w w .ja v a 2s. co m*/ try { clientDeviceId = context.getParams().optString(RemindMeProtocol.ARG_CLIENT_DEVICE_ID); sinceDate = Util .parseDateISO8601(context.getParams().getString(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE)); } catch (ParseException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } JSONObject responseJson = new JSONObject(); JSONArray notesJson = new JSONArray(); Transaction tx = context.getPersistenceManager().currentTransaction(); Date newSinceDate = new Date(); try { tx.begin(); List<Alert> localAlerts = new ArrayList<Alert>(); if (context.getParams().has(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS)) { JSONArray localChangesJson = context.getParams() .getJSONArray(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS); for (int i = 0; i < localChangesJson.length(); i++) { try { JSONObject noteJson = localChangesJson.getJSONObject(i); if (noteJson.has("id")) { Key existingAlertKey = Alert.makeKey(userInfo.getId(), noteJson.get("id").toString()); try { Alert existingAlert = (Alert) context.getPersistenceManager() .getObjectById(Alert.class, existingAlertKey); if (!existingAlert.getOwnerId().equals(userInfo.getId())) { // User doesn't have permission to edit this note. Instead of // throwing an error, just re-create it on the server side. //throw new JsonRpcException(403, // "You do not have permission to modify this note."); noteJson.remove("id"); } } catch (JDOObjectNotFoundException e) { // Alert doesn't exist, instead of throwing an error, // just re-create the note on the server side (unassign its ID). //throw new JsonRpcException(404, "Alert with ID " // + noteJson.get("id").toString() + " does not exist."); noteJson.remove("id"); } } noteJson.put("owner_id", userInfo.getId()); Alert localAlert = new Alert(noteJson); localAlerts.add(localAlert); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid local note content.", e); } } } // Query server-side note changes. Query query = context.getPersistenceManager().newQuery(Alert.class); query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate"); query.setOrdering("modifiedDate desc"); query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate"); @SuppressWarnings("unchecked") List<Alert> alerts = (List<Alert>) query.execute(userInfo.getKey(), sinceDate); // Now merge the lists and conflicting objects. Reconciler<Alert> reconciler = new Reconciler<Alert>() { @Override public Alert reconcile(Alert o1, Alert o2) { boolean pick1 = o1.getModifiedDate().after(o2.getModifiedDate()); // Make sure only the chosen version of the note is persisted context.getPersistenceManager().makeTransient(pick1 ? o2 : o1); return pick1 ? o1 : o2; } }; Collection<Alert> reconciledAlerts = reconciler.reconcileLists(alerts, localAlerts); for (Alert alert : reconciledAlerts) { // Save the note. context.getPersistenceManager().makePersistent(alert); // Put it in the response output. notesJson.put(alert.toJSON()); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } } enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId); responseJson.put(RemindMeProtocol.AlertsSync.RET_ALERTS, notesJson); responseJson.put(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate)); return responseJson; }
From source file:com.snappy.couchdb.CouchDB.java
/** * Method used for updating user attributes * /*w ww. ja v a 2 s . c om*/ * If you add some new attributes to user object you must also add code to * add that data to userJson * * @param user * @return user object * @throws SpikaException * @throws JSONException * @throws ClientProtocolException * @throws IOException * @throws IllegalStateException * @throws SpikaForbiddenException */ public static boolean updateUser(User user) throws JSONException, ClientProtocolException, IllegalStateException, IOException, SpikaException, SpikaForbiddenException { JSONObject userJson = new JSONObject(); List<String> contactIds = new ArrayList<String>(); List<String> groupIds = new ArrayList<String>(); JSONObject json = null; /* General user info */ userJson.put(Const._ID, user.getId()); userJson.put(Const._REV, user.getRev()); userJson.put(Const.EMAIL, user.getEmail()); userJson.put(Const.NAME, user.getName()); userJson.put(Const.TYPE, Const.USER); userJson.put(Const.PASSWORD, FileManagement.md5(SpikaApp.getPreferences().getUserPassword())); userJson.put(Const.LAST_LOGIN, user.getLastLogin()); userJson.put(Const.ABOUT, user.getAbout()); userJson.put(Const.BIRTHDAY, user.getBirthday()); userJson.put(Const.GENDER, user.getGender()); userJson.put(Const.TOKEN, SpikaApp.getPreferences().getUserToken()); userJson.put(Const.TOKEN_TIMESTAMP, user.getTokenTimestamp()); userJson.put(Const.ANDROID_PUSH_TOKEN, SpikaApp.getPreferences().getUserPushToken()); userJson.put(Const.ONLINE_STATUS, user.getOnlineStatus()); userJson.put(Const.AVATAR_FILE_ID, user.getAvatarFileId()); userJson.put(Const.MAX_CONTACT_COUNT, user.getMaxContactCount()); userJson.put(Const.AVATAR_THUMB_FILE_ID, user.getAvatarThumbFileId()); /* Set users favorite contacts */ JSONArray contactsArray = new JSONArray(); contactIds = user.getContactIds(); if (!contactIds.isEmpty()) { for (String id : contactIds) { contactsArray.put(id); } } if (contactsArray.length() > 0) { userJson.put(Const.CONTACTS, contactsArray); } /* Set users favorite groups */ JSONArray groupsArray = new JSONArray(); groupIds = user.getGroupIds(); if (!groupIds.isEmpty()) { for (String id : groupIds) { groupsArray.put(id); } } if (groupsArray.length() > 0) { userJson.put(Const.FAVORITE_GROUPS, groupsArray); } json = ConnectionHandler.postJsonObject(Const.UPDATE_USER, userJson, user.getId(), user.getToken()); return CouchDBHelper.updateUser(json, contactIds, groupIds); }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private void update(JSONObject g) { for (String t : new String[] { "new", "rev", "lrn", "time" }) { String key = t + "Today"; try {//ww w .j a v a2 s. c om if (g.getJSONArray(key).getInt(0) != mToday) { JSONArray ja = new JSONArray(); ja.put(mToday); ja.put(0); g.put(key, ja); } } catch (JSONException e) { throw new RuntimeException(e); } } }
From source file:com.trk.aboutme.facebook.InsightsLogger.java
private static String buildJSONForEvent(String eventName, double valueToSum, Bundle parameters) { String result;/* w w w . ja v a2 s . com*/ try { // Build custom event payload JSONObject eventObject = new JSONObject(); eventObject.put("_eventName", eventName); if (valueToSum != 1.0) { eventObject.put("_valueToSum", valueToSum); } if (parameters != null) { Set<String> keys = parameters.keySet(); for (String key : keys) { Object value = parameters.get(key); if (!(value instanceof String) && !(value instanceof Number)) { notifyDeveloperError( String.format("Parameter '%s' must be a string or a numeric type.", key)); } eventObject.put(key, value); } } JSONArray eventArray = new JSONArray(); eventArray.put(eventObject); result = eventArray.toString(); } catch (JSONException exception) { notifyDeveloperError(exception.toString()); result = null; } return result; }
From source file:org.eclipse.orion.internal.server.servlets.file.DirectoryHandlerV1.java
private void encodeChildren(IFileStore dir, URI location, JSONObject result, int depth) throws CoreException { if (depth <= 0) return;/*from w ww . j a v a 2 s . c om*/ JSONArray children = new JSONArray(); //more efficient to ask for child information in bulk for certain file systems IFileInfo[] childInfos = dir.childInfos(EFS.NONE, null); for (IFileInfo childInfo : childInfos) { IFileStore childStore = dir.getChild(childInfo.getName()); String name = childInfo.getName(); if (childInfo.isDirectory()) name += "/"; //$NON-NLS-1$ URI childLocation = URIUtil.append(location, name); JSONObject childResult = ServletFileStoreHandler.toJSON(childStore, childInfo, childLocation); if (childInfo.isDirectory()) encodeChildren(childStore, childLocation, childResult, depth - 1); children.put(childResult); } try { result.put(ProtocolConstants.KEY_CHILDREN, children); } catch (JSONException e) { // cannot happen throw new RuntimeException(e); } }
From source file:org.eclipse.orion.server.cf.objects.OrgWithSpaces.java
@PropertyDescription(name = CFProtocolConstants.KEY_SPACES) private JSONArray getSpacesJSONArray() { try {//from www . ja v a 2s .c o m JSONArray spacesJSONArray = new JSONArray(); for (Iterator<Space> iterator = spaces.iterator(); iterator.hasNext();) { spacesJSONArray.put(iterator.next().toJSON()); } return spacesJSONArray; } catch (JSONException e) { return null; } }
From source file:controlador.Peticiones.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .jav a2s . c om * * @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("text/html;charset=UTF-8"); String target, op, action, view; target = request.getParameter("target"); op = request.getParameter("op"); if (target.equals("login")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String login = request.getParameter("login"); String pass = request.getParameter("password"); ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='" + Auxiliar.encriptarPass(pass) + "'"); JSONObject objetoJSON = new JSONObject(); response.setContentType("application/json; charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { if (r != null && r.next()) { objetoJSON.put("r", "1"); out.print(objetoJSON); } else { objetoJSON.put("r", "0"); out.print(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } } else { if (target.equals("pedido")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String s = request.getParameter("datos"); JSONTokener token = new JSONTokener(s); JSONArray ar = null; ArrayList<Producto> productos = new ArrayList(); try { ar = new JSONArray(token); for (int i = 0; i < ar.length(); i++) { agregarProducto(ar.getJSONObject(i).getInt("idMesa"), ar.getJSONObject(i).getInt("idProducto")); ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = " + ar.getJSONObject(i).getInt("idProducto")); rs.next(); String nombre = rs.getString("nombreProducto"); Producto pr = new Producto(nombre); if (productos.contains(pr)) { int pos = productos.indexOf(pr); productos.get(pos).sumaCantidad(); } else { productos.add(new Producto(nombre)); } } ResultSet nombreMesa = bd.ejecutarSelect( "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa=" + ar.getJSONObject(0).getInt("idMesa")); nombreMesa.next(); String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona"); Comanda comanda = new Comanda(productos, nombre); System.out.println("Ticket: \n" + comanda.contenidoComanda); Auxiliar.imprimir(comanda.contenidoComanda); } catch (JSONException ex) { System.out.println("Error JSON " + ex.toString()); } catch (SQLException ex) { System.out.println("Error SQL " + ex.toString()); } // Crear un el objeto para enviar a comanda para imprimir, implementar response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); try { obj.put("r", "recibido"); } catch (JSONException ex) { } out.print(obj); out.flush(); } else { if (target.equals("mesas")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("familias")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { ; } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("productos")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } } } } } }
From source file:com.jskaleel.xml.JSONObject.java
/** * Produce a JSONArray containing the names of the elements of this * JSONObject./* w w w .j a va 2s . c o m*/ * * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator<String> keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; }
From source file:com.jskaleel.xml.JSONObject.java
/** * Produce a JSONArray containing the values of the members of this * JSONObject.// w w w. j ava 2s.c om * * @param names * A JSONArray containing a list of key strings. This determines * the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException * If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; }