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.amindorost.searchalgorithms.MainSearch.java

public MainSearch() {
    this.topology = null;
    this.src = null;
    this.dst = null;
    this.nodesQueue = null;
    this.resultJSON = new JSONObject();
    this.iterationJSONArray = new JSONArray();
    this.pathJSON = new JSONArray();
}

From source file:com.romb.hashfon.helper.Helper.java

public String getJson(List list) {
    JSONArray jsonList = new JSONArray();
    for (Object o : list) {
        JSONObject obj1 = new JSONObject();
        for (Field field : o.getClass().getDeclaredFields()) {
            if (!field.getName().equals("serialVersionUID")) {
                field.setAccessible(true);
                String s = "";
                try {
                    s = field.get(o) + "";
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
                }/*  ww w.  j  av  a  2s  .  c  o m*/
                obj1.put(field.getName(), s);
            }
        }
        jsonList.add(obj1);
    }
    return jsonList.toJSONString();
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;//  w  w  w.  jav  a 2  s  .  c o  m
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:CreateGameServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject json = new JSONObject();

    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[1];
    int i = 0;/*  w ww. j  av a 2 s  . c om*/
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];
        i++;
    }
    //System.out.println("param0->"+params[0]);

    DatabaseHandler db = new DatabaseHandler();

    conn = db.makeConnection();

    try {
        stmt = conn.createStatement();

        String query = "INSERT INTO game (hoster,nameplayer1) VALUES (\"" + params[0] + "\",\"" + params[0]
                + "\")";
        //System.out.println(query);

        int updatedRows = stmt.executeUpdate(query);
        if (updatedRows == 1) {
            json.put("reply", "done");
        } else {
            json.put("reply", "undone");
        }

        query = "SELECT id FROM game WHERE hoster=\"" + params[0] + "\"";
        PreparedStatement prstmt = conn.prepareStatement(query);
        ResultSet rs = prstmt.executeQuery();
        String id = "0";
        while (rs.next()) {
            id = rs.getString("id");
        }
        //System.out.println("id-> "+id);
        if (!id.equals("0")) {
            json.put("gameid", id);
        }

    } catch (SQLException ex) {
        Logger.getLogger(CreateGameServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json.toString());

    db.closeAllConnections(conn, stmt);

}

From source file:hobbyshare.testclient.RestService_TestClient.java

public void test_Login() {
    HttpClient httpClient = HttpClientBuilder.create().build();

    JSONObject loginAttempt = new JSONObject();
    loginAttempt.put("password", "1234");
    loginAttempt.put("userName", "77_username");

    try {//from w  w w .j  ava  2s. co m
        HttpPost request = new HttpPost("http://localhost:8095/login");
        StringEntity params = new StringEntity(loginAttempt.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        System.out.println("---Testing Login----");
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        System.out.println("----End of login Test----");
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:RegistrationServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JSONObject json = new JSONObject();

    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[3];
    int i = 0;//  www .  j av  a 2s  . com
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        //System.out.println("ParamName : " +paramName);

        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];
        //System.out.println("ParamValue : " +params[i]);

        i++;
    }

    DatabaseHandler db = new DatabaseHandler();

    conn = db.makeConnection();
    try {
        stmt = conn.createStatement();

        //params[0]=password,params[1]=name,params[2]=email
        String query = "INSERT INTO user (name,email,password) VALUES (\"" + params[1] + "\",\"" + params[2]
                + "\",\"" + params[0] + "\")";
        //System.out.println(query);

        int updatedRows = stmt.executeUpdate(query);
        if (updatedRows == 1) {
            json.put("reply", "done");
        } else {
            json.put("reply", "undone");
        }

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

    //System.out.println(updatedRows);
    //System.out.println(json);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json.toString());

    //closing mysql connection (now done in DatanaseHandler class)
    db.closeAllConnections(conn, stmt);

}

From source file:assignment.HTTPResponse.java

public void serve(HTTPRequest httpRequest, OutputStream outputStream, Socket socket)
        throws IOException, ParseException, InterruptedException {
    PrintWriter pw = new PrintWriter(outputStream, true);
    JSONObject obj = new JSONObject();
    if (httpRequest.getHttpMethod().equals("GET")) {

        String[] url = (httpRequest.getResourceURI()).split("\\?");
        if (url[0].equals("/request")) {
            String ar1[] = url[1].split("&");
            String[] name1 = ar1[0].split("=");
            String connId = name1[1];
            String[] name2 = ar1[1].split("=");
            int timeout = Integer.parseInt(name2[1]);
            input[i][0] = connId;//from  w ww  .  j  a  v a  2s .  c  o  m

            Date startTime = new Date();
            Date parsedDate = df.parse(startTime.toString());
            Date endTime = new Date(parsedDate.getTime() + (1 * timeout));
            input[i][1] = startTime.toString();
            input[i][2] = endTime.toString();
            i++;

            obj.put("status", "ok");
            try {
                Thread.currentThread().sleep(timeout);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            pw.println(obj);
        } else if (url[0].equals("/serverStatus")) {
            Date now = new Date();
            long newDateTime = df.parse((new Date()).toString()).getTime();

            String result = "";
            JSONArray ja = new JSONArray();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        long endDateTime = (df.parse(input[j][2])).getTime();
                        long diff = ((endDateTime - newDateTime) / 1000);
                        JSONObject obj1 = new JSONObject();
                        obj1.put(input[j][0], diff);
                        result += obj1;
                    }
                }
            }
            pw.println(result);
        } else {
            pw.println("Request not supported.");
        }
    } else if ((httpRequest.getHttpMethod().equals("PUT")) || (httpRequest.getHttpMethod().equals("POST"))) {
        if (httpRequest.getResourceURI().equals("/kill")) {
            boolean found = false;
            Date now = new Date();
            for (int j = 0; j < input.length; j++) {
                if (input[j][0] != null && input[j][0].equals(httpRequest.getBody())) {
                    Date end = df.parse(input[j][2]);
                    if (end.compareTo(now) > 0) {
                        input[j][2] = now.toString();
                        found = true;
                    }
                }
            }
            if (found) {
                obj.put("status", "killed");
            } else {
                obj.put("status", "Invalid connId " + httpRequest.getBody());
            }
            System.out.println(obj);
            pw.println(obj);
        } else {
            pw.println("Request not supported.");
        }
    }
    socket.close();
}

From source file:modelo.ParametrizacionManagers.TipoVisita.java

public JSONArray getTiposVisitas() throws SQLException {
    //Ejecutamos la consulta y obtenemos el ResultSet
    SeleccionarTipoVisita select = new SeleccionarTipoVisita();
    ResultSet rset = select.getTiposVisitas();

    //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("descripcion", rset.getString("DESCRIPCION"));

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

    }/*from ww  w.ja  v  a 2 s.c  om*/

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

From source file:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {//from  ww w .ja va 2s .com
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ab.server.proxy.message.ProxyDragMessage.java

@SuppressWarnings("unchecked")
@Override/*from   www. j  a v a 2s. c o  m*/
public JSONObject getJSON() {
    JSONObject o = new JSONObject();
    o.put("x", x);
    o.put("y", y);
    o.put("dx", dx);
    o.put("dy", dy);
    return o;
}