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:io.personium.test.jersey.cell.ctl.ExtRoleCreateTest.java

/**
     * ???????ExtRole??./*w w w  . j av  a2 s. co m*/
     * @param extRolePath ExtRole?
     * @param relationName ??
     * @param relationBoxName ??
     */
    @SuppressWarnings("unchecked")
    private TResponse createExtRole(String extRolePath, String relationName, String relationBoxName) {
        JSONObject body = new JSONObject();
        body.put("ExtRole", extRolePath);
        body.put("_Relation.Name", relationName);
        body.put("_Relation._Box.Name", relationBoxName);
        return Http.request("cell/extRole/extRole-create.txt").with("token", AbstractCase.MASTER_TOKEN_NAME)
                .with("cellPath", cellName).with("body", body.toString()).returns().debug();
    }

From source file:ProductServlet.java

private String getResults(String query, String... params) throws SQLException, ClassNotFoundException {
    StringBuilder results = new StringBuilder();
    String result = "a";

    try (Connection conn = getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);

        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }/*w w  w  .ja v a 2 s  .c  o  m*/

        ResultSet rs = pstmt.executeQuery();
        JSONObject resultObj = new JSONObject();
        JSONArray productArr = new JSONArray();

        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("productID"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        resultObj.put("product", productArr);
        result = resultObj.toString();

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

From source file:api.accounts.UserVerify.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww .j a v  a  2s.  c  om
 *
 * @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:au.edu.ausstage.networks.LookupManager.java

/**
 * A method to lookup a collaborator/*from   w  w w .j av a 2 s.  co  m*/
 *
 * @param id         the unique identifier for the contributor
 * @param formatType the data format to use to encode the return value
 *
 * @return           information about the collaborator
 */
@SuppressWarnings("unchecked")
public String getCollaborator(String id, String formatType) {

    // check on the parameters
    if (InputUtils.isValidInt(id) == false || InputUtils.isValid(formatType) == false) {
        throw new IllegalArgumentException("Both parameters are required");
    }

    // define other helper variables
    QuerySolution row = null;
    Collaborator collaborator = null;

    // define the base sparql query
    String sparqlQuery = "PREFIX foaf:       <" + FOAF.NS + "> " + "PREFIX ausestage:  <" + AuseStage.NS + "> "
            + "SELECT ?givenName ?familyName ?function ?gender ?nationality ?collaboratorCount " + "WHERE { "
            + "   @ a                      foaf:Person; "
            + "                  foaf:givenName              ?givenName; "
            + "                  foaf:familyName             ?familyName; "
            + "                  ausestage:collaboratorCount ?collaboratorCount; "
            + "                  ausestage:function          ?function. "
            + "   OPTIONAL {@         foaf:gender                 ?gender} "
            + "   OPTIONAL {@         ausestage:nationality       ?nationality} " + "} ";

    // build a URI from the id
    id = AusStageURI.getContributorURI(id);

    // add the contributor URI to the query
    sparqlQuery = sparqlQuery.replaceAll("@", "<" + id + ">");

    // execute the query
    ResultSet results = rdf.executeSparqlQuery(sparqlQuery);

    // build the dataset
    // use a numeric sort order
    while (results.hasNext()) {
        // loop though the resulset
        // get a new row of data
        row = results.nextSolution();

        if (collaborator == null) {
            // instantiate a collaborator object
            collaborator = new Collaborator(AusStageURI.getId(id));

            // get the name
            collaborator.setGivenName(row.get("givenName").toString());
            collaborator.setFamilyName(row.get("familyName").toString(), true);

            // get the gender nationality, and collaborator count
            if (row.get("gender") != null) {
                collaborator.setGender(row.get("gender").toString());
            }

            if (row.get("nationality") != null) {
                collaborator.setNationality(row.get("nationality").toString());
            }

            // get the collaboration count
            /* collaborator count is incorrect */
            //collaborator.setCollaborations(Integer.toString(row.get("collaboratorCount").asLiteral().getInt()));

            // add a function
            collaborator.setFunction(row.get("function").toString());

        } else {

            // add the function
            collaborator.setFunction(row.get("function").toString());

        }
    }

    // play nice and tidy up
    rdf.tidyUp();

    // check on what to do
    if (collaborator == null) {
        // no collaborator found
        JSONObject object = new JSONObject();
        object.put("name", "No Collaborator Found");
        return object.toString();
    }

    // define a variable to store the data
    String dataString = null;

    if (formatType.equals("html") == true) {
        dataString = collaborator.toHtml();
    } else if (formatType.equals("xml") == true) {
        dataString = collaborator.toXml();
    } else if (formatType.equals("json") == true) {
        dataString = collaborator.toJson();
    }

    // return the data
    return dataString;

}

From source file:com.db.comserv.main.utilities.HttpCaller.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING")
public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers,
        String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException {

    StringBuffer response = new StringBuffer();
    HttpResult httpResult = new HttpResult();
    boolean gzip = false;
    final long startNano = System.nanoTime();
    try {/*from  www  . j  a v  a2 s  .  co  m*/
        URL encodedUrl = new URL(Utility.encodeUrl(url.toString()));
        HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection();
        TrustModifier.relaxHostChecking(con, sslByPassOption);

        // connection timeout 5s
        con.setConnectTimeout(connTimeOut);

        // read timeout 10s
        con.setReadTimeout(readTimeout * getQueryCost(req));

        methodType = methodType.toUpperCase();
        con.setRequestMethod(methodType);

        sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString()));

        // Get headers & set request property
        for (int i = 0; i < headers.size(); i++) {
            Map<String, String> header = headers.get(i);
            con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString());
            sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(),
                    ServletUtil.filterHeaderValue(header.get("headerKey").toString(),
                            header.get("headerValue").toString()));
        }

        if (con.getRequestProperty("Accept-Encoding") == null) {
            con.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (requestBody != null && !requestBody.equals("")) {
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(Utility.toUtf8Bytes(requestBody));
            wr.flush();
            wr.close();

        }

        // push response
        BufferedReader in = null;
        String inputLine;

        List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding");
        if (contentEncoding != null) {
            for (String val : contentEncoding) {
                if ("gzip".equalsIgnoreCase(val)) {
                    sLog.debug("Gzip enabled response");
                    gzip = true;
                    break;
                }
            }
        }

        sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(),
                ServletUtil.buildHeadersForLog(con.getHeaderFields()));

        if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
            if (con.getErrorStream() != null) {
                if (gzip) {
                    in = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8"));
                } else {
                    in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }
            }
        } else {
            String[] urlParts = url.toString().split("\\.");
            if (urlParts.length > 1) {
                String ext = urlParts[urlParts.length - 1];
                if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")
                        || ext.equalsIgnoreCase("gif")) {
                    BufferedImage imBuff;
                    if (gzip) {
                        imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream()));
                    } else {
                        BufferedInputStream bfs = new BufferedInputStream(con.getInputStream());
                        imBuff = ImageIO.read(bfs);
                    }
                    BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(),
                            BufferedImage.TYPE_3BYTE_BGR);

                    // converting image to greyScale
                    int width = imBuff.getWidth();
                    int height = imBuff.getHeight();
                    for (int i = 0; i < height; i++) {
                        for (int j = 0; j < width; j++) {
                            Color c = new Color(imBuff.getRGB(j, i));
                            int red = (int) (c.getRed() * 0.21);
                            int green = (int) (c.getGreen() * 0.72);
                            int blue = (int) (c.getBlue() * 0.07);
                            int sum = red + green + blue;
                            Color newColor = new Color(sum, sum, sum);
                            newImage.setRGB(j, i, newColor.getRGB());
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "jpg", out);
                    byte[] bytes = out.toByteArray();

                    byte[] encodedBytes = Base64.encodeBase64(bytes);
                    String base64Src = new String(encodedBytes);
                    int imageSize = ((base64Src.length() * 3) / 4) / 1024;
                    int initialImageSize = imageSize;
                    int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size"));
                    float quality = 0.9f;
                    if (!(imageSize <= maxImageSize)) {
                        //This means that image size is greater and needs to be reduced.
                        sLog.debug("Image size is greater than " + maxImageSize + " , compressing image.");
                        while (!(imageSize < maxImageSize)) {
                            base64Src = compress(base64Src, quality);
                            imageSize = ((base64Src.length() * 3) / 4) / 1024;
                            quality = quality - 0.1f;
                            DecimalFormat df = new DecimalFormat("#.0");
                            quality = Float.parseFloat(df.format(quality));
                            if (quality <= 0.1) {
                                break;
                            }
                        }
                    }
                    sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : "
                            + imageSize + "Url is : " + url + "quality is :" + quality);
                    String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64,"
                            + new String(base64Src);
                    JSONObject joResult = new JSONObject();
                    joResult.put("Image", src);
                    out.close();
                    httpResult.setResponseCode(con.getResponseCode());
                    httpResult.setResponseHeader(con.getHeaderFields());
                    httpResult.setResponseBody(joResult.toString());
                    httpResult.setResponseMsg(con.getResponseMessage());
                    return httpResult;
                }
            }

            if (gzip) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8"));
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            }
        }
        if (in != null) {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        httpResult.setResponseCode(con.getResponseCode());
        httpResult.setResponseHeader(con.getHeaderFields());
        httpResult.setResponseBody(response.toString());
        httpResult.setResponseMsg(con.getResponseMessage());

    } catch (Exception e) {
        sLog.error("Failed to received HTTP response after timeout", e);

        httpResult.setTimeout(true);
        httpResult.setResponseCode(500);
        httpResult.setResponseMsg("Internal Server Error Timeout");
        return httpResult;
    }

    return httpResult;
}

From source file:clientpaxos.ClientPaxos.java

public static void Vote(String votedName) throws Exception {
    if (votePhase.equals("day")) {
        // Kondisi siang
        String jsonVote;/*from ww w  .  ja v a  2s .  c o  m*/
        JSONObject jsonObject = new JSONObject();
        int killed_id = -1;
        for (int i = 0; i < listAlivePlayer.size(); i++) {
            if (listAlivePlayer.get(i).getUsername().equals(votedName)
                    && listAlivePlayer.get(i).getPlayerId() != player_id) {
                killed_id = listAlivePlayer.get(i).getPlayerId();
            }
        }
        if (killed_id != -1) {
            //                System.out.println("player_id : " + player_id);
            //method yang akan dikirimkan
            jsonObject.put("method", "vote_civilian");
            jsonObject.put("player_id", killed_id);
            String jsonOut = jsonObject.toString();
            System.out.println("kirim ke kpu : " + jsonOut);
            voteInput = false;

            //Kirim ke KPUjoin
            for (int i = 0; i < listPlayer.size(); i++) {
                if (listPlayer.get(i).getPlayerId() == acc_kpu_id) {
                    UDPThread.sendReliableMessage(listPlayer.get(i).getAddress(), listPlayer.get(i).getPort(),
                            jsonOut);
                }
            }
        } else {
            System.out.println("Error! Player yang divote tidak valid");
            StringBuilder alivePlayers = new StringBuilder("(");
            for (int i = 0; i < listAlivePlayer.size(); i++) {
                if (listAlivePlayer.get(i).getPlayerId() != player_id) {
                    if (!alivePlayers.toString().equals("(")) {
                        alivePlayers.append(", ");
                    }
                    alivePlayers.append(listAlivePlayer.get(i).getUsername());
                }
            }
            alivePlayers.append(")");
            System.out.print("vote player yang akan dibunuh " + alivePlayers.toString() + ": ");
        }
    } else if (votePhase.equals("night")) {
        // Kondisi malam
        String jsonVote;
        JSONObject jsonObject = new JSONObject();
        System.out.println("nama player yg akan dibunuh : " + votedName);
        int killed_id = -1;
        for (int i = 0; i < listAlivePlayer.size(); i++) {
            if (listAlivePlayer.get(i).getUsername().equals(votedName)
                    && listAlivePlayer.get(i).getPlayerId() != player_id
                    && !friend.get(0).equals(listAlivePlayer.get(i).getUsername())) {
                killed_id = listAlivePlayer.get(i).getPlayerId();
            }
        }
        if (killed_id != -1) {
            //method yang akan dikirimkan
            jsonObject.put("method", "vote_werewolf");
            jsonObject.put("player_id", killed_id);
            String jsonOut = jsonObject.toString();
            System.out.println("kirim ke kpu : " + jsonOut);
            voteInput = false;

            //Kirim ke KPU
            for (int i = 0; i < listPlayer.size(); i++) {
                if (listPlayer.get(i).getPlayerId() == acc_kpu_id) {
                    UDPThread.sendReliableMessage(listPlayer.get(i).getAddress(), listPlayer.get(i).getPort(),
                            jsonOut);
                }
            }
        } else {
            System.out.println("Error! Player yang divote tidak valid");
            StringBuilder aliveCivilians = new StringBuilder("(");
            for (int i = 0; i < listAlivePlayer.size(); i++) {
                if (listAlivePlayer.get(i).getPlayerId() != player_id
                        && !friend.get(0).equals(listAlivePlayer.get(i).getUsername())) {
                    if (!aliveCivilians.toString().equals("(")) {
                        aliveCivilians.append(", ");
                    }
                    aliveCivilians.append(listAlivePlayer.get(i).getUsername());
                }
            }
            aliveCivilians.append(")");
            System.out.print("vote player yang akan dibunuh " + aliveCivilians.toString() + ": ");
        }
    }
}

From source file:control.ProcesoVertimientosServlets.InsertarResultadoSupervision.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w ww .  j  av a2s.c  om*/
 * @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 {
    JSONObject jsonObjectResp = new JSONObject();
    try {

        int tecnico = Integer.parseInt(request.getParameter("tecnico"));
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        String observacion = request.getParameter("observacion");
        String estuvo = request.getParameter("estuvo");
        int resul;

        ProgramarMonitoreo manager = new ProgramarMonitoreo();

        resul = manager.insertarResultadoSupervision(codigo, tecnico, observacion, estuvo);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        jsonObjectResp.put("error", resul);
        response.getWriter().write(jsonObjectResp.toString());

    } catch (Exception e) {
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        jsonObjectResp.put("error", 0);
        response.getWriter().write(jsonObjectResp.toString());

    }

}

From source file:CPUController.java

@RequestMapping("/cpu")
public @ResponseBody CPU cpu(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from w  w w . j a  v a  2s  .  co  m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "cpu");
    params.put("search", search);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";
    String cpu = "";
    String clock = "";
    String metricType = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);
            String key = (String) tobj.get("key_");
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("idle") && key.contains("idle")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu idle time";
            } else if (name.equals("iowait") && key.contains("iowait")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu iowait time";
            } else if (name.equals("nice") && key.contains("nice")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu nice time";
            } else if (name.equals("system") && key.contains("system")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu system time";
            } else if (name.equals("user") && key.contains("user")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu user time";
            } else if (name.equals("load") && key.contains("load")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "processor load";
            } else if (name.equals("usage") && key.contains("usage")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "system cpu usage average";
            }
        }
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    if (cpu.equals("")) {
        return new CPU(
                "Error: Please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
    }

    return new CPU(hostid, metricType, cpu, clock);
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private OVFWrapper[] getAllServersWrappers() {
    ArrayList<OVFWrapper> wrappers = new ArrayList<OVFWrapper>();
    String servers = oStackClient.getAllServers();

    JSONObject allServers = (JSONObject) JSONValue.parse(servers);
    JSONArray jsonServers = (JSONArray) allServers.get("servers");

    for (int i = 0; i < jsonServers.size(); ++i) {
        JSONObject server = (JSONObject) jsonServers.get(i);
        OVFWrapper wTmp = this.parse(server.toString());
        wrappers.add(wTmp);//from w  w  w . j a va 2  s .c  o  m
    }

    OVFWrapper vms[] = wrappers.toArray(new OVFWrapper[wrappers.size()]);

    return vms;
}

From source file:io.personium.test.jersey.cell.ctl.ExtRoleCreateTest.java

/**
     * ???????ExtRole??().//ww w.  j a va 2  s.  c  om
     * @param relationName ??
     * @param relationBoxName ??
     * @param errKey 
     * @param errValue 
     * @param ?
     */
    @SuppressWarnings("unchecked")
    private void errCreateExtRole(String relationName, String relationBoxName, String errKey, String errValue,
            int errSC) {
        JSONObject body = new JSONObject();
        body.put("ExtRole", EXTROLE_PATH_DEFAULT);
        body.put("_Relation.Name", relationName);
        body.put("_Relation._Box.Name", relationBoxName);
        body.put(errKey, errValue);

        Http.request("cell/extRole/extRole-create.txt").with("token", AbstractCase.MASTER_TOKEN_NAME)
                .with("cellPath", cellName).with("body", body.toString()).returns().statusCode(errSC);
    }