Example usage for org.json.simple JSONObject JSONObject

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

Introduction

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

Prototype

JSONObject

Source Link

Usage

From source file:com.gae.JsonBeans.java

public String revDirect(String kind, String key, String[] id) {
    String out = "";
    String prop[][] = getprop(id);
    JSONObject jsonobj = new JSONObject();
    boolean listp = false;
    try {//  w  w w. j  a  v a 2 s.  co m
        Key itemkey = KeyFactory.createKey(kind, key);
        Entity imas = ds.get(itemkey);
        String prop_st = "";
        Text prop_te = null;
        if (id.length == 1 && id[0].equals("*")) {
            /* ***************************************** *
             *                 
             * ***************************************** */
            Map pmap = new HashMap();
            pmap = imas.getProperties();
            Set keySet = pmap.keySet(); //?????  
            Iterator keyIte = keySet.iterator();
            while (keyIte.hasNext()) { //???iterator??  
                String ekey = keyIte.next().toString();
                String value = pmap.get(ekey).toString(); //value?
                //out += ekey + "<k>" + value + "<p>";
                jsonobj.put(ekey, value);
            }
        } else {
            /* **************************************** *
               *                          ?
             * **************************************** */
            for (int i = 0; i < id.length; i++) {
                String proplist = imas.getProperty(prop[i][1]).toString();
                if (proplist.indexOf(",") == -1) {
                    listp = false;
                } else {
                    listp = true;
                }
                if (prop[i][0].equals("st")) {
                    /*      */
                    if (imas.hasProperty(prop[i][1])) {
                        /*       */
                        prop_st = imas.getProperty(prop[i][1]).toString();
                        if (listp == false) {
                            // ???List???
                            out += prop_st + "<p>";
                        } else {
                            // ?List
                            String prop_li = prop_st.replaceAll("[ \\[\\]]", "");
                            out += prop_li + "<p>";
                        }
                    }
                } else if (prop[i][0].equals("te")) {
                    if (imas.hasProperty(prop[i][1])) {
                        /*       */
                        prop_te = (Text) imas.getProperty(prop[i][1]);
                        out += prop_te.getValue() + "<p>";
                    }
                } else {
                    /*  ????     */
                    if (imas.hasProperty(prop[i][1])) {
                        /*       */
                        prop_st = imas.getProperty(prop[i][1]).toString();
                        if (prop_st.indexOf(",") == -1) {
                            // ???List???
                            out += prop_st + "<p>";
                        } else {
                            // ?List
                            String prop_li = prop_st.replaceAll("[ \\[\\]]", "");
                            out += prop_li + "<p>";
                        }
                    }
                }
                /*  End  : Add on version1.1      */
            }
        }
    } catch (EntityNotFoundException e) {
        out = "NO:???????";
    }
    return (out);
}

From source file:com.imagelake.android.usersmanagement.Servlet_UserManagement.java

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

        String type = request.getParameter("type");
        JSONArray ja;
        if (type != null && !type.trim().equals("")) {

            if (type.equals("all")) {
                ja = new JSONArray();
                List<User> li = udi.listSellersBuyers();
                if (!li.isEmpty()) {

                    for (User u : li) {
                        JSONObject jo = new JSONObject();
                        jo.put("id", u.getUser_id());
                        jo.put("user_name", u.getUser_name());
                        jo.put("f_name", u.getFirst_name());
                        jo.put("l_name", u.getLast_name());
                        jo.put("em", u.getEmail());
                        jo.put("phn", u.getPhone());
                        jo.put("state", u.getState());
                        jo.put("type", u.getUser_type());
                        ja.add(jo);
                    }
                    out.write("json=" + ja.toJSONString());
                } else {
                    out.write("msg=No item found.");
                }
            } else if (type.equals("sort")) {
                ja = new JSONArray();

                String uid, date, buy, sell, name;
                uid = request.getParameter("uid");
                date = request.getParameter("date");
                buy = request.getParameter("buy");
                sell = request.getParameter("sell");
                name = request.getParameter("name");

                System.out.println("uid:" + uid);
                System.out.println("date:" + date);
                System.out.println("buy:" + buy);
                System.out.println("sell:" + sell);

                String sql = "SELECT * FROM user WHERE ";

                if (!sell.equals("false") || !buy.equals("false")) {

                    if (!uid.equals("") && !uid.equals(null)) {
                        System.out.println("user id=" + uid);
                        sql += " user_id='" + Integer.parseInt(uid) + "'";
                        if (!date.trim().equals("") && !date.equals(null)
                                || !buy.equals("") && !buy.equals(null)
                                || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }
                    }
                    if (!date.equals("") && !date.equals(null)) {
                        String[] dt = date.split("-");
                        String orDate = dt[2] + "-" + dt[1] + "-" + dt[0];
                        System.out.println("date=" + orDate);

                        sql += " date='" + orDate + "'";
                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)
                                || !name.equals("") && !name.equals(null)) {
                            sql += " AND ";
                        }

                    }

                    //                    if (!name.equals("") && !name.equals(null)) {
                    //                        System.out.println("Name=" + name);
                    //                        sql += "user_name='" + name + "'";
                    //                        if (!buy.equals("") && !buy.equals(null) || !sell.equals("") && !sell.equals(null)) {
                    //                            sql += " AND ";
                    //                        }
                    //                    }
                    if (!buy.equals("") && !buy.equals(null) && !buy.equals("false")) {
                        System.out.println("buyers=" + buy);
                        sql += "user_type_user_type_id='" + 3 + "'";
                        if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                            sql += " OR ";
                        }

                    }
                    if (!sell.equals("") && !sell.equals(null) && !sell.equals("false")) {
                        System.out.println("Sellers=" + sell);
                        sql += "user_type_user_type_id='" + 2 + "'";

                    }
                    System.out.println("sql=" + sql);
                    PreparedStatement ps;

                    try {
                        ps = DBFactory.getConnection().prepareStatement(sql);
                        ResultSet rs = ps.executeQuery();
                        while (rs.next()) {
                            JSONObject jo = new JSONObject();
                            jo.put("id", rs.getInt(1));
                            jo.put("user_name", rs.getString(2));
                            jo.put("f_name", rs.getString(3));
                            jo.put("l_name", rs.getString(4));
                            jo.put("em", rs.getString(5));
                            jo.put("phn", rs.getString(12));
                            jo.put("state", rs.getInt(19));
                            jo.put("type", rs.getInt(21));
                            ja.add(jo);
                        }

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

                } else {
                    System.out.println("no item");
                    out.write("msg=No item found.");
                }
            } else if (type.equals("update")) {
                String id = request.getParameter("id");
                String uid = request.getParameter("uid");
                String state = request.getParameter("state");

                System.out.println("id:" + id);
                System.out.println("uid:" + uid);
                System.out.println("state:" + state);

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

                User user = (User) udi.getUser(Integer.parseInt(uid));

                boolean ok = udi.updateUserState(Integer.parseInt(uid), Integer.parseInt(state));
                String un = udi.getUn(Integer.parseInt(uid));
                if (ok) {
                    //                        AdminNotification a = new AdminNotification();
                    //                        a.setUser_id(user.getUser_id());
                    //                        a.setDate(timeStamp);
                    //
                    //                        a.setShow(1);
                    //                        if (state.equals("2")) {
                    //                            a.setType(2);
                    //                            String not = "Admin " + user.getUser_name() + " has blocked user " + un;
                    //                            a.setNotification(not);
                    //                        } else if (state.equals("1")) {
                    //                            a.setType(4);
                    //                            String not = "Admin " + user.getUser_name() + " has activated user " + un;
                    //                            a.setNotification(not);
                    //                        }
                    //
                    //                        int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    //                        System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);
                    //
                    //                        boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.notMeList(user.getUser_id()), an, 1);
                    //                        if (kl) {
                    //                            out.write("ok");
                    //                        } else {
                    //                            out.write("no");
                    //                        }
                    out.write("msg=Successful...");
                } else {
                    out.write("msg=Unable to complete the action,Please try agin later.");
                }

            }

        } else {
            System.out.println("type");
            out.write("msg=Internal server error,Please try again later.");
        }

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

}

From source file:Employee.CreateMailingList.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*  www. ja v a  2 s.  co m*/
 * @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");
    JSONArray jsonArray = new JSONArray();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();

        String query = "SELECT P.SSN, P.FirstName, P.LastName, P.Email "
                + "FROM [MatchesFromAbove].[dbo].[Person] P, [MatchesFromAbove].[dbo].[Customer] C"
                + " WHERE C.Active = 'true' AND P.SSN = C.SSN";

        ResultSet rs = st.executeQuery(query);
        //loop through result set and create the json objects
        while (rs.next()) {
            JSONObject emailToAdd = new JSONObject();
            emailToAdd.put("ssn", rs.getString("SSN"));
            emailToAdd.put("firstName", rs.getString("FirstName"));
            emailToAdd.put("lastName", rs.getString("LastName"));
            emailToAdd.put("email", rs.getString("Email"));
            //add the json object that we're passing into the json array
            jsonArray.add(emailToAdd);
        }
        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        PrintWriter printout = response.getWriter();
        printout.print(jsonArray);
        printout.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return;
    }
}

From source file:net.duckling.ddl.web.api.APIAndroidMessagePullController.java

@RequestMapping
public void init(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String uid = findUser(req);//from   w ww  .j ava 2s . c  o  m
    if (StringUtils.isEmpty(uid) || "Guest".equals(uid)) {
        resp.sendError(401);
        JSONObject obj = new JSONObject();
        obj.put("error", "!");
        JsonUtil.writeJSONObject(resp, obj);
        return;
    }
    String sessionId = req.getSession().getId();
    AndroidMessageBean bean = androidNoticeHandler.getUserMessage(uid, sessionId);
    JSONObject obj = new JSONObject();
    addMessage(bean, obj);
    if (bean.getLatestMessageTeamId() > 0) {
        Team team = teamService.getTeamByID(bean.getLatestMessageTeamId());
        if (team != null) {
            obj.put("latestMesageTeamCode", team.getName());
            obj.put("latestMesageTeamName", team.getDisplayName());
        }
    }
    JsonUtil.writeJSONObject(resp, obj);
}

From source file:control.ParametrizacionServlets.InsertarPrmfisicoquimicos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w ww .j  a v  a2 s.c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        //Obtenemos los datos enviados.
        String descripcion = request.getParameter("descripcion");
        int unidades = Integer.parseInt(request.getParameter("unidades"));
        int tipoParametro = Integer.parseInt(request.getParameter("tipoParametro"));
        int salida;
        JSONObject jsonObject = new JSONObject();

        //Creamos el manager para registrar la informacion
        ParamFisicoquimicos manager = new ParamFisicoquimicos();

        salida = manager.insertar(descripcion, tipoParametro, unidades);

        jsonObject.put("error", salida);

        response.setContentType("application/json");
        response.getWriter().write(jsonObject.toString());

    } catch (Exception ex) {
        //Logger.getLogger(InsertarActEconomica.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:control.UsuariosServlets.ActualizarUsuarios.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   www  . j  a  v  a  2  s.  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer respuesta = 0;

    try {
        String usuario = request.getParameter("descripcion");
        Integer rol = Integer.parseInt(request.getParameter("rol"));
        Integer codigo = Integer.parseInt(request.getParameter("codigo"));

        Usuarios manager = new Usuarios();
        respuesta = manager.actualizarUsuarios(usuario, rol, codigo);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", respuesta);
        response.getWriter().write(jsonObject.toString());

    } catch (Exception ex) {

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", respuesta);
        response.getWriter().write(jsonObject.toString());
    }
}

From source file:api.accounts.UserVerify.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w  .  j a  va 2 s. co 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 {
    // request "?username=str1&password=str2&type=check/add"
    String clientUserName = request.getParameter("username");
    String clientPassword = request.getParameter("password");
    String methodType = request.getParameter("type");
    Map<String, Object> outcome = new HashMap<>();
    JSONObject output = new JSONObject();

    switch (methodType) {
    case "check":
        outcome = this.checkUserInfo(clientUserName, clientPassword);
        output = new JSONObject(outcome);
        break;
    case "add":
        outcome = this.addUserInfo(clientUserName, clientPassword);
        output = new JSONObject(outcome);
        break;
    default:
        break;
    }

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println(output.toString());
    }
}

From source file:com.saludtec.web.GaleriaWeb.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String servicio = request.getRequestURI().replace("/HCEMed/Galeria/", "");
        switch (servicio) {
        case "guardar":
            guardarGaleria(request).writeJSONString(out);
            break;

        case "editar":
            editarGaleria(request).writeJSONString(out);
            break;

        case "eliminar":
            eliminarGaleria(request).writeJSONString(out);
            break;

        case "traer":
            traerGaleria(request).writeJSONString(out);
            break;

        case "listar":
            listarGaleria(request).writeJSONString(out);
            break;

        default://from w w  w.  j a va2  s . co  m
            obj = new JSONObject();
            objArray = new JSONArray();
            obj.put("error", "404 - El servicio " + servicio + " no existe");
            objArray.add(obj);
            objArray.writeJSONString(out);
            break;
        }

    }
}

From source file:com.mobicage.rogerthat.form.LongListWidgetResult.java

@SuppressWarnings("unchecked")
@Override/*from w  w  w  .j a v a 2s. c om*/
public JSONObject toJSONObject() {
    JSONObject obj = new JSONObject();
    if (this.values == null)
        obj.put("values", null);
    else {
        JSONArray array = new JSONArray();
        for (Long val : this.values) {
            array.add(val);
        }
        obj.put("values", array);
    }
    return obj;
}

From source file:com.mobicage.rogerthat.form.FloatListWidgetResult.java

@SuppressWarnings("unchecked")
@Override//from   w ww.  j a  v a  2  s.c  om
public JSONObject toJSONObject() {
    JSONObject obj = new JSONObject();
    if (this.values == null)
        obj.put("values", null);
    else {
        JSONArray array = new JSONArray();
        for (Double val : this.values) {
            array.add(val);
        }
        obj.put("values", array);
    }
    return obj;
}