Example usage for org.json.simple JSONObject toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:server.ServerHooks.java

public String status(Map<String, String> params) {
    String id;// w  ww. jav a2s  . c o  m
    JSONObject json = new JSONObject();

    if ((id = params.get(STATUS_ID_KEY)) != null)
        // is this a special status request (id == 'ERROR')?
        if (id.toLowerCase().equals("error")) {
            Result result = CommandProcessor.getActiveError();
            if (result.success())
                json.put(STATUS_RETURN_STATUS_KEY, CommandStatus.COMPLETE.toString());
            else {
                json.put(STATUS_RETURN_STATUS_KEY, CommandStatus.ERROR.toString());
                json.put(STATUS_ERROR_KEY, result.errorMessage);
            }
        } else {
            // note: we must call getResult before getStatus, because getStatus may remove the
            // item from the list if it has encountered success/error
            Result result = cmdq.getResult(id);
            CommandStatus status = cmdq.getStatus(id);
            json.put(STATUS_RETURN_STATUS_KEY, status.toString());
            if (status == CommandStatus.ERROR)
                if (result != null)
                    json.put(STATUS_ERROR_KEY, result.errorMessage);
        }
    else
        json.put(STATUS_ERROR_KEY, "Missing id value for status request");

    return json.toString();
}

From source file:server.ServerHooks.java

public String clearQueue(Map<String, String> params) {
    JSONObject json = new JSONObject();

    String strVal = null;//from  ww  w. j ava 2s . c o  m
    if ((strVal = params.get(CLEAR_QUEUE_ID_KEY)) != null) {
        int intVal = -1;
        try {
            intVal = Integer.parseInt(strVal);
        } catch (NumberFormatException ignored) {
            System.err.println("Clear queue failed - invalid number " + strVal);
            json.put(STATUS_ERROR_KEY, "Invalid ID number");
        }
        //if value is legit
        if (intVal != -1)
            cmdq.clear(intVal);
    } else {
        System.err.println("Clear queue failed - no parameter found");
        json.put(STATUS_ERROR_KEY, "No ID parameter found");
    }
    return json.toString();
}

From source file:server.ServerHooks.java

public String getVar(Map<String, String> params) {
    JSONObject json = new JSONObject();
    String key = null;//from w w  w  .ja  v  a2s .  c om
    String val;

    key = params.get(GET_INPUT_VAL_KEY);
    //        System.out.println("GET Printout: Key: " + key + " Value: " + vars.get(key));
    synchronized (vars) {
        val = vars.get(key);
    }

    if (val == null)
        val = "";

    json.put(GET_RETURN_VAL_KEY, val);
    return json.toString();
}

From source file:server.ServerHooks.java

public String setVar(Map<String, String> params) {
    String key = null;// www  .  j  a v  a2s . c o  m
    JSONObject json = new JSONObject();
    String val;

    key = params.get(SET_VAR_READ_VAL_KEY);
    val = params.get(SET_VAR_READ_VAL_VALUE);

    if (key != null && val != null)
        synchronized (vars) {
            vars.put(key, val);
        }

    return json.toString();
}

From source file:server.WebServer.java

@Override
public NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) {
    DatabaseWrapper dw = DatabaseWrapper.getInstance();
    System.out.println("URI: " + session.getUri());

    String URI = session.getUri().trim();

    //gets a new ID to be used for that message
    if (URI.startsWith(GET_IMAGE_ID_URI)) {
        JSONObject json = new JSONObject();

        int newImageId = dw.addNewImage();

        json.put("id", newImageId);

        return new NanoHTTPD.Response(json.toString());
    }/*w  ww . j  a  va  2s.c  om*/
    //returns the generated image and notates a view of the image
    else if (URI.startsWith(GET_IMAGE_URI + "/")) {
        Response response = new Response("");
        response.addHeader(XSS_KEY, XSS_VALUE);
        JSONObject json = new JSONObject();
        //string following the request URI
        try {
            int requestID = Integer.parseInt(session.getUri().trim().replaceFirst(GET_IMAGE_URI + "/", ""));
            System.out.println("Request ID: " + requestID);
            response.setMimeType("image/png");

            //if succesfully updated viewcount
            if (dw.incrementViewcount(requestID))
            //gets the file data for the 1x1 generated image
            {
                response.setData(new FileInputStream(Main.FAV_ICON_FILE_LOCATION));
                response.setStatus(Response.Status.OK);
                return response;
            } else {
                //error in parsing of number or getting file
                json.put("error", "Image not found");
                response = new Response(json.toString());
                response.addHeader(XSS_KEY, XSS_VALUE);
                response.setMimeType("application/json");
                response.setStatus(Response.Status.INTERNAL_ERROR);
                return response;
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException ex) {
            System.err.println("Parse of URI for int failed");
        }
        //error in parsing of number or getting file
        json.put("error", "Image could not be served");
        response = new Response(json.toString());
        response.setMimeType("application/json");
        response.addHeader(XSS_KEY, XSS_VALUE);
        response.setStatus(Response.Status.INTERNAL_ERROR);
        return response;
    }
    //gets the count for the number of views
    else if (URI.startsWith(GET_IMAGE_URI + "/")) {
        Response response = new Response("");
        JSONObject json = new JSONObject();
        int requestID = Integer.parseInt(session.getUri().trim().replaceFirst(GET_IMAGE_URI + "/", ""));
        int viewcount = -1;
        if ((viewcount = dw.getViewcount(requestID)) != -1) {
            json.put("viewcount", viewcount);
            response = new Response(json.toString());
            response.setStatus(Response.Status.OK);
            response.setMimeType("application/json");
            return response;
        } else {
            json.put("error", "Viewcount failed");
            response = new Response(json.toString());
            response.setMimeType("application/json");
            response.setStatus(Response.Status.INTERNAL_ERROR);
            return response;
        }
    } else if (URI.equals(FAV_ICO)) {
        try {
            return new NanoHTTPD.Response(NanoHTTPD.Response.Status.ACCEPTED, "image/x-icon",
                    new FileInputStream(Main.FAV_ICON_FILE_LOCATION));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        JSONObject json = new JSONObject();
        json.put("error", "Fav icon load failed.");
        return new NanoHTTPD.Response(json.toString());
    } else {
        JSONObject json = new JSONObject();
        json.put("error", "Please make a proper request.");
        return new NanoHTTPD.Response(json.toString());
    }
}

From source file:serverpaxos.ServerPaxos.java

public static void ParseCommand(String cmd, Socket socket) throws Exception {
    System.out.println("parse command");
    if (cmd.equals("vote_now")) {
        String json;/*  www .j  a va2s  . co m*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("method", "vote_now");

        Scanner scan = new Scanner(System.in);
        System.out.print("masukan phase: ");
        String phase = scan.nextLine();
        jsonObject.put("phase", phase);

        //Send To Client
        String response;
        response = jsonObject.toString();
        System.out.println("kirim : " + response);
        PrintWriter outToClient = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        //send msg to client
        outToClient.print(response + '\n');
        outToClient.flush();
    }
}

From source file:serverpaxos.ServerPaxos.java

public static void voteNow() throws IOException {
    String json;/*  w w w . j a  va2  s  .c  om*/

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("method", "vote_now");

    //Scanner scan = new Scanner(System.in);
    //System.out.print("masukan phase: ");
    //String phase = scan.nextLine();
    if (day) {
        jsonObject.put("phase", "day");
    } else {
        jsonObject.put("phase", "night");
    }

    //Send To Client
    String response;
    response = jsonObject.toString();
    System.out.println("kirim ke client : " + response);
    sendToAllClients(response, clientSockets);
}

From source file:serverpaxos.ServerPaxos.java

public static void broadcastClientAddress() throws IOException {
    String response;/*from  w  w w.  ja v a  2  s  . co m*/
    //build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status", "ok");

    //tempjason untuk array
    JSONArray ja = new JSONArray();
    for (int i = 0; i < listPlayer.size(); i++) {
        JSONObject tempobject = new JSONObject();
        tempobject.put("player_id", listPlayer.get(i).getPlayerId());
        tempobject.put("is_alive", listPlayer.get(i).getIsAlive());
        tempobject.put("address", listPlayer.get(i).getAddress());
        tempobject.put("port", listPlayer.get(i).getPort());
        tempobject.put("username", listPlayer.get(i).getUsername());
        if (listPlayer.get(i).getIsAlive() == 0) {

            tempobject.put("role", listPlayer.get(i).getRole());
        }
        ja.add(tempobject);
    }

    jsonObject.put("clients", ja);
    jsonObject.put("description", "list of clients retrieved");

    //convert JSONObject to JSON to String
    response = jsonObject.toString();
    System.out.println("kirim ke client : " + response);
    sendToAllClients(response, clientSockets);
}

From source file:servlets.MobileLogin.java

/** 
 * Initiated by login.jsp. Once this post request has been completely processed, the user will be logged in, the account will be one count closer to been temporarily been locked or will be locked out temporarily.
 * This method takes the credentials submitted and determines if they are correct. If they are correct, a session is prepared for the user and they are assigned a CSRF token.
 * @param login User's User Name//from w w  w  . ja  v  a  2 s . c  om
 * @param pwd User's Password      
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    log.debug("**** servlets.MobileLogin ***");
    HttpSession ses = request.getSession(true);
    PrintWriter out = response.getWriter();
    out.print(getServletInfo());
    response.setContentType("application/json");
    // params
    String p_login = request.getParameter("login");
    log.debug("userName: " + p_login);
    String p_pwd = request.getParameter("pwd");
    String csrfToken = new String();

    boolean authenticated = false;

    // session is not new, try to set credentials
    p_login = nvl(p_login, (String) ses.getAttribute("login"));
    p_pwd = nvl(p_pwd, (String) ses.getAttribute("password"));
    // get credentials
    String ApplicationRoot = getServletContext().getRealPath("");
    try {
        String user[] = Getter.authUser(ApplicationRoot, p_login, p_pwd);
        if (user != null && !user[0].isEmpty()) {

            //Kill Session and Create a new one with user logged in
            log.debug("Creating new session for " + user[2] + " " + user[1]);
            ses.invalidate();
            ses = request.getSession(true);
            ses.setAttribute("userStamp", user[0]);
            ses.setAttribute("userName", user[1]);
            ses.setAttribute("userRole", user[2]);
            //Used to make returned Keys user specific. Transferred to Exposed Server
            String encyptedUserName = Hash.encrypt(Hash.userNameKey, p_login);
            ses.setAttribute("ThreadSequenceId", encyptedUserName);
            log.debug("userClassId = " + user[4]);

            ses.setAttribute("userClass", user[4]);
            log.debug("Setting CSRF cookie");
            csrfToken = Hash.randomString();
            Cookie token = new Cookie("token", csrfToken);
            if (request.getRequestURL().toString().startsWith("https"))//If Requested over HTTPs
                token.setSecure(true);
            response.addCookie(token);
            authenticated = true;

            if (user[3].equalsIgnoreCase("true")) {
                log.debug("Temporary Password Detected, user will be prompted to change");
                ses.setAttribute("ChangePassword", "true");
            }
            //Removing user from kick list. If they were on it before, their suspension must have ended if they DB authentication Succeeded
            UserKicker.removeFromKicklist(user[1]);
        }
    } catch (Exception e) {
        log.error("Could not Find User: " + e.toString());
    }
    if (authenticated) {
        //returning SessionID and CSRF Token
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("JSESSIONID", ses.getId());
        jsonObj.put("token", csrfToken);
        out.write(jsonObj.toString());
        return;
    } else {
        //Lagging Response
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        out.write("ERROR: Could not Authenticate");
        return;
    }
}

From source file:showdomilhao.DAO.PontuacaoDAO.java

public void save(Ranking ranking) {
    JSONObject jsonToFile = new JSONObject();
    JSONArray rankingJSON = new JSONArray();

    for (RankItem rank : ranking.getRanking()) {
        JSONObject rankJSON = new JSONObject();
        rankJSON.put("jogador", rank.jogador);
        rankJSON.put("pontuacao", rank.pontuacao);
        rankingJSON.add(rankJSON);// w  ww  . j ava 2 s .  c o  m
    }

    jsonToFile.put("ranking", rankingJSON);

    try (FileWriter file = new FileWriter("ranking.json")) {
        file.write(jsonToFile.toString());
    } catch (IOException ex) {
        Logger.getLogger(PontuacaoDAO.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(jsonToFile.toString());
}