Example usage for org.json.simple JSONObject toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:msuresh.raftdistdb.TestAtomix.java

private static void UpdatePortNumber() {
    try {/*from   ww  w.j a  v  a2 s .  com*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(Constants.STATE_LOCATION + "global.info"));
        JSONObject jsonObject = (JSONObject) obj;
        jsonObject.put("currentCount", portId);
        try (FileWriter file = new FileWriter(Constants.STATE_LOCATION + "global.info")) {
            file.write(jsonObject.toJSONString());
        }
    } catch (Exception e) {

    }
}

From source file:dimensionsorter.DimensionSorter.java

private static void initializeImageSorter() {
    try {// w  ww .  j a  va  2  s.  c  om
        // Retrieve storage account from connection-string
        // (The storage connection string needs to be changed in case of
        // cloud infrastructure
        // is used instead of emulator)
        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        // Create the queue client
        CloudQueueClient queueClient = storageAccount.createCloudQueueClient();

        // Retrieve a reference to a queue
        CloudQueue queue = queueClient.getQueueReference(globalImageSorterQueue);

        // Create the queue if it doesn't already exist
        queue.createIfNotExist();

        // Create the json object with the appropriate variables
        JSONObject obj = new JSONObject();
        obj.put("dataset", datasetName);
        obj.put("numOfL", new Integer(numberOfImageSorterNodes));
        obj.put("numOfImages", new Integer(numOfImages));

        // Send the Message
        CloudQueueMessage message = new CloudQueueMessage(obj.toJSONString());
        queue.addMessage(message);

    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (StorageException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:ch.newscron.shortUrlUtils.ShortenerURL.java

/**
 * Given a long original URL, the function makes a request to the Google API (with key) and takes out the shortened goo.gl URL from the received JsonNode. 
 * @param longURL is the full (domain/path/ENCODED_DATA) URL created for inviting potential members
 * @return a String which is the goo.gl shortened URL correlated to the original long URL.
 *///from   ww w  .j a v  a 2  s.c  o m
public static String getShortURL(String longURL) {
    try {
        JSONObject data = new JSONObject();
        data.put("longUrl", longURL);

        // HTTP request with the result
        HttpResponse<com.mashape.unirest.http.JsonNode> postResponse = Unirest.post(google_url)
                .header("Content-Type", "application/json").body(data.toJSONString()).asJson();
        return (String) postResponse.getBody().getObject().get("id"); //If everything is working, then return the shortened URL

    } catch (Exception e) {
    }

    return null; //In case of errors or problems, just return the full and long URL
}

From source file:jo.alexa.sim.ui.logic.RuntimeLogic.java

public static void copySpec(RuntimeBean runtime) {
    AppSpecBean spec = makeMRU(runtime, null);
    JSONObject jspec = ToJSONLogic.toJSON(spec);
    StringSelection ss = new StringSelection(jspec.toJSONString());
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(ss, mClipOwner);
}

From source file:org.jboss.aerogear.unifiedpush.test.util.AuthenticationUtils.java

public static Session login(String loginName, String password, String root)
        throws NullPointerException, UnexpectedResponseException {
    Validate.notNull(root);//from www.  j  ava2 s  .  c o  m

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("loginName", loginName);
    jsonObject.put("password", password);

    Response response = Session.newSession(root).given().contentType(ContentTypes.json())
            .header(Headers.acceptJson()).body(jsonObject.toJSONString()).post("/rest/auth/login");

    // TODO should we throw or return invalid session?
    if (response.statusCode() == HttpStatus.SC_OK) {
        return new Session(root, loginName, password, response.cookies());
    } else if (response.statusCode() == HttpStatus.SC_FORBIDDEN) {
        throw new ExpiredPasswordException(response);
    } else if (response.statusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new InvalidPasswordException(response);
    } else {
        // This should never happen
        throw new UnexpectedResponseException(response);
    }
}

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 . j a  va2 s  .c o m*/
        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:model.Post_store.java

public static int getlastid() {
    JSONParser parser = new JSONParser();
    int lastid = 1;
    try {//from  www  . j a v  a  2s. c o m

        Object idObj = parser.parse(new FileReader(root + "posts/lastid.json"));

        JSONObject jsonObject = (JSONObject) idObj;

        String slastid = jsonObject.get("lastid").toString();
        lastid = Integer.parseInt(slastid);

        //System.out.println(lastid);

    } catch (FileNotFoundException e) {
        JSONObject newIdObj = new JSONObject();
        lastid = 1;
        newIdObj.put("lastid", lastid);

        try (FileWriter file = new FileWriter(root + "posts/lastid.json");) {
            file.write(newIdObj.toJSONString());
            file.flush();
            file.close();

        } catch (IOException ex) {
            System.out.println(e);
        }
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return lastid;
}

From source file:com.conwet.silbops.msg.Message.java

public static Message fromJSON(JSONObject json) {

    try {//from   w  w w .j a  va  2s . c  o  m
        MessageType type = MessageType.fromJSON((String) json.get("type"));
        Constructor<? extends Message> constructor = typeMap.get(type).getConstructor(JSONObject.class);
        return constructor.newInstance(json.get("payload"));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Malformed object[" + json.toJSONString() + "]", ex);
    }
}

From source file:com.oic.connection.Connections.java

/**
 * ????JSON??//from   ww w .j a va 2s .  co m
 *
 * @param json
 */
public static void broadCastMessage(JSONObject json) {
    synchronized (userConnections) {
        Session session;
        try {
            for (int i = 0; i < userConnections.size(); i++) {
                WebSocketListener websocket = userConnections.get(i);
                session = websocket.getSession();
                if (session.isOpen()) {
                    session.getRemote().sendString(json.toJSONString());
                } else {
                    session.close();
                    userConnections.remove(i);
                }
            }
        } catch (IOException e) {
            LOG.log(Level.WARNING, "error {0}", e.toString());
        }
    }
}

From source file:org.jboss.aerogear.unifiedpush.test.util.AuthenticationUtils.java

public static boolean changePassword(String loginName, String oldPassword, String newPassword, String root) {
    Validate.notNull(root);/*from w  w  w . j  a v  a2s.  c  o m*/

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("loginName", loginName);
    jsonObject.put("password", oldPassword);
    jsonObject.put("newPassword", newPassword);

    // FIXME should not this be using already existing session?
    Response response = Session.newSession(root).given().contentType(ContentTypes.json())
            .header(Headers.acceptJson()).body(jsonObject.toJSONString()).put("/rest/auth/update");

    if (response.statusCode() == HttpStatus.SC_OK) {
        return true;
    } else if (response.statusCode() == HttpStatus.SC_UNAUTHORIZED) {
        throw new InvalidPasswordException(response);
    } else {
        throw new UnexpectedResponseException(response);
    }
}