Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:com.aokyu.dev.pocket.Response.java

protected Response(JSONObject jsonObj, String rootKey, Map<String, List<String>> headerFields)
        throws JSONException, PocketException {
    JSONObject obj = jsonObj.getJSONObject(rootKey);
    if (obj != null) {
        String[] keys = JSONUtils.getKeys(obj);
        int size = keys.length;
        for (int i = 0; i < size; i++) {
            String key = keys[i];
            Object value = obj.get(key);
            put(key, value);/*from   ww  w . ja v a2  s  .c  om*/
        }
    }

    mUserLimit = new UserLimit(headerFields);
    mClientLimit = new ClientLimit(headerFields);
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testCreateProject() throws Exception {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProject";
    URI workspaceLocation = createWorkspace(workspaceName);

    //create a project
    String projectName = "My Project";
    WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    String locationHeader = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    assertNotNull(locationHeader);//from   ww w .  j  ava 2 s  .  c  om

    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
    String projectId = project.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(projectId);

    //ensure project location = <workspace location>/project/<projectName>
    URI projectLocation = new URI(toAbsoluteURI(locationHeader));
    URI relative = workspaceLocation.relativize(projectLocation);
    IPath projectPath = new Path(relative.getPath());
    assertEquals(2, projectPath.segmentCount());
    assertEquals("project", projectPath.segment(0));
    assertEquals(projectName, projectPath.segment(1));

    //ensure project appears in the workspace metadata
    request = new GetMethodWebRequest(addSchemeHostPort(workspaceLocation).toString());
    setAuthentication(request);
    response = webConversation.getResponse(request);
    JSONObject workspace = new JSONObject(response.getText());
    assertNotNull(workspace);
    JSONArray projects = workspace.getJSONArray(ProtocolConstants.KEY_PROJECTS);
    assertEquals(1, projects.length());
    JSONObject createdProject = projects.getJSONObject(0);
    assertEquals(projectId, createdProject.get(ProtocolConstants.KEY_ID));
    assertNotNull(createdProject.optString(ProtocolConstants.KEY_LOCATION, null));

    //check for children element to conform to structure of file API
    JSONArray children = workspace.optJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertNotNull(children);
    assertEquals(1, children.length());
    JSONObject child = children.getJSONObject(0);
    assertEquals(projectName, child.optString(ProtocolConstants.KEY_NAME));
    assertEquals("true", child.optString(ProtocolConstants.KEY_DIRECTORY));
    String contentLocation = child.optString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(contentLocation);

    //ensure project content exists
    if (OrionConfiguration.getMetaStore() instanceof SimpleMetaStore) {
        // simple metastore, projects not in the same simple location anymore, so do not check
    } else {
        // legacy metastore, use what was in the original test
        IFileStore projectStore = EFS.getStore(makeLocalPathAbsolute(projectId));
        assertTrue(projectStore.fetchInfo().exists());
    }

    //add a file in the project
    String fileName = "file.txt";
    request = getPostFilesRequest(toAbsoluteURI(contentLocation), getNewFileJSON(fileName).toString(),
            fileName);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertEquals("Response should contain file metadata in JSON, but was " + response.getText(),
            "application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in response", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, projectName);
}

From source file:org.loklak.api.iot.NodelistPushServlet.java

@Override
protected void customProcessing(JSONObject message) {
    JSONObject location = (JSONObject) message.get("position");

    final Double longitude = Double.parseDouble((String) location.get("long"));
    final Double latitude = Double.parseDouble((String) location.get("lat"));
    List<Double> location_point = new ArrayList<>();
    location_point.add(longitude);/* w  ww .ja  va 2 s  .co  m*/
    location_point.add(latitude);
    message.put("location_point", location_point);
    message.put("location_mark", location_point);

    JSONObject user = new JSONObject(true);
    user.put("screen_name", "freifunk_" + message.get("name"));
    user.put("name", message.get("name"));
    message.put("user", user);
}

From source file:org.wso2.iot.integration.common.OAuthUtil.java

public static JSONObject getOAuthTokenPair(String backendHTTPURL, String backendHTTPSURL) throws Exception {
    String AuthString = "Basic YWRtaW46YWRtaW4=";
    RestClient client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON, AuthString);
    HttpResponse oAuthData = client.post(Constants.APIApplicationRegistration.API_APP_REGISTRATION_ENDPOINT,
            Constants.APIApplicationRegistration.API_APP_REGISTRATION_PAYLOAD);
    JSONObject jsonObj = new JSONObject(oAuthData.getData());
    String clientId = jsonObj.get(Constants.OAUTH_CLIENT_ID).toString();
    String clientSecret = jsonObj.get(Constants.OAUTH_CLIENT_SECRET).toString();
    byte[] bytesEncoded = Base64.encodeBase64((clientId + ":" + clientSecret).getBytes());
    String basicAuthString = "Basic " + new String(bytesEncoded);
    //Initiate a RestClient to get OAuth token
    client = new RestClient(backendHTTPSURL, Constants.APPLICATION_URL_ENCODED, basicAuthString);
    oAuthData = client.post(Constants.APIApplicationRegistration.TOKEN_ENDPOINT,
            Constants.APIApplicationRegistration.OAUTH_TOKEN_PAYLOAD);
    jsonObj = new JSONObject(oAuthData.getData());
    return jsonObj;
}

From source file:org.wso2.iot.integration.common.OAuthUtil.java

/**
 * To get the oauth token pair for the given auth string which is encoded in base64 format.
 * @param authString encoded auth string
 * @param backendHTTPURL backend http URL
 * @param backendHTTPSURL backend https URL
 * @return a JSON object which consist of oauth token pair
 * @throws Exception Exception// w  ww  .  j  a  v a2s  . c  om
 */
public static String getOAuthTokenPair(String authString, String backendHTTPURL, String backendHTTPSURL,
        String username, String password) throws Exception {
    RestClient client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON, "Basic " + authString);
    HttpResponse oAuthData = client.post(Constants.APIApplicationRegistration.API_APP_REGISTRATION_ENDPOINT,
            Constants.APIApplicationRegistration.API_APP_REGISTRATION_PAYLOAD);
    JSONObject jsonObj = new JSONObject(oAuthData.getData());
    String clientId = jsonObj.get(Constants.OAUTH_CLIENT_ID).toString();
    String clientSecret = jsonObj.get(Constants.OAUTH_CLIENT_SECRET).toString();
    byte[] bytesEncoded = Base64.encodeBase64((clientId + ":" + clientSecret).getBytes());
    String basicAuthString = "Basic " + new String(bytesEncoded);
    //Initiate a RestClient to get OAuth token
    client = new RestClient(backendHTTPSURL, Constants.APPLICATION_URL_ENCODED, basicAuthString);
    oAuthData = client.post(Constants.APIApplicationRegistration.TOKEN_ENDPOINT, "username=" + username
            + "&password=" + password + Constants.APIApplicationRegistration.MULTI_TENANT_OAUTH_TOKEN_PAYLOAD);
    jsonObj = new JSONObject(oAuthData.getData());
    return jsonObj.get(Constants.OAUTH_ACCESS_TOKEN).toString();

}

From source file:org.eclipse.flux.service.common.ToolingServiceProvider.java

/**
 * Constructs Tooling Services Manager// w  w w  .  j a  v  a  2 s  .c  o  m
 * 
 * @param host Flux server URL
 * @param serviceLauncher The tooling service starter/stopper 
 */
public ToolingServiceProvider(final MessageConnector messageConnector, final String serviceId,
        final IServiceLauncher serviceLauncher, int poolSize, boolean autoMaintainServicePoolSize) {
    super();
    this.messageConnector = messageConnector;
    this.serviceId = serviceId;
    this.poolSize = poolSize;
    this.autoMaintainServicePoolSize = autoMaintainServicePoolSize;
    serviceLauncher(serviceLauncher);

    messageHandlers = new IMessageHandler[] {

            new IMessageHandler() {

                @Override
                public boolean canHandle(String type, JSONObject message) {
                    try {
                        return message.getString("username").equals(MessageConstants.SUPER_USER)
                                && message.getString("service").equals(serviceId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return false;
                    }
                }

                @Override
                public void handle(String type, JSONObject message) {
                    try {
                        messageConnector.send(SERVICE_REQUIRED_RESPONSE,
                                new JSONObject(message, JSON_PROPERTIES));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public String getMessageType() {
                    return SERVICE_REQUIRED_REQUEST;
                }

            },

            new IMessageHandler() {

                @Override
                public boolean canHandle(String type, JSONObject message) {
                    try {
                        return message.getString("service").equals(serviceId);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return false;
                    }
                }

                @Override
                public void handle(String type, final JSONObject message) {
                    try {
                        JSONObject statusMessage = new JSONObject(message, JSON_PROPERTIES);
                        statusMessage.put("status", "unavailable");
                        String error = getError();
                        if (error == null) {
                            statusMessage.put("info", "Starting up services, please wait...");
                        } else {
                            statusMessage.put("error", getError());
                        }
                        messageConnector.send(DISCOVER_SERVICE_RESPONSE, statusMessage);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public String getMessageType() {
                    return DISCOVER_SERVICE_REQUEST;
                }

            },

            new IMessageHandler() {

                @Override
                public boolean canHandle(String type, JSONObject message) {
                    try {
                        return message.getString("service").equals(serviceId)
                                && "ready".equals(message.getString("status"))
                                && !MessageConstants.SUPER_USER.equals(message.get("username"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return false;
                    }
                }

                @Override
                public void handle(String type, JSONObject message) {
                    schedulePoolMaintenance();
                }

                @Override
                public String getMessageType() {
                    return SERVICE_STATUS_CHANGE;
                }

            } };
}

From source file:ch.icclab.cyclops.resource.impl.RateResource.java

/**
 * Saves the rate mentioned for a static rating policy into the db
 *
 * Pseudo Code//ww  w  . ja  v  a2 s. com
 * 1. Check for the rating policy
 * 2. Set the flag as per the rating policy mentioned in the incoming request
 * 3. Save the data into the db
 *
 * @param entity Entity containing the information to be saved
 * @return Representation
 */
@Post("json:json")
public Representation setRate(Representation entity) {
    counter.increment(endpoint);

    JsonRepresentation request;
    JSONObject jsonObj;
    String ratingPolicy;

    // Get the JSON object from the incoming request
    try {
        request = new JsonRepresentation(entity);
        jsonObj = request.getJsonObject();
        ratingPolicy = (String) jsonObj.get("rate_policy");
        // Set the Metering Type flag according to the rating policy
        // For static rate, save the static rate of the resources
        if (ratingPolicy.equalsIgnoreCase("static")) {
            Flag.setMeteringType("static");
            saveStaticRate(jsonObj, ratingPolicy);
        } else {
            Flag.setMeteringType("dynamic");
            //TODO: saveDynamicRate
        }
    } catch (IOException e) {
        e.printStackTrace();
        // TODO: return error code for IOException and JSONException
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null; //TODO: Construct & return a response (maybe return code 200)
}

From source file:ch.icclab.cyclops.resource.impl.RateResource.java

/**
 * Saves static rate into InfluxDB//from www  .j a v a2s .com
 *
 * Pseudo Code
 * 1. Populate object array with "rate" data from JSONObject
 * 2. Create the POJO object from object array
 * 3. Map POJO object to JSON data
 * 4. Save JSON data in InfluxDB client
 *
 * @param jsonObj Data obj containing the static rate of a resource
 * @param ratingPolicy String containing the rating policy
 * @return boolean
 */
private boolean saveStaticRate(JSONObject jsonObj, String ratingPolicy) {
    boolean result = false;
    TSDBData rateData = new TSDBData();
    ArrayList<String> strArr = new ArrayList<String>();
    ArrayList<Object> objArrNode;
    ArrayList<ArrayList<Object>> objArr = new ArrayList<ArrayList<Object>>();
    ObjectMapper mapper = new ObjectMapper();
    Load load = new Load();
    HashMap staticRate = new HashMap();
    String jsonData = null;
    JSONObject rateJsonObj;
    Iterator iterator;
    String key;

    if (dbClient == null) {
        dbClient = new InfluxDBClient();
    }
    //TODO: simplify this code, separate method of object creation from this method
    // Reset the hashmap containing the static rate
    load.setStaticRate(staticRate);
    // Set the flag to "Static"
    Flag.setMeteringType("static");
    // Create the Array to hold the names of the columns
    strArr.add("resource");
    strArr.add("rate");
    strArr.add("rate_policy");
    try {
        rateJsonObj = (JSONObject) jsonObj.get("rate");
        iterator = rateJsonObj.keys();
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            objArrNode = new ArrayList<Object>();
            objArrNode.add(key);
            objArrNode.add(rateJsonObj.get(key));
            objArrNode.add(ratingPolicy);
            objArr.add(objArrNode);
            // Load the rate hashmap with the updated rate
            staticRate.put(key, rateJsonObj.get(key));
        }
    } catch (JSONException e) {
        logger.error("Error while saving the Static Rate: " + e.getMessage());
        e.printStackTrace();
    }
    // Update the static hashmap containing the static rates
    load.setStaticRate(staticRate);
    // Set the data object to save into the DB
    rateData.setName("rate");
    rateData.setColumns(strArr);
    rateData.setPoints(objArr);
    try {
        jsonData = mapper.writeValueAsString(rateData);
    } catch (JsonProcessingException e) {
        logger.error("Error while saving the Static Rate: " + e.getMessage());
        e.printStackTrace();
    }
    result = dbClient.saveData(jsonData);
    return result;
}

From source file:org.uiautomation.ios.IOSCapabilities.java

public IOSCapabilities(JSONObject json) throws JSONException {
    Iterator<String> iter = json.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        Object value = json.get(key);
        setCapability(key, decode(value));
    }/*from w w  w  .jav a  2 s .co m*/
}

From source file:de.itomig.itoplib.GetItopJSON.java

public static <T> ArrayList<T> getArrayFromJson(String json, Type T) {
    ArrayList<T> list = new ArrayList<T>();
    String code = "100"; // json error code, "0" => everything is o.k.
    Log.d(TAG, "getArrayFromJson - Type=" + T.toString());

    JSONObject jsonObject = null;/*from  w  w  w  .ja va 2 s. co  m*/
    try {
        jsonObject = new JSONObject(json);
        code = jsonObject.getString("code");
        Log.d(TAG, "code=" + code);
        Log.d(TAG, "message=" + jsonObject.getString("message"));

    } catch (JSONException e) {
        Log.e(TAG, "error in getArrayFromJSON " + e.getMessage());
    }

    if ((jsonObject != null) && (code.trim().equals("0"))) {
        try {

            JSONObject objects = jsonObject.getJSONObject("objects");
            Iterator<?> keys = objects.keys();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                Log.d(TAG, "key=" + key);
                if (objects.get(key) instanceof JSONObject) {
                    // Log.d(TAG,"obj="+objects.get(key).toString());
                    JSONObject o = (JSONObject) objects.get(key);
                    JSONObject fields = o.getJSONObject("fields");
                    Log.d(TAG, "fields=" + fields.toString());

                    Gson gson = new Gson();
                    String k[] = key.split(":");
                    int id = Integer.parseInt(k[2]);
                    T jf = gson.fromJson(fields.toString(), T);
                    if (jf instanceof CMDBObject) {
                        ((CMDBObject) jf).id = id;
                    }
                    list.add(jf);
                }
            }
            Log.d(TAG, "code=" + jsonObject.getString("code"));
            Log.d(TAG, "message=" + jsonObject.getString("message"));

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } // endif (jsonObject != null)

    return list;

}