Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:org.wso2.emm.agent.services.ProcessMessage.java

private void messageExecute(String msg) {
    stillProcessing = true;//from  w ww  . j  a v a2  s .  c  om
    JSONArray repArray = new JSONArray();
    JSONObject jsReply = null;
    String msgId = "";

    JSONArray dataReply = null;
    try {
        JSONArray jArr = new JSONArray(msg.trim());
        for (int i = 0; i < jArr.length(); i++) {
            JSONArray innerArr = new JSONArray(jArr.getJSONObject(i).getString("data"));
            String featureCode = jArr.getJSONObject(i).getString("code");
            dataReply = new JSONArray();
            jsReply = new JSONObject();
            jsReply.put("code", featureCode);

            for (int x = 0; x < innerArr.length(); x++) {
                msgId = innerArr.getJSONObject(x).getString("messageId");
                jsReply.put("messageId", msgId);

                if (featureCode.equals(CommonUtilities.OPERATION_POLICY_BUNDLE)) {
                    SharedPreferences mainPrefp = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);

                    Editor editorp = mainPrefp.edit();
                    editorp.putString("policy", "");
                    editorp.commit();

                    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
                    Editor editor = mainPref.edit();
                    String arrToPut = innerArr.getJSONObject(0).getJSONArray("data").toString();

                    editor.putString("policy", arrToPut);
                    editor.commit();
                }

                String msgData = innerArr.getJSONObject(x).getString("data");
                JSONObject dataObj = new JSONObject("{}");
                operation = new Operation(context);
                if (featureCode.equalsIgnoreCase(CommonUtilities.OPERATION_POLICY_REVOKE)) {
                    operation.operate(featureCode, jsReply);
                    jsReply.put("status", msgId);
                } else {
                    if (msgData.charAt(0) == '[') {
                        JSONArray dataArr = new JSONArray(msgData);
                        for (int a = 0; a < dataArr.length(); a++) {
                            JSONObject innterDataObj = dataArr.getJSONObject(a);
                            featureCode = innterDataObj.getString("code");
                            String dataTemp = innterDataObj.getString("data");
                            if (!dataTemp.isEmpty() && dataTemp != null && !dataTemp.equalsIgnoreCase("null"))
                                dataObj = innterDataObj.getJSONObject("data");

                            dataReply = operation.operate(featureCode, dataObj);
                            //dataReply.put(resultJson);
                        }
                    } else {
                        if (!msgData.isEmpty() && msgData != null && !msgData.equalsIgnoreCase("null"))
                            if (msgData.charAt(0) == '{') {
                                dataObj = new JSONObject(msgData);
                            }
                        dataReply = operation.operate(featureCode, dataObj);
                        //dataReply.put(resultJson);
                    }
                }

            }
            jsReply.put("data", dataReply);
            repArray.put(jsReply);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (Operation.enterpriseWipe == false) {
            SharedPreferences mainPref = context.getSharedPreferences(
                    context.getResources().getString(R.string.shared_pref_package), Context.MODE_PRIVATE);
            String regId = mainPref.getString(context.getResources().getString(R.string.shared_pref_regId), "");
            PayloadParser ps = new PayloadParser();

            replyPayload = ps.generateReply(repArray, regId);
            if (CommonUtilities.DEBUG_MODE_ENABLED) {
                Log.e(TAG, "replyPlayload -" + replyPayload);
            }
            stillProcessing = false;
            getOperations(replyPayload);
        }

    }

}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String Login(String host, String username, String password, String token) throws JSONException {
    if (password == null)
        Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username);
    else//from  w  ww.ja  v a 2s  .co m
        Log.i(TAG, "Login by password, host: " + host + ", username: " + username);

    try {
        URL url = new URL("https://" + host + URL_LOGIN);

        HttpsURLConnection http = CreateConnection(url);

        if (password != null) {
            // Setup HTTPS POST request
            String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password="
                    + URLEncoder.encode(password, "UTF-8") + "&submit=submit";

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length));

            // Write request
            DataOutputStream outputStream = new DataOutputStream(http.getOutputStream());
            outputStream.writeBytes(urlParams);
            outputStream.flush();
            outputStream.close();
        } else {
            http.setRequestMethod("GET");
            http.setRequestProperty("Cookie", token);
        }

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            final String cookie = http.getHeaderField("Set-Cookie");
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie);

            if (result == RESULT_SUCCESS) {
                if (cookie != null)
                    return cookie;
                else
                    return token;
            }

            // All other results are failures...
            return "";
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
    }

    Log.i(TAG, "Malformed result");
    return "";
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static public String GetSystemInfo(String host, String token, long last_sample)
        throws JSONException, ParseException, IOException, AuthenticationException {
    try {//from  w w  w.j a  va2 s . c  o m
        URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample);
        Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url);

        HttpsURLConnection http = CreateConnection(url);

        http.setRequestMethod("GET");
        http.setRequestProperty("Cookie", token);

        final StringBuffer response = ProcessRequest(http);

        // Process response
        JSONObject json_data = null;
        try {
            //Log.i(TAG, "response: " + response.toString());
            json_data = new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return "";
        }
        if (json_data.has("result")) {
            Integer result = RESULT_UNKNOWN;
            try {
                result = Integer.valueOf(json_data.getString("result"));
            } catch (NumberFormatException e) {
            }

            Log.d(TAG, "result: " + result.toString());

            if (result == RESULT_SUCCESS && json_data.has("data")) {
                //Log.i(TAG, "data: " + json_data.getString("data"));
                return json_data.getString("data");
            }

            if (result == RESULT_ACCESS_DENIED)
                throw new AuthenticationException();

            // New cookies?
            final String cookie = http.getHeaderField("Set-Cookie");
            if (cookie != null) {
                Log.d(TAG, "New cookie!");
            }

            // All other results are failures...
            throw new IOException();
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException", e);
        throw new ParseException();
    }

    Log.i(TAG, "Malformed result");
    throw new IOException();
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

private void parseArgs(JSONArray args) {
    Log.d(TAG, "Execute args: " + args.toString());
    if (args.length() > 0) {
        try {//from  w  w w  .  j  av  a  2s  . c  om
            final JSONObject obj = args.getJSONObject(0);
            _minTime = obj.getLong("minTime");
            _minDistance = obj.getLong("minDistance");
            _noWarn = obj.getBoolean("noWarn");
            _providers = obj.getString("providers");
            _useCache = obj.getBoolean("useCache");
            _returnSatelliteData = obj.getBoolean("satelliteData");
            _buffer = obj.getBoolean("buffer");
            _signalStrength = obj.getBoolean("signalStrength");
            _bufferSize = obj.getInt("bufferSize");

        } catch (Exception exc) {
            Log.d(TAG, ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
            sendCallback(PluginResult.Status.ERROR,
                    ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
        }
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;// w w  w . j  a  va  2s .  c  om
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFolders() {
    //File.deleteAllFolders();

    URL urlO = null;/*from   w w  w .  ja  v a2  s. c  o m*/
    try {
        urlO = new URL(folderUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(folderJson.get("_id").toString());

                if (file == null) {
                    file = new File(folderJson, true);
                } else {
                    file.setName(folderJson.getString("name"));
                    file.setPath(folderJson.getString("path"));
                    file.setCreationDate(folderJson.getString("creationDate"));
                    file.setLastModification(folderJson.getString("lastModification"));
                    file.setTags(folderJson.getString("tags"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing remote folder : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName()));

                file.save();
                createFolder(file.getPath(), file.getName());

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:com.wglxy.example.dashL.SearchActivity.java

ArrayList<User> parseJSON(String results) throws JSONException, NullPointerException {
    ArrayList<User> list = new ArrayList<User>();
    JSONObject jsonResult = new JSONObject(results);
    int status = jsonResult.getInt("status");
    int numResults = jsonResult.getInt("numResults");

    if (status != 200 && numResults <= 0)
        return list;
    else {/*from  w  ww.j av  a2  s  .  c o  m*/
        JSONArray arr = jsonResult.getJSONArray("results");
        Log.e(LOG_TAG, "results: " + arr.length());

        for (int i = 0; i < arr.length(); i++) {
            JSONObject jsonObject = arr.getJSONObject(i);
            User user = new User();
            int id = jsonObject.getInt("id");
            String email = jsonObject.getString("email");
            String first_name = jsonObject.getString("first_name");
            String last_name = jsonObject.getString("last_name");
            String business_name = jsonObject.getString("business_name");
            String services = jsonObject.getString("services");
            String address = jsonObject.getString("address");
            int stars = jsonObject.getInt("stars");
            String image = Constants.API_BASE_IMAGE_URL + jsonObject.getString("image");
            Log.e(LOG_TAG, "image: " + image);

            user.setId(id);
            user.setEmail(email);
            user.setFirst_name(first_name);
            user.setLast_name(last_name);
            user.setBusiness_name(business_name);
            user.setAddress(address);
            user.setServices(services);
            user.setStars(stars);
            user.setImage(image);

            list.add(user);
        }
        return list;
    }
}

From source file:com.brennasoft.facebookdashclockextension.fbclient.NotificationsRequest.java

private NotificationsResponse parseResponse(Response response) {
    NotificationsResponse notificationsResponse = new NotificationsResponse();
    GraphObject graphObject = response.getGraphObject();
    try {//from  ww w .  j a v a2s .  com
        JSONArray data = graphObject.getInnerJSONObject().getJSONArray("data");
        notificationsResponse.count = data.length();
        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i);
            notificationsResponse.addNotification(object.getString("notification_id"),
                    object.getLong("updated_time"), object.getString("title_text"));
        }
        notificationsResponse.success = true;
    } catch (JSONException e) {
        Crashlytics.logException(e);
    }
    return notificationsResponse;
}

From source file:org.hydracache.client.partition.PartitionAwareClient.java

@Override
public synchronized List<Identity> listNodes() throws Exception {
    log.info("Retrieving list of nodes.");

    RequestMessage requestMessage = new RequestMessage();
    requestMessage.setMethod(GET);/*from w ww  . j a va  2s . c om*/
    requestMessage.setPath("registry");

    // Pick a random node to connect to
    Random rnd = new Random();
    int nextInt = rnd.nextInt(seedServerIds.size());
    Identity identity = seedServerIds.get(nextInt);

    ResponseMessage responseMessage = messager.sendMessage(identity, nodePartition, requestMessage);

    if (responseMessage == null)
        throw new ClientException("Failed to retrieve node registry.");

    List<Identity> identities = new LinkedList<Identity>();

    String registry = new String(responseMessage.getResponseBody());
    log.debug("Received registry: " + registry);
    JSONArray seedServerArray = new JSONArray(registry);
    for (int i = 0; i < seedServerArray.length(); i++) {
        JSONObject seedServer = seedServerArray.getJSONObject(i);

        identities.add(new Identity(InetAddress.getByName(seedServer.getString(IP)), seedServer.getInt(PORT)));
    }
    return identities;
}

From source file:com.tune.reporting.base.endpoints.EndpointBase.java

/**
 * Fetch all fields from model and related models of this endpoint.
 *
 * @return Map All endpoint fields.//from   w  w  w  .  j ava  2  s  . c  o  m
 *
 * @throws TuneServiceException If service fails to handle post request.
 * @throws TuneSdkException If error within SDK.
 */
protected final Map<String, Map<String, String>> getEndpointFields()
        throws TuneServiceException, TuneSdkException {
    Map<String, String> mapQueryString = new HashMap<String, String>();
    mapQueryString.put("controllers", this.controller);
    mapQueryString.put("details", "modelName,fields");

    TuneServiceClient client = new TuneServiceClient("apidoc", "get_controllers", this.getAuthKey(),
            this.getAuthType(), mapQueryString);

    client.call();

    TuneServiceResponse response = client.getResponse();
    int httpCode = response.getHttpCode();
    JSONArray data = (JSONArray) response.getData();

    if (httpCode != HTTP_STATUS_OK) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(
                String.format("Connection failure '%s': Request: '%s'", httpCode, requestUrl));
    }

    if ((null == data) || (data.length() == 0)) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(String.format("Failed to get fields for endpoint: '%s', Request: '%s'",
                this.controller, requestUrl));
    }

    try {
        JSONObject endpointMetaData = data.getJSONObject(0);

        this.endpointModelName = endpointMetaData.getString("modelName");
        JSONArray endpointFields = endpointMetaData.getJSONArray("fields");

        Map<String, Map<String, String>> fieldsFound = new HashMap<String, Map<String, String>>();
        Map<String, Set<String>> relatedFields = new HashMap<String, Set<String>>();

        for (int i = 0; i < endpointFields.length(); i++) {
            JSONObject endpointField = endpointFields.getJSONObject(i);
            Boolean fieldRelated = endpointField.getBoolean("related");
            String fieldType = endpointField.getString("type");
            String fieldName = endpointField.getString("name");
            Boolean fieldDefault = endpointField.has("fieldDefault") ? endpointField.getBoolean("fieldDefault")
                    : false;

            if (fieldRelated) {
                if (fieldType.equals("property")) {
                    String relatedProperty = fieldName;
                    if (!relatedFields.containsKey(relatedProperty)) {
                        relatedFields.put(relatedProperty, new HashSet<String>());
                    }
                    continue;
                }

                String[] fieldRelatedNameParts = fieldName.split("\\.");
                String relatedProperty = fieldRelatedNameParts[0];
                String relatedFieldName = fieldRelatedNameParts[1];

                if (!relatedFields.containsKey(relatedProperty)) {
                    relatedFields.put(relatedProperty, new HashSet<String>());
                }

                Set<String> relatedFieldFields = relatedFields.get(relatedProperty);
                relatedFieldFields.add(relatedFieldName);
                relatedFields.put(relatedProperty, relatedFieldFields);
                continue;
            }

            Map<String, String> fieldFoundInfo = new HashMap<String, String>();
            fieldFoundInfo.put("default", Boolean.toString(fieldDefault));
            fieldFoundInfo.put("related", "false");
            fieldsFound.put(fieldName, fieldFoundInfo);
        }

        Map<String, Map<String, String>> fieldsFoundMerged = new HashMap<String, Map<String, String>>();
        Iterator<Map.Entry<String, Map<String, String>>> it = fieldsFound.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, Map<String, String>> pairs = it.next();

            String fieldFoundName = pairs.getKey();
            Map<String, String> fieldFoundInfo = pairs.getValue();

            fieldsFoundMerged.put(fieldFoundName, fieldFoundInfo);

            if ((fieldFoundName != "_id") && fieldFoundName.endsWith("_id")) {
                String relatedProperty = fieldFoundName.substring(0, fieldFoundName.length() - 3);
                if (relatedFields.containsKey(relatedProperty)
                        && !relatedFields.get(relatedProperty).isEmpty()) {
                    for (String relatedFieldName : relatedFields.get(relatedProperty)) {
                        if ("id" == relatedFieldName) {
                            continue;
                        }
                        String relatedPropertyFieldName = String.format("%s.%s", relatedProperty,
                                relatedFieldName);
                        Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                        relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                        relatedPropertyFieldInfo.put("related", "true");
                        fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                    }
                } else {
                    Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                    relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                    relatedPropertyFieldInfo.put("related", "true");
                    String relatedPropertyFieldName = String.format("%s.%s", relatedProperty, "name");
                    fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                }
            }
        }

        this.endpointFields = fieldsFoundMerged;

    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    return this.endpointFields;
}