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.owly.clnt.StatsWinTypeperfTest.java

/**
 * @param args//from  ww  w  . ja  va  2 s  .c o  m
 */
public static void main(String[] args) {

    Logger log = Logger.getLogger(StatsWinTypeperfTest.class);

    StatsWinTypeperf testStats = new StatsWinTypeperf();
    JSONObject topjson = new JSONObject();

    System.out.println("Date is: " + testStats.getActualDate());
    System.out.println("My Host  is: " + testStats.getMyhost());
    log.debug("Before StatsWinTypeperf ");
    topjson = testStats.getWinTypeperf();
    log.debug("After StatsWinTypeperf ");
    System.out.println("JSON: " + topjson.toString());
    System.out.println("Header: " + testStats.getHeader());

}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUninstallCapabilityOnEdgeAcs.java

/**
 * @param args//from   w ww  .  j a v a2  s . c o m
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUninstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUninstall\""));

    // UUID: string
    // Version: string
    // ExecutionEnvRef: String

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "2.2.0");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.owly.clnt.StatsTopCpuTest.java

/**
 * @param args/*from w w  w.  j  a v a2 s.  c om*/
 */
public static void main(String[] args) {

    Logger log = Logger.getLogger(StatsTopCpuTest.class);

    StatsTopCpu testStats = new StatsTopCpu();
    JSONObject topCPUjson = new JSONObject();

    System.out.println("Date is: " + testStats.getActualDate());
    System.out.println("My Host  is: " + testStats.getMyhost());
    log.debug("Before StatsTopCpuTest ");
    topCPUjson = testStats.getJSONTopCpu();
    log.debug("After StatsTopCpuTest ");
    System.out.println("JSON: " + topCPUjson.toString());
    System.out.println("Header: " + testStats.getHeader());

}

From source file:com.owly.clnt.StatsVmstatTest.java

/**
 * @param args/*from w ww. j  a va2s . c  o  m*/
 */
public static void main(String[] args) {

    Logger log = Logger.getLogger(StatsVmstatTest.class);

    StatsVmstat testStats = new StatsVmstat();
    JSONObject vmstatjson = new JSONObject();

    System.out.println("Date is: " + testStats.getActualDate());
    System.out.println("My Host  is: " + testStats.getMyhost());
    System.out.println("Header: " + testStats.getHeader());
    log.debug("Before VMstat ");
    vmstatjson = testStats.getJSONVmStat();
    log.debug("After VMstat ");
    System.out.println("JSON: " + vmstatjson.toString());

}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUpdateCapabilityOnEdgeAcs.java

/**
 * @param args//from  w w  w .j  av  a2 s  .com
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUpdate
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUpdate\""));

    // UUID: string
    // Version: string
    // URL: string
    // Username: string
    // Password: string

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "1.0.0");
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-2.2.0.jar");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateInstallCapabilityOnEdgeAcs.java

/**
 * @param args//from w w  w . j  av  a 2  s.  c o m
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateInstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateInstall\""));

    // URL: string
    // UUID: string
    // Username: string
    // Password: string
    // ExecutionEnvRef: string

    JSONObject object = new JSONObject();
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-1.0.0.jar");
    // object.put("UUID", "UUID_value");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);

        // 10 avr. 2013 10:09:23
        // org.apache.commons.httpclient.auth.AuthChallengeProcessor
        // selectAuthScheme
        // INFO: basic authentication scheme selected
        // status: 200
        // resp: "executed: changeDUStateInstall: {Password=Password_value,
        // Username=Username_value, ExecutionEnvRef=ExecutionEnvRef_value,
        // URL=http:\/\/archive.apache.org\/dist\/felix\/org.apache.felix.http.jetty-1.0.0.jar},
        // resp: com.netopia.nbbs.tr69.msg.ChangeDUStateResponse@2db81edf"

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {/*from   w  w w  . j  a  va 2 s .  c o m*/
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:com.owly.clnt.OwlyClnt.java

/**
 * @param args//  www .j a  va2 s  . c om
 *            First argument in the port where webserver is going to start
 */
public static void main(String[] args) {

    Logger log = Logger.getLogger(OwlyClnt.class);
    log.debug("Executing OwlyClnt");

    if (args.length == 1) {

        String clientport = args[0];
        setPort(Integer.parseInt(clientport));
        log.debug("Port to run  :" + clientport);

        // URL used for generating the VMstat of the server
        get(new Route("/OwlyClnt/Stats_Vmstat") {
            @Override
            public Object handle(Request request, Response response) {

                Logger log = Logger.getLogger(OwlyClnt.class);
                log.debug("Calling Stats_Vmstat");

                OSValidator osValidator = new OSValidator();
                log.debug("operating System " + osValidator.getOS());

                JSONObject json = new JSONObject();

                if (osValidator.isWindows()) {

                    StatsWinTypeperf testStats = new StatsWinTypeperf();

                    try {
                        json = testStats.getWinTypeperf();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    if (OSValidator.isUnix()) {

                        StatsVmstat testStats = new StatsVmstat();

                        try {
                            json = testStats.getJSONVmStat();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        json.put("StatType", "NOK");

                    }

                }

                return json.toString();

            }

        });

        // URL used for generating the TopCPU of the server
        get(new Route("/OwlyClnt/Stats_TopCPU") {
            @Override
            public Object handle(Request request, Response response) {

                Logger log = Logger.getLogger(OwlyClnt.class);
                log.debug("Calling Stats_Vmstat");

                OSValidator osValidator = new OSValidator();
                log.debug("operating System " + osValidator.getOS());

                JSONObject topCpuStatJson = new JSONObject();

                if (OSValidator.isUnix()) {

                    StatsTopCpu testStats = new StatsTopCpu();

                    try {
                        topCpuStatJson = testStats.getJSONTopCpu();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
                    topCpuStatJson.put("StatType", "NOK");

                }

                return topCpuStatJson.toString();
            }
        });

        // Url used for executing a healthcheck and see if the server is
        // available
        get(new Route("/healthCheck") {
            @Override
            public Object handle(Request request, Response response) {

                JSONObject objJSON = new JSONObject();
                objJSON.put("StatusServer", "OK");

                return objJSON.toString();
            }
        });

    } else {
        System.out.println("ERROR : you need to specify port number -> ./OwlyClnt port ");
    }

}

From source file:com.intuit.utils.PopulateUsers.java

public static void main(String[] args) {
    Date now = new Date();
    System.out.println("Current date is: " + now.toString());

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("tweetsdb");
    DBCollection collection = db.getCollection("userscollection");
    WriteResult result = collection.remove(new BasicDBObject());

    int userIndex = 1;
    for (int i = 1; i <= 10; i++) {
        JSONObject userDocument = new JSONObject();
        String user = "user" + userIndex;
        userDocument.put("user", user);

        JSONArray followerList = new JSONArray();
        Random randomGenerator = new Random();
        for (int j = 0; j < 3; j++) {
            int followerId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be a follower on himself
            while (followerId == userIndex) {
                followerId = randomGenerator.nextInt(10) + 1;
            }/*from  w w  w  .j  av  a  2  s  .  c  o m*/

            String follower = "user" + followerId;
            if (!followerList.contains(follower)) {
                followerList.add(follower);
            }
        }
        userDocument.put("followers", followerList);

        JSONArray followingList = new JSONArray();
        for (int k = 0; k < 3; k++) {
            int followingId = randomGenerator.nextInt(10) + 1;
            // Assumption here is, a user will not be following his own tweets
            while (followingId == userIndex) {
                followingId = randomGenerator.nextInt(10) + 1;
            }

            String followingUser = "user" + followingId;
            if (!followingList.contains(followingUser)) {
                followingList.add(followingUser);
            }
        }
        userDocument.put("following", followingList);
        System.out.println("Json string is: " + userDocument.toString());
        DBObject userDBObject = (DBObject) JSON.parse(userDocument.toString());
        collection.insert(userDBObject);
        userIndex++;

    }

    //        try {
    //            FileWriter file = new FileWriter("/Users/dmurty/Documents/MongoData/usersCollection.js");
    //            file.write(usersArray.toJSONString());
    //            file.flush();
    //            file.close();
    //        } catch (IOException ex) {
    //            Logger.getLogger(PopulateUsers.class.getName()).log(Level.SEVERE, null, ex);
    //        } 
}

From source file:EZShare.SubscribeCommandConnection.java

public static boolean onKeyPressed(DataOutputStream sslOut, String string, JSONObject unsubscribJsonObject) {
    try {// w  ww  . jav  a 2s  . c  o  m
        sslOut.writeUTF(unsubscribJsonObject.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}