Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:com.dvd.ui.AddUser.java

private void addUserBtnActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addUserBtnActionPerformed

    String userID = userIDTxt.getText();
    String userName = userNameTxt.getText();
    String password = userPassword.getText();
    String type = typeFlag.getSelectedItem().toString();

    if (userID != null && !userID.isEmpty() && userName != null && !userName.isEmpty() && password != null
            && !password.isEmpty() && type != null && !type.isEmpty()) {
        try {// w ww.j  a  v a2  s .c o  m
            int id = Integer.parseInt(userID);

            String userType = "";
            if (type.equals("Member")) {
                userType = "mem";
            } else if (type.equals("Employee")) {
                userType = "emp";
            }
            if (isServiceOn) {

                String result = "";
                String url1 = "http://localhost:8080/addUser?userID=" + id + "&UserName="
                        + URLEncoder.encode(userName, "UTF-8").replace("+", "%20") + "&password=" + password
                        + "&type=" + userType;

                // String q = URLEncoder.encode(url1, "UTF-8").replace("+",
                // "%20");
                URL url = new URL(url1);

                URL obj = url;
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                // con.setRequestProperty(CONTENT_LENGTH,
                // Integer.toString(content.getBytes().length));
                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setRequestProperty("Content-Language", "en-US");
                // optional default is GET
                con.setRequestMethod("POST");
                // add request header
                con.setRequestProperty("User-Agent", "Mozilla/5.0");

                int responseCode = con.getResponseCode();
                System.out.println("\nSending 'GET' request to URL : " + url);
                System.out.println("Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // print result
                result = response.toString();
                // Parse to get translated text

                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.getJSONObject("responseCode").getInt("code");

                if (code == 201) {
                    errorUserTag.setForeground(Color.BLACK);
                    errorUserTag.setText("User Successfully Added.");
                } else {
                    errorUserTag.setForeground(Color.RED);
                    errorUserTag.setText("User Registration failed");
                }

            } else {

                UserRepository repository = new UserRepository();

                User user = new User(userName, id, userType);
                repository.createUser(user);
                errorUserTag.setForeground(Color.BLACK);
                errorUserTag.setText("User Successfully Added.");

            }

        } catch (Exception e) {

            errorUserTag.setForeground(Color.RED);
            errorUserTag.setText("Adding User failed");

        }

    } else {
        errorUserTag.setForeground(Color.RED);
        errorUserTag.setText("Please Enter Valid data");

    }

}

From source file:rsInstanceJumpstart.rackspaceAccount.java

public String[][] listServers() {
    String[][] thisServerList = new String[100][5];
    //String thisServerList;
    HttpURLConnection connection;
    String output = "";
    int thisServerListCounter = 0;
    String thisServerLink;//from w  w  w. java2s  . co  m
    try {

        for (int i = 0; i < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog")
                .length(); i++) {
            if ("cloudServersOpenStack".equals(serviceCatalogJson.getJSONObject("access")
                    .getJSONArray("serviceCatalog").getJSONObject(i).get("name").toString())) {
                for (int ii = 0; ii < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog")
                        .getJSONObject(i).getJSONArray("endpoints").length(); ii++) {
                    String thisEndpoint = serviceCatalogJson.getJSONObject("access")
                            .getJSONArray("serviceCatalog").getJSONObject(i).getJSONArray("endpoints")
                            .getJSONObject(ii).get("publicURL").toString();
                    if (thisEndpoint.length() > 0) {
                        try {
                            output = "";
                            System.out.println("current endpoint: " + thisEndpoint);
                            connection = (HttpURLConnection) new URL(thisEndpoint + "/servers")
                                    .openConnection();

                            connection.setRequestProperty("Accept", "application/json");
                            connection.setRequestProperty("X-Auth-Token", currentAuthToken);

                            InputStream response;

                            response = connection.getInputStream();

                            //System.out.println(String.valueOf(connection.getResponseCode()));

                            BufferedReader reader = null;
                            try {
                                reader = new BufferedReader(new InputStreamReader(response));
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    output += line + "\n";
                                }
                            } finally {
                                if (reader != null) {
                                    try {
                                        reader.close();
                                    } catch (IOException e) {
                                        System.out.println(e);
                                    }
                                }
                            }
                        } catch (IOException e) {
                            System.out.println(e);
                        }
                        JSONObject thisResponseJson = new JSONObject(output);
                        if (thisResponseJson.getJSONArray("servers").length() > 0) {
                            for (int iii = 0; iii < thisResponseJson.getJSONArray("servers").length(); iii++) {
                                thisServerLink = thisResponseJson.getJSONArray("servers").getJSONObject(iii)
                                        .getJSONArray("links").getJSONObject(0).get("href").toString();
                                //query for details of each server

                                try {
                                    output = "";
                                    connection = (HttpURLConnection) new URL(thisServerLink).openConnection();

                                    connection.setRequestProperty("Accept", "application/json");
                                    connection.setRequestProperty("X-Auth-Token", currentAuthToken);

                                    InputStream response;

                                    response = connection.getInputStream();

                                    //System.out.println(String.valueOf(connection.getResponseCode()));

                                    BufferedReader reader = null;
                                    try {
                                        reader = new BufferedReader(new InputStreamReader(response));
                                        String line;
                                        while ((line = reader.readLine()) != null) {
                                            output += line + "\n";
                                        }
                                    } finally {
                                        if (reader != null) {
                                            try {
                                                reader.close();
                                            } catch (IOException e) {
                                                System.out.println(e);
                                            }
                                        }
                                    }
                                } catch (IOException e) {
                                    System.out.println(e);
                                }
                                //System.out.println(output);
                                JSONObject thisServer = new JSONObject(output);
                                System.out.println(thisServer.getJSONObject("server").get("name").toString());
                                if ("SHUTOFF".equals(thisServerList[thisServerListCounter][2] = thisServer
                                        .getJSONObject("server").getString("status"))) {
                                    thisServerList[thisServerListCounter][0] = thisServer
                                            .getJSONObject("server").getString("name");
                                    thisServerList[thisServerListCounter][1] = thisServer
                                            .getJSONObject("server").getString("id");
                                    thisServerList[thisServerListCounter][2] = thisServer
                                            .getJSONObject("server").getString("status");
                                    thisServerList[thisServerListCounter][3] = thisServerLink;
                                    thisServerList[thisServerListCounter][4] = thisServer
                                            .getJSONObject("server").getString("accessIPv4");
                                    System.out.println(thisServerList[thisServerListCounter][2]);
                                    thisServerListCounter++;
                                }
                            }
                        }
                    }

                }

            }

        }

    } catch (JSONException e) {
        //let's assume for now we won't have any
    }

    //thisServerList = output;
    return thisServerList;
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

/**
 * Finds and returns a user with the given id. Throws an InstagramException
 * if none is found or the user with that id cannot be accessed
 * /*from   w  ww .ja v  a  2s . co m*/
 * @param userId
 *            id of the user
 * @return The user with the id passed
 */
public User getUserById(int userId) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("user_id", userId);
    String uri = uriConstructor.constructUri(UriFactory.Users.GET_DATA, map, true);
    JSONObject userObject = (new GetMethod(uri).call()).getJSON();
    if (userObject.has("data")) {
        return new User(userObject.getJSONObject("data"), getAccessToken());
    } else {
        throw new InstagramException("User with id = " + userId + " cannot be accessed" + " or may not exist");
    }
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

/**
 * Gets the media with the id passed. Throws an InstagramException if no
 * media with that is is found.//from  w w w . ja v  a2s.c o m
 * 
 * @param mediaId
 *            the id of the media to be returned
 * @throws Exception,  JSONException
 * @return The media with the id passed
 */
public Media getMedia(String mediaId) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("media_id", mediaId);
    String uri = uriConstructor.constructUri(UriFactory.Media.GET_MEDIA, map, true);
    JSONObject object = (new GetMethod(uri).call()).getJSON();
    return Media.fromJSON(object.getJSONObject("data"), getAccessToken());
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public Relationship getRelationshipWith(int userId) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("user_id", userId);
    String uri = uriConstructor.constructUri(UriFactory.Relationships.GET_RELATIONSHIP_STATUS, map, true);
    JSONObject object = (new GetMethod(uri)).call().getJSON();
    return new Relationship(object.getJSONObject("data"), getAccessToken());
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public boolean modifyRelationship(int userId, Relationship.Action action) throws Exception {
    String actionString = "";
    HashMap<String, Object> map = new HashMap<String, Object>();
    HashMap<String, Object> args = new HashMap<String, Object>();
    map.put("user_id", userId);

    switch (action) {
    case BLOCK:/*w w  w. j a  v a  2s  .  c om*/
        actionString = "block";
        break;
    case UNBLOCK:
        actionString = "unblock";
        break;
    case APPROVE:
        actionString = "approve";
        break;
    case DENY:
        actionString = "deny";
        break;
    case FOLLOW:
        actionString = "follow";
        break;
    case UNFOLLOW:
        actionString = "unfollow";
        break;
    }

    args.put("action", actionString);
    String uri = uriConstructor.constructUri(UriFactory.Relationships.MUTATE_RELATIONSHIP, map, true);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    PostMethod post = (new PostMethod(uri)).setPostParameters(args);
    JSONObject object = post.call().getJSON();
    return object.getJSONObject("meta").getInt("code") == 200;
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public Comment postComment(String mediaId, String text) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    HashMap<String, Object> args = new HashMap<String, Object>();
    map.put("media_id", mediaId);
    args.put("text", text);
    args.put("access_token", getAccessToken());
    String uri = uriConstructor.constructUri(UriFactory.Comments.POST_MEDIA_COMMENT, map, false);
    PostMethod post = new PostMethod(uri).setPostParameters(args);
    JSONObject object = post.call().getJSON();
    return new Comment(object.getJSONObject("data"), getAccessToken());
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public boolean removeComment(String mediaId, String commentId) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("media_id", mediaId);
    map.put("comment_id", commentId);
    String uri = uriConstructor.constructUri(UriFactory.Comments.DELETE_MEDIA_COMMENT, map, true);
    JSONObject object = (new DeleteMethod(uri)).call().getJSON();
    return object.getJSONObject("meta").getInt("code") == 200;
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public boolean likeMedia(String mediaId) throws Exception, JSONException {
    HashMap<String, Object> map = new HashMap<String, Object>();
    HashMap<String, Object> args = new HashMap<String, Object>();
    map.put("media_id", mediaId);
    args.put("access_token", getAccessToken());
    String uri = uriConstructor.constructUri(UriFactory.Likes.SET_LIKE, map, false);
    JSONObject object = (new PostMethod(uri).setPostParameters(args)).call().getJSON();
    return object.getJSONObject("meta").getInt("code") == 200;
}

From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java

public boolean removeMediaLike(String mediaId) throws Exception {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("media_id", mediaId);
    String uri = uriConstructor.constructUri(UriFactory.Likes.REMOVE_LIKE, map, true);
    JSONObject object = (new DeleteMethod(uri)).call().getJSON();
    return object.getJSONObject("meta").getInt("code") == 200;
}