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:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java

/**
 * Authentication logic/*from  w  w w.j a  v  a2 s .c  o m*/
 *
 * @return Access JOSS access object
 * @throws IOException if failed to parse the response
 */
public Access passwordScopeAuth() throws IOException {
    InputStreamReader reader = null;
    BufferedReader bufReader = null;
    try {
        JSONObject user = new JSONObject();
        user.put("id", mUserId);
        user.put("password", mPassword);
        JSONObject password = new JSONObject();
        password.put("user", user);
        JSONArray methods = new JSONArray();
        methods.add("password");
        JSONObject identity = new JSONObject();
        identity.put("methods", methods);
        identity.put("password", password);
        JSONObject project = new JSONObject();
        project.put("id", mProjectId);
        JSONObject scope = new JSONObject();
        scope.put("project", project);
        JSONObject auth = new JSONObject();
        auth.put("identity", identity);
        auth.put("scope", scope);
        JSONObject requestBody = new JSONObject();
        requestBody.put("auth", auth);
        HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStream output = connection.getOutputStream();
        output.write(requestBody.toString().getBytes());
        int status = connection.getResponseCode();
        if (status != 201) {
            return null;
        }
        reader = new InputStreamReader(connection.getInputStream());
        bufReader = new BufferedReader(reader);
        String res = bufReader.readLine();
        JSONParser parser = new JSONParser();
        JSONObject jsonResponse = (JSONObject) parser.parse(res);

        String token = connection.getHeaderField("X-Subject-Token");
        PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion);
        bufReader.close();
        reader.close();
        connection.disconnect();
        return access;

    } catch (Exception e) {
        if (bufReader != null) {
            bufReader.close();
        }
        if (reader != null) {
            reader.close();
        }
        throw new IOException(e);
    }
}

From source file:clientpaxos.ClientPaxos.java

public static void ParseCommand(String msg) throws Exception {
    if (!voteInput) {
        if (msg.equals("join")) {
            String json;/*  w  w  w .jav  a  2 s  .  co  m*/
            JSONObject jsonObject = new JSONObject();
            System.out.print("Masukkan nama : ");
            String username = scan.nextLine();
            jsonObject.put("method", "join");
            jsonObject.put("username", username);
            jsonObject.put("udp_address", InetAddress.getLocalHost().getHostAddress());
            host = InetAddress.getLocalHost().getHostAddress();
            System.out.print("Masukkan port : ");
            port = scan.nextInt();
            scan.nextLine();
            jsonObject.put("udp_port", port);
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("leave")) {
            String json;
            player_id = -1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "leave");
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("ready")) {
            String json;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "ready");
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("client_address")) {
            getClientAddress();
        } else if (msg.equals("prepare")) {
            UDPThread.propose();
        } else {
            String json;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", msg);
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        }
    } else {
        Vote(msg);
    }
}

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

/**
 * ??????????./*  w  w w.  j  av  a  2  s .  com*/
 * @param boxNameEmpty _Box.Name???
 */
@SuppressWarnings("unchecked")
private void createRoleAndCheckResponse(boolean boxNameEmpty) {
    JSONObject body = new JSONObject();
    body.put("Name", testRoleName);
    if (!boxNameEmpty) {
        body.put("_Box.Name", null);
    }

    TResponse response = Http.request("role-create.txt")
            .with("token", AbstractCase.MASTER_TOKEN_NAME)
            .with("cellPath", cellName)
            .with("body", body.toString())
            .returns()
            .statusCode(HttpStatus.SC_CREATED);

    // ???
    String location = UrlUtils.cellCtlWithoutSingleQuote("testcell1", "Role",
            "Name='" + testRoleName + "',_Box.Name=null");
    ODataCommon.checkCommonResponseHeader(response, location);

    // ???
    Map<String, Object> additional = new HashMap<String, Object>();
    additional.put("Name", testRoleName);
    additional.put("_Box.Name", null);
    ODataCommon.checkResponseBody(response.bodyAsJson(), location, ROLE_TYPE, additional);

}

From source file:cprasmu.rascam.camera.RazCamServerImpl.java

public String getAdvertData() {

    JSONObject obj = new JSONObject();
    obj.put("wlanAddress", wlanAddress);
    obj.put("webServerPort", webServerPort);
    obj.put("instanceName", instanceName);
    obj.put("lastModified", rcm.getLastModified().getTime());

    return obj.toString();

}

From source file:hoot.services.controllers.info.ReportsResource.java

/**
 * <NAME>Report Service Delete Report</NAME>
 * <DESCRIPTION>Deletes requested report.</DESCRIPTION>
 * <PARAMETERS>//from w ww  . j  a v a 2 s.  c  o m
 * <id>
 * Report id for deletion
 * </id>
 * </PARAMETERS>
 * <OUTPUT>
 *    JSON Object
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/info/reports/delete?id=123-456</URL>
 *    <REQUEST_TYPE>GET</REQUEST_TYPE>
 *    <INPUT>
 * </INPUT>
 * <OUTPUT>{"id":"123-456", "deleted":"true"}</OUTPUT>
 * </EXAMPLE>
 * @param id
 * @return
 */
@GET
@Path("/delete")
@Produces(MediaType.TEXT_PLAIN)
public Response delReport(@QueryParam("id") final String id) {
    JSONObject resp = new JSONObject();
    boolean isDeleted = false;
    try {
        isDeleted = _deleteReport(id);
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error exporting report file: " + ex.toString(),
                Status.INTERNAL_SERVER_ERROR, log);
    }
    resp.put("id", id);
    resp.put("deleted", "" + isDeleted);
    return Response.ok(resp.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);/* w  w w . j  av  a2 s . c o  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();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    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 = "";

    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);

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:apimanager.ZohoSupportAPIManager.java

public String[] getCompleteRecordsForMEDCSupport(String departName) {
    Integer index = 1;// w  w  w  . j a v  a  2s  .com

    System.out.println(
            "Trying to connect to zoho support(MEDCSupport portal -->" + departName + ") server......");
    loggerObj.log(Level.INFO,
            "Trying to connect to zoho support(MEDCSupport portal -->" + departName + ") server......");

    DateFormat dateFormat = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
    Date date = new Date();
    String currTime = dateFormat.format(date);
    String folderToWriteResponse = "./Files/FromMEDCServer/" + currTime;
    boolean createFolderToWriteResponse = new File(folderToWriteResponse).mkdirs();

    if (!createFolderToWriteResponse) {
        loggerObj.log(Level.INFO, "Cannot create a folder" + folderToWriteResponse + " to write response");
        return null;
    }

    JSONObject resultObj = getRecordsForMEDCSupport(departName, folderToWriteResponse, index);
    loggerObj.log(Level.INFO, "Resultant object received from MEDC server is:" + resultObj.toString());

    if (resultObj == null) {
        System.out.println("Connection failure");
        loggerObj.log(Level.INFO, "connection problem in getCompleteRecordsForMEDCSupport method");
        return null;

    }
    System.out.println("connection successfull...");
    loggerObj.log(Level.INFO, "connection successfull...");
    System.out.println("Requesting tickets from zoho support api(MEDC support portal--->" + departName
            + ") server... \nThis might take around 5 mins");
    loggerObj.log(Level.INFO, "Requesting tickets from zoho support api(MEDC support portal--->" + departName
            + ") server... \nThis might take around 5 mins");

    while (resultObj != null) {
        //this logic uses index to increment the fromIndex and toIndex in the sequence: 1 to 200 , 201 to 400, 401 to 600, 601 to 800, etc,.
        loggerObj.log(Level.INFO,
                "received tickets in the range: " + ((index - 1) * 200 + 1) + " to " + index * 200);

        System.out.print(".");
        resultObj = getRecordsForMEDCSupport(departName, folderToWriteResponse, ++index);

    }
    System.out.println("\nReceived tickets from zoho support api... Going to process the tickets");
    loggerObj.log(Level.INFO, "\nReceived tickets from zoho support api... Going to process the tickets");

    //This is done so the last file is not written as that is a error file.
    index = index - 1;
    loggerObj.log(Level.INFO, "The folderToWriteResponse is " + folderToWriteResponse + "/JSONResponse_"
            + "The index value is " + index);

    return new String[] { folderToWriteResponse + "/JSONResponse_", index.toString() };
}

From source file:control.ParametrizacionServlets.ActualizarActEconomica.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  w w. j  a v a  2  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 {

    JSONObject respError = new JSONObject();

    try {

        //Obtenemos la informacion del form.
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        int ciiu = Integer.parseInt(request.getParameter("codigoCiiu"));
        String descripcion = request.getParameter("descripcion");

        ActividadEconomica manager = new ActividadEconomica();
        respError = manager.actualizar(codigo, descripcion, ciiu);

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

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

}

From source file:ServiceController.java

public String setRequest(String key_, String authentication, String hostid) {
    // create json object for apiinfo.version 
    JSONArray list = new JSONArray();
    JSONObject jsonObj = new JSONObject();
    JSONObject search = new JSONObject();
    JSONObject params = new JSONObject();

    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");

    params.put("output", "extend");
    params.put("hostid", hostid);
    params.put("search", search);
    params.put("sortfield", "name");

    search.put("key_", key_);

    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    return jsonObj.toString();
}

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

/**
 * ??./* w ww.  ja  v  a 2 s  .  c  o m*/
 * @param testRoleName
 * @return ???Role?Id
 */
@SuppressWarnings("unchecked")
String createRole(final String testRoleName) {
    // Role?C
    JSONObject body = new JSONObject();
    body.put("Name", testRoleName);
    body.put("_Box.Name", null);

    TResponse res = Http.request("role-create.txt")
            .with("token", AbstractCase.MASTER_TOKEN_NAME)
            .with("cellPath", cellName)
            .with("body", body.toString())
            .returns()
            .statusCode(HttpStatus.SC_CREATED)
            .inspect(new TResponse.Inspector() {
                public void inspect(TResponse resp) {
                }
            });

    String roleLocHeader = res.getLocationHeader();

    assertNotNull(roleLocHeader);

    // Role?R
    res = Http.request("role-retrieve.txt")
            .with("cellPath", cellName)
            .with("rolename", testRoleName)
            .with("boxname", "null")
            .with("token", AbstractCase.MASTER_TOKEN_NAME)
            .returns()
            .statusCode(HttpStatus.SC_OK)
            .contentType("application/json");

    JSONObject roleJson = res.bodyAsJson();
    roleJson = getResultsFromEntityResponse(roleJson);
    assertEquals(testRoleName, roleJson.get("Name"));
    assertNull(roleJson.get("_Box.Name"));
    assertNotNull(roleJson.get("__published"));
    assertNotNull(roleJson.get("__updated"));
    // assertEquals(etag, ((JSONObject) roleJson.get("__metadata")).get("etag"));

    // Role?U
    // TODO UPDATE??????
    return roleLocHeader;
}