Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

In this page you can find the example usage for org.json JSONArray put.

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:org.schedulesdirect.grabber.ScheduleTask.java

protected Map<String, Collection<String>> getStaleStationIds() {
    Map<String, Collection<String>> staleIds = new HashMap<>();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S,
            clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl());
    JSONArray data = new JSONArray();
    for (int i = 0; i < this.req.length(); ++i) {
        JSONObject o = new JSONObject();
        o.put("stationID", this.req.getString(i));
        data.put(o);
    }//from   w  ww. ja  va2 s .co  m
    try {
        JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(result)) {
            Iterator<?> idItr = result.keys();
            while (idItr.hasNext()) {
                String stationId = idItr.next().toString();
                boolean schedFileExists = Files
                        .exists(vfs.getPath("schedules", String.format("%s.txt", stationId)));
                Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId));
                JSONObject cachedMd5s = Files.exists(cachedMd5File)
                        ? Config.get().getObjectMapper()
                                .readValue(new String(Files.readAllBytes(cachedMd5File),
                                        ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        : new JSONObject();
                JSONObject stationInfo = result.getJSONObject(stationId);
                Iterator<?> dateItr = stationInfo.keys();
                while (dateItr.hasNext()) {
                    String date = dateItr.next().toString();
                    JSONObject dateInfo = stationInfo.getJSONObject(date);
                    if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) {
                        Collection<String> dates = staleIds.get(stationId);
                        if (dates == null) {
                            dates = new ArrayList<String>();
                            staleIds.put(stationId, dates);
                        }
                        dates.add(date);
                        if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date));
                    } else if (LOG.isDebugEnabled())
                        LOG.debug(String.format("Station %s is unchanged on the server; skipping it!",
                                stationId));
                }
                Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                        StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.CREATE);
            }
        }
    } catch (Throwable t) {
        Grabber.failedTask = true;
        LOG.error("Error processing cache; returning partial stale list!", t);
    }
    return staleIds;
}

From source file:org.uiautomation.ios.UIAModels.predicate.ComposedCriteria.java

public JSONObject stringify() {
    JSONObject res = new JSONObject();
    JSONArray or = new JSONArray();
    for (Criteria c : criterias) {
        or.put(c.stringify());
    }//  www.  ja  v  a  2  s.c  o  m
    try {
        res.put(type.toString(), or);
    } catch (JSONException e) {
        throw new WebDriverException(e);
    }

    return res;
}

From source file:com.izv.controlador.ControladorAndroid.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w.j a v  a2  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("text/html;charset=UTF-8");
    boolean forward = false;
    String target, op, action, view;
    ControlDB bd;

    target = request.getParameter("target");
    op = request.getParameter("op");
    action = request.getParameter("action");
    if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("op")) {
        response.setContentType("text/html;charset=UTF-8");
        format = new SimpleDateFormat();
        format.applyPattern("yyyy-dd-MM");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        format.format(date);
        Inmueble inmueble = new Inmueble();
        inmueble.setLocalidad(request.getParameter("localidad"));
        inmueble.setDireccion(request.getParameter("direccion"));
        inmueble.setTipo(request.getParameter("tipo"));
        inmueble.setUsuario(request.getParameter("usuario"));
        inmueble.setPrecio(request.getParameter("precio"));
        inmueble.setFechaalta(date);
        ModeloInmueble.insert(inmueble);
        Inmueble inm = ModeloInmueble.get(inmueble.getId() + "");
        try (PrintWriter out = response.getWriter()) {
            out.println(inm.getId() + "");
        }
    } else {
        if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("op")) {
            forward = false;
            boolean error = false;
            String id = request.getParameter("id");
            response.setContentType("text/html;charset=UTF-8");
            Calendar calendario = new GregorianCalendar();
            Date date = calendario.getTime();
            SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSSSS");
            String fecha = formatoFecha.format(date);
            String titulo = "inmueble_" + id + "_" + fecha;
            Part archivoPost = request.getPart("archivo");
            String carpeta = getServletContext().getRealPath("/") + "fotos/";
            InputStream input = archivoPost.getInputStream();
            try {
                OutputStream out = new FileOutputStream(carpeta + titulo + ".jpg");
                byte[] b = new byte[2048];
                int length;
                while ((length = input.read(b)) != -1) {
                    out.write(b, 0, length);
                }
            } catch (Exception e) {
                error = true;
            } finally {
                input.close();
            }
            Fotos fot = new Fotos();
            fot.setIdinmueble(Integer.valueOf(id));
            fot.setNombre(titulo + ".jpg");
            ModeloFoto.insert(fot);
            try (PrintWriter out = response.getWriter()) {
                if (error) {
                    out.println("error");
                } else {
                    out.println("foto subida"); // respuesta json chapucera
                }
            }
        } else {
            if (target.equals("bar")) {
                try {
                    bd = new ControlDB();
                    bd.cargarDriver();
                    bd.conectar();
                    response.setContentType("application/json");
                    /*
                     int r = bd.ejecutarDelete("delete from pedidos where idPedido=52");
                     System.out.println(r);
                     */
                    //                        String fechaHora = getFecha();
                    //                        String consulta = "insert into pedidos values(0, '" + fechaHora + "', 0, 0, null, 'admin ', 6, 1)";
                    //                        bd.ejecutarInsert(consulta);
                    ResultSet r = bd.ejecutarSelect("Select * from pedidos");
                    JSONArray array = new JSONArray();
                    ResultSetMetaData rsMetaData = r.getMetaData();
                    int columns = rsMetaData.getColumnCount();
                    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");
                            //                                System.out.println(r.getString(1) + " " + r.getString(2) + " " + r.getString(3)
                            //                                        + " " + r.getString(4));
                            array.put(objetoJSON);
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    PrintWriter out = response.getWriter();
                    out.print(array);
                    out.flush();
                    //                        obj.put("nombre", "Angel");
                    //                        obj.put("password", "1234");
                    //                        System.out.println("JSON " + obj.toString());
                    //                        System.out.println(obj.getString("nombre") + " " + obj.getString("password"));

                } catch (JSONException ex) {
                    Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    }
}

From source file:de.elepferd.web.pushnotifier.server.PushNotifierServlet.java

@JsonRpcMethod(method = PushNotifierProtocol.NotesList.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(Note.class);
    query.setFilter("ownerKey == ownerKeyParam && pendingDelete == false");
    query.declareParameters(Key.class.getName() + " ownerKeyParam");
    @SuppressWarnings("unchecked")
    List<Note> notes = (List<Note>) query.execute(userInfo.getKey());

    JSONObject responseJson = new JSONObject();
    try {/*from   w w w  .  j a  va 2  s.c  om*/
        JSONArray notesJson = new JSONArray();
        for (Note note : notes) {
            notesJson.put(note.toJSON());
        }

        responseJson.put(PushNotifierProtocol.NotesList.RET_NOTES, notesJson);
    } catch (JSONException e) {
        throw new JsonRpcException(500, "Error serializing response.", e);
    }

    return responseJson;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

/**
 * Retrieve the mini summary information e.g. summary and number and append
 * the csid and recordType to it/*ww  w. jav a 2 s  .co  m*/
 *
 * @param {Storage} storage Type of storage (e.g. AuthorizationStorage,
 * RecordStorage,...)
 * @param {String} type The type of record requested (e.g. permission)
 * @param {String} csid The csid of the record
 * @return {JSONObject} The JSON string containing the mini record
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 * @throws JSONException
 */
private JSONObject generateMiniRecord(Storage storage, String type, String csid) throws JSONException {
    String postfix = "list";
    if (this.mode == MODE_SEARCH) {
        postfix = "search";
    }
    JSONObject restrictions = new JSONObject();
    JSONObject out = new JSONObject();
    try {
        if (csid == null || csid.equals("")) {
            return out;
        }
        out = storage.retrieveJSON(type + "/" + csid + "/view/" + postfix, restrictions);
        out.put("csid", csid);
        String recordtype = null;
        if (!r.isType("searchall")) {
            recordtype = type_to_url.get(type);
        } else {
            JSONObject summarylist = out.getJSONObject("summarylist");
            String uri = summarylist.getString("uri");
            if (uri != null && uri.startsWith("/")) {
                uri = uri.substring(1);
            }
            String[] parts = uri.split("/");
            String recordurl = parts[0];
            Record itemr = r.getSpec().getRecordByServicesUrl(recordurl);
            if (itemr == null) {
                String docType = summarylist.getString("docType");
                itemr = r.getSpec().getRecordByServicesDocType(docType);
            }
            if (itemr == null) {
                recordtype = UNKNOWN_RECORD_TYPE;
                log.warn("Could not get record type for record with services URI " + uri);
            } else {
                recordtype = type_to_url.get(itemr.getID());
                String refName = null;
                if (summarylist.has("refName")) {
                    refName = summarylist.getString("refName");
                }
                // For an authority item (i.e. an item in a vocabulary),
                // include the name of its parent vocabulary in a
                // "namespace" value within the mini summary.
                RefName.AuthorityItem item = null;
                if (refName != null) {
                    item = RefName.AuthorityItem.parse(refName);
                }
                // If this refName could be successfully parsed (above) as an
                // authority item refName, then include the "namespace" value.
                if (item != null) {
                    String namespace = item.getParentShortIdentifier();
                    if (namespace != null) {
                        out.put("namespace", namespace);
                    } else {
                        log.warn("Could not get vocabulary namespace for record with services URI " + uri);
                    }
                }
            }
        }
        out.put("recordtype", recordtype);
        // CSPACE-2894
        if (this.r.getID().equals("permission")) {
            String summary = out.getString("summary");
            String name = Generic.ResourceNameUI(this.r.getSpec(), summary);
            if (name.contains(WORKFLOW_SUB_RESOURCE)) {
                return null;
            }
            out.put("summary", name);
            out.put("display", Generic.getPermissionView(this.r.getSpec(), summary));
        }
    } catch (ExistException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    } catch (UnimplementedException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    } catch (UnderlyingStorageException e) {
        out.put("csid", csid);
        out.put("isError", true);
        JSONObject msg = new JSONObject();
        msg.put("severity", "error");
        msg.put("message", "Exist Exception:" + e.getMessage());
        JSONArray msgs = new JSONArray();
        msgs.put(msg);
        out.put("messages", msgs);
    }
    return out;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

/**
 * Creates a list of results containing:summary, number, recordType, csid
 *
 * @param {Storage} storage The type of storage (e.g.
 * AuthorizationStorage,RecordStorage,...)
 * @param {String} base The type of record (e.g. permission)
 * @param {String[]} paths The list of csids from the records that were
 * requested/*from  www. ja  v a2  s.  c o m*/
 * @param {String} key The surrounding key for the results (e.g.
 * {"key":{...}})
 * @return {JSONObject} The JSONObject that is sent back to the UI Layer
 * @throws JSONException
 * @throws ExistException
 * @throws UnimplementedException
 * @throws UnderlyingStorageException
 */
private JSONObject pathsToJSON(Storage storage, String base, String[] paths, String key, JSONObject pagination)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();
    JSONArray members = new JSONArray();
    for (String p : paths) {
        JSONObject temp = generateEntry(storage, base, p);
        if (temp != null) {
            members.put(temp);
        }
    }
    out.put(key, members);

    if (pagination != null) {
        out.put("pagination", pagination);
    }
    return out;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

private JSONObject showReports(JSONObject data, String type, String key) throws JSONException {
    JSONObject results = new JSONObject();
    JSONArray list = new JSONArray();
    JSONArray names = new JSONArray();

    if (data.has(key)) {
        JSONArray ja = data.getJSONArray(key);

        for (int j = 0; j < ja.length(); j++) {
            list.put(ja.getJSONObject(j).getString("csid"));
            names.put(ja.getJSONObject(j).getString("number"));
        }//from   w w w  . j  av  a 2s.  c  o  m
        results.put("reportlist", list);
        results.put("reportnames", names);
    }
    return results;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

private JSONObject showBatches(JSONObject data, String type, String key) throws JSONException {
    JSONObject results = new JSONObject();
    JSONArray list = new JSONArray();
    JSONArray names = new JSONArray();
    JSONArray newFocuses = new JSONArray();

    if (data.has(key)) {
        JSONArray ja = data.getJSONArray(key);

        for (int j = 0; j < ja.length(); j++) {
            list.put(ja.getJSONObject(j).getString("csid"));
            names.put(ja.getJSONObject(j).getString("number"));

            JSONObject summarylist = ja.getJSONObject(j).getJSONObject("summarylist");
            newFocuses.put(summarylist.getBoolean("createsNewFocus"));
        }//from w  w  w  .  ja v  a2s .co  m
        results.put("batchlist", list);
        results.put("batchnames", names);
        results.put("batchnewfocuses", newFocuses);
    }
    return results;
}

From source file:com.leanengine.JsonEncode.java

static JSONObject entityListToJson(List<LeanEntity> entityList) throws LeanException {
    JSONObject rootNode = new JSONObject();
    JSONArray resultsArray = new JSONArray();

    for (LeanEntity entity : entityList) {
        resultsArray.put(entityToJson(entity));
    }/*w  w w . j a v  a  2  s  .  c o  m*/
    try {
        rootNode.put("result", resultsArray);
    } catch (JSONException e) {
        // this should not happen under normal circumstances
        throw new IllegalStateException(e);
    }
    return rootNode;
}

From source file:com.leanengine.JsonEncode.java

private static void addTypedValueToArray(JSONArray node, Object value) throws JSONException {
    if (value instanceof Date) {
        node.put(getDateNode((Date) value));
    } else if (value instanceof LeanText) {
        node.put(getLeanTextNode((LeanText) value));
    } else {/*from  www .ja va  2 s  .co m*/
        node.put(value);
    }
}