Example usage for org.json.simple JSONArray JSONArray

List of usage examples for org.json.simple JSONArray JSONArray

Introduction

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

Prototype

JSONArray

Source Link

Usage

From source file:com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANRecordReaderTest.java

/**
 * Sets up tests by creating a unique instance of the tested class, and by defining the behaviour of the mocked
 * classes.//w w  w  .jav a 2  s  .c o m
 *  
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
    // set up the instance of the tested class
    recordReader = new CKANRecordReader(backend, inputSplit, taskAttemptContext);

    // set up other instances
    JSONArray records = new JSONArray();
    records.add((new JSONObject()));

    // set up the behaviour of the mocked classes
    when(backend.getRecords(resId, firstRecordIndex, length)).thenReturn(records);
    when(inputSplit.getFirstRecordIndex()).thenReturn(firstRecordIndex);
    when(inputSplit.getLength()).thenReturn(length);
    when(inputSplit.getResId()).thenReturn(resId);
}

From source file:es.alrocar.jpe.writer.handler.MiniJPEWriterHandler.java

/**
 * {@inheritDoc}//from   w w w  . ja  v  a  2  s  .co  m
 */
public Object startFeatureCollection() {
    featureCount = 0;
    featureCollection = new org.json.JSONObject();

    features = new JSONArray();
    // featureCollection.put("features", new JSONArray());

    return featureCollection;
}

From source file:com.imagelake.android.earnings.Servlet_AdminEarnings.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {//from  w  ww. j a  v a2s.  c om

        String type = request.getParameter("type");
        String usid = request.getParameter("id");

        User us = new UserDAOImp().getUser(Integer.parseInt(usid));

        UserDAOImp udi = new UserDAOImp();

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date1 = sdf.format(d);

        SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss");
        String Time = sdf2.format(d);
        String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

        if (type.equals("new")) {
            ja = new JSONArray();
            System.out.println("type:" + type);
            ja = ppdi.getPayments(1);
            System.out.println(ja);
            response.setContentType("text/html");
            response.getWriter().write("json=" + ja.toJSONString());

        } else if (type.equals("sort")) {
            ja = new JSONArray();
            System.out.println("type:" + type);

            String uid = request.getParameter("uid");
            String date = request.getParameter("date");
            String conr = request.getParameter("conr");
            String newr = request.getParameter("newr");

            System.out.println("uid: " + uid);
            System.out.println("date: " + date);
            System.out.println("conrequest:" + conr);
            System.out.println("newrequest:" + newr);

            String dbDate[] = date.split("-");

            String sql = "SELECT * FROM payment_preferences WHERE ";

            if (uid != null && uid.trim() != "") {
                sql += "user_id='" + Integer.parseInt(uid) + "' ";
                if (date != null && date.trim() != "" || !conr.equals("false") || !newr.equals("false")) {
                    sql += "AND ";
                } else {
                    sql += "AND ";
                }
            }

            if (conr.equals("true")) {
                if (date != null && date.trim() != "") {
                    sql += "conf_date='" + dbDate[2] + "-" + dbDate[1] + "-" + dbDate[0] + "' AND state='2' ";
                    if (!newr.equals("false")) {
                        sql += "OR ";
                    }
                } else {
                    sql += "state='2' ";
                    if (!newr.equals("false")) {
                        sql += "OR ";
                    }

                }
            }
            if (newr.equals("true")) {
                if (date != null && date.trim() != "") {
                    sql += "date='" + dbDate[2] + "-" + dbDate[1] + "-" + dbDate[0] + "' AND state='1' ";

                } else {
                    sql += "state='1' ";
                }
            }
            if (conr.trim().equals("false") && newr.equals("false")) {
                if (date != null && date.trim() != "") {
                    sql += "conf_date='" + dbDate[2] + "-" + dbDate[1] + "-" + dbDate[0] + "' OR date='"
                            + dbDate[2] + "-" + dbDate[1] + "-" + dbDate[0] + "' ";
                } else {
                    sql += "state='1' ";
                }
            }
            System.out.println("sql: " + sql);
            try {
                PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);
                ResultSet rs = ps.executeQuery();

                int pages = 0;
                PaymentAccountDAOImp pad = new PaymentAccountDAOImp();

                while (rs.next()) {

                    pages++;

                    JSONObject jo = new JSONObject();
                    jo.put("id", rs.getString(1));
                    jo.put("userid", rs.getString(2));
                    jo.put("reqdate", rs.getString(3));
                    jo.put("acctype", pad.getPaymetAccountName(rs.getInt(5)));
                    jo.put("amount", rs.getDouble(7));
                    jo.put("state", rs.getInt(8));
                    jo.put("email", rs.getString(9));
                    jo.put("no", pages);
                    ja.add(jo);

                }
                System.out.println(ja.toJSONString());
                response.getWriter().write("json=" + ja.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("msg=Internal server error,Please try again later.");
            }

        } else if (type.equals("settle")) {
            String id = request.getParameter("idd");
            String staType = request.getParameter("state");
            String uid = request.getParameter("uid");
            String amount = request.getParameter("amount");

            double damo = Double.parseDouble(amount);
            System.out.println("amount:" + amount + " " + damo);

            if (id != null && !id.trim().equals("") && staType != null && !staType.trim().equals("")
                    && uid != null && !uid.trim().equals("") && amount != null && !amount.trim().equals("")) {
                boolean ok = ppdi.requestSettle(Integer.parseInt(id), Integer.parseInt(staType),
                        us.getUser_id(), "conf_date");
                if (ok) {

                    SellerIncomeDAOImp sid = new SellerIncomeDAOImp();
                    //old-income
                    SellerIncome lastSellerIncome = sid.getSellerIncome(Integer.parseInt(uid));
                    //new-income
                    double newIncome = lastSellerIncome.getTotal() - damo;
                    SellerIncome newSellerincome = new SellerIncome();
                    newSellerincome.setUser_id(Integer.parseInt(uid));
                    newSellerincome.setSell_inc_id(lastSellerIncome.getSell_inc_id());
                    newSellerincome.setTotal(newIncome);

                    boolean update = sid.updateSellerIncome(newSellerincome);
                    if (update) {
                        //                        boolean notiok = false;
                        //                        if (staType.equals("2")) {
                        //                            String noti = "Admin " + us.getUser_name() + " has confirmed your earning request";
                        //                            notiok = new NotificationDAOImp().addNotification(noti, date1, Time, Integer.parseInt(uid), 1, 4);
                        //                        } else if (staType.equals("3")) {
                        //                            String noti = "Admin " + us.getUser_name() + " has canceled your earning request";
                        //                            notiok = new NotificationDAOImp().addNotification(noti, date1, Time, Integer.parseInt(uid), 1, 3);
                        //                        }
                        //                        AdminNotification a = new AdminNotification();
                        //                        a.setUser_id(us.getUser_id());
                        //                        a.setDate(timeStamp);
                        //
                        //                        a.setShow(1);
                        //                        if (staType.equals("3")) {
                        //                            a.setType(2);
                        //                            String not = "Admin " + us.getUser_name() + " has canceled " + amount + " earning request.";
                        //                            a.setNotification(not);
                        //                        } else if (staType.equals("2")) {
                        //                            a.setType(4);
                        //                            String not = "Admin " + us.getUser_name() + " has confirmed " + amount + " earning requests.";
                        //                            a.setNotification(not);
                        //                        }
                        //
                        //                        int an = new AdminNotificationDAOImp().insertNotificaation(a);
                        //                        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);
                        //
                        //                        boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.notMeList(us.getUser_id()), an, 1);
                        //
                        //                        if (notiok && kl) {
                        //                            out.write("ok");
                        //                        } else {
                        //                            out.write("error");
                        //                        }
                        User u = udi.getUser(Integer.parseInt(uid));
                        out.write("msg=x-" + u.getPhone());
                    } else {
                        out.write("msg=Unable to update sellers income.");
                    }

                } else {
                    out.write("msg=Unable to complete your request,Please try agin later.");
                }
            } else {
                out.write("msg=Internal server error,Please try again later.");
            }

        } else if (type.equals("cancel")) {
            String id = request.getParameter("idd");
            String staType = request.getParameter("state");
            String uid = request.getParameter("uid");
            String amount = request.getParameter("amount");
            double damo = Double.parseDouble(amount);
            System.out.println("amount:" + amount + " " + damo);
            System.out.println("idd:" + id);
            System.out.println("statype:" + staType);
            System.out.println("uid:" + uid);
            System.out.println("id:" + usid);
            System.out.println("type:" + type);

            if (id != null && !id.trim().equals("") && staType != null && !staType.trim().equals("")
                    && uid != null && !uid.trim().equals("") && amount != null && !amount.trim().equals("")) {
                boolean ok = ppdi.requestSettle(Integer.parseInt(id), Integer.parseInt(staType),
                        us.getUser_id(), "conf_date");
                if (ok) {
                    //                    boolean notiok = false;
                    //                        if (staType.equals("2")) {
                    //                            String noti = "Admin " + us.getUser_name() + " has confirmed your earning request";
                    //                            notiok = new NotificationDAOImp().addNotification(noti, date1, Time, Integer.parseInt(uid), 1, 4);
                    //                        } else if (staType.equals("3")) {
                    //                            String noti = "Admin " + us.getUser_name() + " has canceled your earning request";
                    //                            notiok = new NotificationDAOImp().addNotification(noti, date1, Time, Integer.parseInt(uid), 1, 3);
                    //                        }
                    //                        AdminNotification a = new AdminNotification();
                    //                        a.setUser_id(us.getUser_id());
                    //                        a.setDate(timeStamp);
                    //
                    //                        a.setShow(1);
                    //                        if (staType.equals("3")) {
                    //                            a.setType(2);
                    //                            String not = "Admin " + us.getUser_name() + " has canceled " + amount + " earning request.";
                    //                            a.setNotification(not);
                    //                        } else if (staType.equals("2")) {
                    //                            a.setType(4);
                    //                            String not = "Admin " + us.getUser_name() + " has confirmed " + amount + " earning requests.";
                    //                            a.setNotification(not);
                    //                        }
                    //
                    //                        int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    //                        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);
                    //
                    //                        boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.notMeList(us.getUser_id()), an, 1);
                    //
                    //                        if (notiok && kl) {
                    //                            out.write("ok");
                    //                        } else {
                    //                            out.write("error");
                    //                        }
                    out.write("msg=Successful...");
                } else {
                    out.write("msg=Unable to complete your request,Please try agin later.");
                }
            } else {
                out.write("msg=Internal server error,Please try again later.");
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@GET/*from www . j a va 2s . c  om*/
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public String search(@PathParam("repositoryId") String repositoryId, @QueryParam("query") String query) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    List<Group> groups = this.principalService.getGroups(repositoryId);
    JSONArray queriedGroups = new JSONArray();

    for (Group g : groups) {
        if (g.getGroupId().startsWith(query) || g.getName().startsWith(query)) {
            queriedGroups.add(this.convertGroupToJson(g));
        }
    }

    if (queriedGroups.size() == 0) {
        status = false;
        addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_NOTFOUND);
    } else {
        result.put("result", queriedGroups);
    }

    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:com.conwet.silbops.msg.UnsubscribeMsg.java

@Override
@SuppressWarnings("unchecked")
public JSONObject getPayloadAsJSON() {

    JSONObject json = new JSONObject();
    json.put("subscription", subscription.toJSON());

    JSONArray uncov = new JSONArray();
    for (Subscription fil : uncovered) {

        uncov.add(fil.toJSON());/*  ww  w  .jav a2  s . c om*/
    }
    json.put("uncovered", uncov);

    return json;
}

From source file:modelo.ProcesoVertimientosManagers.ManejoLodos.java

public JSONArray getLodos(String codigo) throws Exception {

    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarEntidadesLodos select = new SeleccionarEntidadesLodos();
    ResultSet rset = select.getLodos(codigo);
    //Creamos los JSONArray para guardar los objetos JSON
    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArreglo = new JSONArray();

    //Recorremos el ResultSet, armamos el objeto JSON con la info y guardamos
    //en el JSONArray.
    while (rset.next()) {

        //Armamos el objeto JSON con la informacion del registro
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("codigo", rset.getString("CODIGO"));
        jsonObject.put("nombreEmpresa", rset.getString("NOMBRE_EMPRESA"));
        jsonObject.put("recolecta", rset.getString("RECOLECTA"));
        jsonObject.put("transporte", rset.getString("TRANSPORTE"));
        jsonObject.put("dispone", rset.getString("DISPONE"));

        //Guardamos el JSONObject en el JSONArray y lo enviamos a la vista.
        jsonArray.add(jsonObject.clone());

    }/*from   www .j  a  v  a  2s .  c o  m*/

    jsonArreglo.add(jsonArray);
    select.desconectar();

    return jsonArreglo;

}

From source file:csiro.pidsvc.mappingstore.ManagerJson.java

@SuppressWarnings("unchecked")
public JSONArray getSettings() throws SQLException {
    PreparedStatement pst = null;
    ResultSet rs = null;//from  w ww  . j  a  va  2  s .  co m
    JSONArray ret = new JSONArray();

    try {
        pst = _connection.prepareStatement("SELECT * FROM configuration");
        if (pst.execute()) {
            for (rs = pst.getResultSet(); rs.next();)
                ret.add(JSONObjectHelper.create("name", rs.getString(1), "value", rs.getString(2)));
        }
    } finally {
        if (rs != null)
            rs.close();
        if (pst != null)
            pst.close();
    }
    return ret;
}

From source file:edu.vt.vbi.patric.portlets.PathwayTable.java

@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException {

    response.setContentType("application/json");

    HashMap<String, String> key = new HashMap<>();

    if (request.getParameter("id") != null) {
        key.put("feature_id", request.getParameter("id"));
    }//from   w  w  w .  j av a2s.c  o m

    DataApiHandler dataApi = new DataApiHandler(request);

    int count_total = 0;
    JSONArray results = new JSONArray();
    List<String> pathwayKeys = new ArrayList<>();
    Map<String, Integer> mapOccurrence = new HashMap<>();
    try {
        SolrQuery query = new SolrQuery("feature_id:" + request.getParameter("id"));
        query.setRows(dataApi.MAX_ROWS);

        String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map respBody = (Map) resp.get("response");

        count_total = (Integer) respBody.get("numFound");
        List<Map> sdl = (List<Map>) respBody.get("docs");

        for (Map doc : sdl) {
            String pathwayKey = "(pathway_id:" + doc.get("pathway_id").toString() + " AND ec_number:"
                    + doc.get("ec_number").toString() + ")";

            pathwayKeys.add(pathwayKey);
        }

        SolrQuery queryRef = new SolrQuery(StringUtils.join(pathwayKeys, " OR "));
        queryRef.setFields("pathway_id,ec_number,occurrence");
        queryRef.setRows(pathwayKeys.size());

        apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, queryRef);

        resp = jsonReader.readValue(apiResponse);
        respBody = (Map) resp.get("response");

        List<Map> refList = (List<Map>) respBody.get("docs");

        for (Map doc : refList) {
            mapOccurrence.put(doc.get("pathway_id") + "_" + doc.get("ec_number"),
                    (Integer) doc.get("occurrence"));
        }

        for (Map doc : sdl) {
            JSONObject item = new JSONObject();
            item.put("pathway_id", doc.get("pathway_id"));
            item.put("feature_id", doc.get("feature_id"));
            item.put("pathway_name", doc.get("pathway_name"));
            item.put("pathway_class", doc.get("pathway_class"));
            item.put("algorithm", doc.get("annotation"));
            item.put("ec_number", doc.get("ec_number"));
            item.put("ec_name", doc.get("ec_description"));
            item.put("taxon_id", doc.get("taxon_id"));
            item.put("genome_id", doc.get("genome_id"));

            item.put("occurrence", mapOccurrence.get(doc.get("pathway_id") + "_" + doc.get("ec_number")));

            results.add(item);
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    JSONObject jsonResult = new JSONObject();

    try {
        jsonResult.put("total", count_total);
        jsonResult.put("results", results);
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
    }

    PrintWriter writer = response.getWriter();
    jsonResult.writeJSONString(writer);
    writer.close();
}

From source file:cc.pinel.mangue.storage.MangaStorage.java

public void addManga(Manga manga) throws IOException {
    JSONObject json = null;//from   w ww .  j av  a2s  .co m

    try {
        json = readJSON();
    } catch (Exception e) {
        // ignored
    }
    if (json == null)
        json = new JSONObject();

    JSONArray jsonMangas = (JSONArray) json.get("mangas");
    if (jsonMangas == null) {
        jsonMangas = new JSONArray();
        json.put("mangas", jsonMangas);
    }

    JSONObject jsonManga = findManga(jsonMangas, manga.getId());
    if (jsonManga == null) {
        jsonManga = new JSONObject();
        jsonManga.put("id", manga.getId());
        jsonManga.put("name", manga.getName());
        jsonManga.put("path", manga.getPath());

        jsonMangas.add(jsonManga);

        Object[] sortedArray = jsonMangas.toArray();
        Arrays.sort(sortedArray, new Comparator() {
            public int compare(Object o1, Object o2) {
                JSONObject manga1 = (JSONObject) o1;
                JSONObject manga2 = (JSONObject) o2;
                return manga1.get("name").toString().compareTo(manga2.get("name").toString());
            }
        });

        JSONArray sortedJSONArray = new JSONArray();
        for (int i = 0; i < sortedArray.length; i++)
            sortedJSONArray.add(sortedArray[i]);
        json.put("mangas", sortedJSONArray);

        writeJSON(json);
    }
}

From source file:com.aerothai.database.model.ModelService.java

public JSONObject GetModelAt(int id) throws Exception {

    Connection dbConn = null;/*from w ww. ja  va2s.c o  m*/
    JSONObject obj = new JSONObject();
    JSONArray objList = new JSONArray();

    int no = 1;
    //obj.put("draw", 2);
    obj.put("tag", "listat");
    obj.put("msg", "error");
    obj.put("status", false);
    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        String query = "SELECT * FROM model where idmodel = " + id;
        System.out.println(query);
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {

            JSONObject jsonData = new JSONObject();
            jsonData.put("id", rs.getInt("idmodel"));
            jsonData.put("details", rs.getString("details"));
            jsonData.put("idunit", rs.getString("idunit"));
            jsonData.put("iddevice_type", rs.getString("iddevice_type"));
            jsonData.put("no", no);
            objList.add(jsonData);
            no++;
        }
        obj.put("msg", "done");
        obj.put("status", true);
        obj.put("data", objList);
    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj;
}