Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:org.openmrs.mobile.listeners.visit.FindVisitsByPatientUUIDListener.java

@Override
public void onResponse(JSONObject response) {
    mLogger.d(response.toString());

    try {//from   ww  w  . j  a  v a2  s. co m
        JSONArray visitResultJSON = response.getJSONArray(BaseManager.RESULTS_KEY);
        if (visitResultJSON.length() > 0) {
            for (int i = 0; i < visitResultJSON.length(); i++) {
                Visit visit = VisitMapper.map(visitResultJSON.getJSONObject(i));
                long visitId = visitDAO.getVisitsIDByUUID(visit.getUuid());

                if (visitId > 0) {
                    visitDAO.updateVisit(visit, visitId, mPatientID);
                } else {
                    visitDAO.saveVisit(visit, mPatientID);
                }
            }
        }
    } catch (JSONException e) {
        mErrorOccurred = true;
        mLogger.d(e.toString());
    } finally {
        updateData();
    }
}

From source file:de.decoit.visa.http.ajax.handlers.ConfigureHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Get the URI of the request and extract the query string from it
    QueryString queryParameters = new QueryString(he.getRequestURI());

    // Create StringBuilder for the response
    String response = null;/*from   ww  w.  ja v  a  2s  .com*/

    // Check if the query parameters are valid for this handler
    if (this.checkQueryParameters(queryParameters)) {
        try {
            // Close any existing connection to IO-Tool, this handler is
            // called on reload of the frontend
            try {
                TEBackend.closeIOConnector(false);
            } catch (IOToolException iote) {
                log.warn("Cannot close connection to the IO-Tool, using connection from old session");
            }

            // Process document root parameter
            String docRoot = queryParameters.get("documentRoot").get();

            // Set export directory
            StringBuilder sbExportPath = new StringBuilder(docRoot);
            if (!docRoot.endsWith("/")) {
                sbExportPath.append("/");
            }
            sbExportPath.append("export/");

            TEBackend.setExportPath(sbExportPath.toString());

            // Set import directory
            StringBuilder sbImportPath = new StringBuilder(docRoot);
            if (!docRoot.endsWith("/")) {
                sbImportPath.append("/");
            }
            sbImportPath.append("import/");

            TEBackend.setImportPath(sbImportPath.toString());

            // Process rows and cols parameter
            int rows = Integer.parseInt(queryParameters.get("rows").get());
            int cols = Integer.parseInt(queryParameters.get("cols").get());

            TEBackend.setGridDimensions(cols, rows);
            TEBackend.TOPOLOGY_STORAGE.getComponentGroupByName("0.0.0.0").setSubgridDimensions(cols, rows);

            // Process cell size parameter
            int cSize = Integer.parseInt(queryParameters.get("csize").get());

            TEBackend.setCellSize(cSize);

            // Process component margin parameter
            int compMargin = Integer.parseInt(queryParameters.get("compMargin").get());

            TEBackend.setComponentMargin(compMargin);

            // Return success response
            JSONObject rv = new JSONObject();
            rv.put("status", AJAXServer.AJAX_SUCCESS);
            rv.put("vsatemplates", TEBackend.RDF_MANAGER.vsaTemplatesToJSON());
            response = rv.toString();
        } catch (Throwable ex) {
            TEBackend.logException(ex, log);

            // Exception was thrown during configuration
            JSONObject rv = new JSONObject();

            try {
                rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
                rv.put("type", ex.getClass().getSimpleName());
                rv.put("message", ex.getMessage());
            } catch (JSONException exc) {
                /* Ignore */
            }

            response = rv.toString();
        }
    } else {
        // Missing or malformed query string, set response to error code
        JSONObject rv = new JSONObject();
        try {
            // Missing or malformed query string, set response to error code
            rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

From source file:com.imalu.alyou.activity.RegisterActivity.java

/**
 * /* w ww.  j a  v  a  2s . co  m*/
 * 
 * @param view
 */
public void register(View view) {

    final String pwd = passwordEditText.getText().toString().trim();
    String confirm_pwd = confirmPwdEditText.getText().toString().trim();
    if (TextUtils.isEmpty(pwd)) {
        Toast.makeText(this, "???", Toast.LENGTH_SHORT).show();
        passwordEditText.requestFocus();
        return;
    } else if (TextUtils.isEmpty(confirm_pwd)) {
        Toast.makeText(this, "???", Toast.LENGTH_SHORT).show();
        confirmPwdEditText.requestFocus();
        return;
    } else if (!pwd.equals(confirm_pwd)) {
        Toast.makeText(this, "????", Toast.LENGTH_SHORT).show();
        return;
    }

    RegisterRequest registerReq = new RegisterRequest();

    registerReq.setPassword(pwd);
    registerReq.setUsername(username);
    NetManager.execute(NetManager.REGISTER_REQUEST_OPERATION, registerReq, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            //pd.dismiss();
            Log.e("login_check", " response:" + response.toString());
            //Toast.makeText(getApplicationContext(), ": " + , 0).show();

            //RegisterResponse regResp = (RegisterResponse)response;

            // ?????
            //AlUApplication.getInstance().setUserName(username);
            //AlUApplication.getInstance().setPassword(password);

            /*runOnUiThread(new Runnable() {
               public void run() {
                  pd.setMessage("???...");
               }
            });*/
            try {

                RegisterResponse regResp = new RegisterResponse();
                regResp.setJsonObject(response);
                Log.e("AAAAAAAAAA", "" + regResp.getCode());
                if (regResp.getCode()) {
                    Toast.makeText(getApplicationContext(), "?", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), ": " + regResp.getInfo(),
                            Toast.LENGTH_SHORT).show();
                }
                // ** ?logout??
                // ** manually load all local groups and
                // conversations in case we are auto login
                //EMGroupManager.getInstance().loadAllGroups();
                //EMChatManager.getInstance().loadAllConversations();

                // demo??????username??
                /*List<String> usernames = EMContactManager.getInstance().getContactUserNames();
                EMLog.d("roster", "contacts size: " + usernames.size());
                        
                for (String username : usernames) {
                   User user = new User();
                   user.setUsername(username);
                   setUserHearder(username, user);
                   userlist.put(username, user);
                }*/
                /*Map<String, User> userlist = new HashMap<String, User>();
                // user""
                User newFriends = new User();
                newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
                newFriends.setNick("");
                newFriends.setHeader("");
                userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
                // "?"
                User groupUser = new User();
                groupUser.setUsername(Constant.GROUP_USERNAME);
                groupUser.setNick("?");
                groupUser.setHeader("");
                userlist.put(Constant.GROUP_USERNAME, groupUser);*/

                // 
                //AlUApplication.getInstance().setContactList(userlist);
                // db
                //UserDao dao = new UserDao(LoginActivity.this);
                //List<User> users = new ArrayList<User>(userlist.values());
                //dao.saveContactList(users);

                // ??(??groupidgroupname????members),sdkdb
                //EMGroupManager.getInstance().getGroupsFromServer();*/
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ": " + e.getMessage(), Toast.LENGTH_SHORT)
                        .show();
                //e.printStackTrace();
            }

            Log.e("login_check", "1111111111111111111");
            //?nickname ios?nick
            //boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(AlUApplication.currentUserNick);
            //if (!updatenick) {
            //   EMLog.e("LoginActivity", "update current user nick fail");
            //}

            //if (!LoginActivity.this.isFinishing())
            //pd.dismiss();
            // ?
            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
            finish();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject jsonObj) {
            //   Log.e("register", throwable.getMessage());
            finish();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, final String responseString,
                Throwable throwable) {
            runOnUiThread(new Runnable() {
                public void run() {
                    //pd.dismiss();
                    //Toast.makeText(getApplicationContext(), ": " + responseString, 0).show();
                    Log.e("register", responseString);
                    finish();
                }
            });
        }
    });

    //
    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage("...");
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sdk
                    EMChatManager.getInstance().createAccountOnServer(username, pwd);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!RegisterActivity.this.isFinishing())
                                pd.dismiss();
                            // ???
                            AlUApplication.getInstance().setUserName(username);
                            Toast.makeText(getApplicationContext(), "?", 0).show();
                            finish();
                        }
                    });
                } catch (final EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (!RegisterActivity.this.isFinishing())
                                pd.dismiss();
                            int errorCode = e.getErrorCode();
                            if (errorCode == EMError.NONETWORK_ERROR) {
                                Toast.makeText(getApplicationContext(), "?",
                                        Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_ALREADY_EXISTS) {
                                Toast.makeText(getApplicationContext(), "?",
                                        Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.UNAUTHORIZED) {
                                Toast.makeText(getApplicationContext(), "???",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), ": " + e.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        }).start();

    }
    //
}

From source file:com.android.volley.enhance.MultiPartJSONRequest.java

/**
 * Creates a new request with the given method.
 *
 * @param method        the request {@link Method} to use
 * @param url           URL to fetch the string at
 * @param listener      Listener to receive the String response
 * @param errorListener Error listener, or null to ignore errors
 *///w  w w.  j  ava 2  s .  c o m
public MultiPartJSONRequest(Context context, int method, String url, JSONObject jsonRequest,
        Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);

    mContext = context;
    mListener = listener;
}

From source file:org.wso2.carbon.connector.clevertim.UpdateCase.java

/**
 * Create JSON request for UpdateCase./*from ww w . j a v a2 s  .co m*/
 *
 * @return JSON payload.
 * @throws JSONException thrown when parsing JSON String.
 */
private String getJsonPayload() throws JSONException {

    JSONObject jsonPayload = new JSONObject();

    String id = (String) messageContext.getProperty(Constants.ID);
    if (id != null && !id.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.ID, id);
    }
    String name = (String) messageContext.getProperty(Constants.NAME);
    if (name != null && !name.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.NAME, name.trim());
    }
    String description = (String) messageContext.getProperty(Constants.DESCRIPTION);
    if (description != null && !description.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.DESCRIPTION, description.trim());
    }
    String leadUser = (String) messageContext.getProperty(Constants.LEAD_USER);
    if (leadUser != null && !leadUser.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.LEAD_USER, leadUser.trim());
    }
    String customer = (String) messageContext.getProperty(Constants.CUSTOMER);
    if (customer != null && !customer.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOMER, customer.trim());
    }
    String customFields = (String) messageContext.getProperty(Constants.CUSTOM_FIELDS);
    if (customFields != null && !customFields.isEmpty()) {

        jsonPayload.put(Constants.JSONKeys.CUSTOM_FIELD, new JSONObject(customFields));
    }
    String tags = (String) messageContext.getProperty(Constants.TAGS);
    if (tags != null && !tags.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TAGS, new JSONArray(tags));
    }

    return jsonPayload.toString();
}

From source file:com.citrus.sdk.CitrusActivity.java

private void fetchBill() {
    showDialog("Validating Payment Details. Please wait...", false);

    String billUrl = mPaymentType.getUrl();

    if (billUrl.contains("?")) {
        billUrl = billUrl + "&amount=" + mPaymentType.getAmount().getValue();
    } else {//  www  .  j  a  v a 2 s .  c o  m
        billUrl = billUrl + "?amount=" + mPaymentType.getAmount().getValue();
    }

    mCitrusClient.getBill(billUrl, mPaymentType.getAmount(), new com.citrus.sdk.Callback<PaymentBill>() {
        @Override
        public void success(PaymentBill paymentBill) {
            customParametersOriginalMap = paymentBill.getCustomParametersMap();
            JSONObject billJson = PaymentBill.toJSONObject(paymentBill);
            if (billJson != null) {
                proceedToPayment(billJson.toString());
            } else {
                TransactionResponse transactionResponse = new TransactionResponse(
                        TransactionResponse.TransactionStatus.FAILED,
                        ResponseMessages.ERROR_MESSAGE_INVALID_BILL, mTransactionId);
                sendResult(transactionResponse);
            }
        }

        @Override
        public void error(CitrusError error) {
            TransactionResponse transactionResponse = new TransactionResponse(
                    TransactionResponse.TransactionStatus.FAILED, error.getMessage(), mTransactionId);
            sendResult(transactionResponse);
        }
    });
}

From source file:com.trk.aboutme.facebook.TestSession.java

private static synchronized void retrieveTestAccountsForAppIfNeeded() {
    if (appTestAccounts != null) {
        return;/*w  w  w  .ja v  a 2s  . c o  m*/
    }

    appTestAccounts = new HashMap<String, TestAccount>();

    // The data we need is split across two different FQL tables. We construct two queries, submit them
    // together (the second one refers to the first one), then cross-reference the results.

    // Get the test accounts for this app.
    String testAccountQuery = String.format("SELECT id,access_token FROM test_account WHERE app_id = %s",
            testApplicationId);
    // Get the user names for those accounts.
    String userQuery = "SELECT uid,name FROM user WHERE uid IN (SELECT id FROM #test_accounts)";

    Bundle parameters = new Bundle();

    // Build a JSON string that contains our queries and pass it as the 'q' parameter of the query.
    JSONObject multiquery;
    try {
        multiquery = new JSONObject();
        multiquery.put("test_accounts", testAccountQuery);
        multiquery.put("users", userQuery);
    } catch (JSONException exception) {
        throw new FacebookException(exception);
    }
    parameters.putString("q", multiquery.toString());

    // We need to authenticate as this app.
    parameters.putString("access_token", getAppAccessToken());

    Request request = new Request(null, "fql", parameters, null);
    Response response = request.executeAndWait();

    if (response.getError() != null) {
        throw response.getError().getException();
    }

    FqlResponse fqlResponse = response.getGraphObjectAs(FqlResponse.class);

    GraphObjectList<FqlResult> fqlResults = fqlResponse.getData();
    if (fqlResults == null || fqlResults.size() != 2) {
        throw new FacebookException("Unexpected number of results from FQL query");
    }

    // We get back two sets of results. The first is from the test_accounts query, the second from the users query.
    Collection<TestAccount> testAccounts = fqlResults.get(0).getFqlResultSet().castToListOf(TestAccount.class);
    Collection<UserAccount> userAccounts = fqlResults.get(1).getFqlResultSet().castToListOf(UserAccount.class);

    // Use both sets of results to populate our static array of accounts.
    populateTestAccounts(testAccounts, userAccounts);

    return;
}

From source file:de.dmxcontrol.model.BaseModel.java

protected void SendData(String propertyType, Object valueType, Object value) throws JSONException {

    JSONArray array = new JSONArray();
    for (int i = 0; i < ReceivedData.get().Devices.size(); i++) {
        if (getEntitySelection().contains(EntityManager.Type.DEVICE,
                ReceivedData.get().Devices.get(i).getId())) {
            array.put(ReceivedData.get().Devices.get(i).guid);
        }//from  www  . ja v a2 s .  co  m
    }
    for (int i = 0; i < ReceivedData.get().Groups.size(); i++) {
        if (getEntitySelection().contains(EntityManager.Type.GROUP, ReceivedData.get().Groups.get(i).getId())) {
            array.put(ReceivedData.get().Groups.get(i).guid);
        }
    }

    JSONObject o = new JSONObject();
    o.put("Type", "PropertyValue");
    o.put("GUIDs", array);
    o.put("PropertyType", propertyType);
    o.put("ValueType", valueType);
    o.put("Value", value);

    ServiceFrontend.get().sendMessage(o.toString().getBytes());
}

From source file:org.smilec.smile.bu.json.CurrentMessageJSONParser.java

public static final String getStatus(InputStream is) throws DataAccessException {
    String s;/* w  w w .  j a v a2s.  c  o  m*/
    try {
        s = IOUtil.loadContent(is, ENCODING);

        JSONObject json = new JSONObject(s);

        String type = "";
        if (!json.toString().equals("{}")) {
            type = json.getString(TYPE);
        }

        return type;
    } catch (IOException e) {
        throw new DataAccessException(e);
    } catch (JSONException e) {
        throw new DataAccessException(e);
    }
}

From source file:tv.matchstick.demo.dashboard.DashBoardChannel.java

public final void show(FlintManager apiClient, String user, String info) {
    try {/*from  w w  w.  j  a va 2  s .  c o  m*/
        Log.d(TAG, "show: " + info);
        JSONObject payload = new JSONObject();
        payload.put(KEY_COMMAND, KEY_SHOW);
        payload.put(KEY_USER, user);
        payload.put(KEY_INFO, info);
        sendMessage(apiClient, payload.toString());
    } catch (JSONException e) {
        Log.e(TAG, "Cannot create object to show file", e);
    }
}