Advertisement
Guest User

Untitled

a guest
Jan 15th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.50 KB | None | 0 0
  1. /*
  2. * Copyright 2013-2017 Amazon.com,
  3. * Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Licensed under the Amazon Software License (the "License").
  6. * You may not use this file except in compliance with the
  7. * License. A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/asl/
  10. *
  11. * or in the "license" file accompanying this file. This file is
  12. * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, express or implied. See the License
  14. * for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17.  
  18. package com.amazonaws.youruserpools;
  19.  
  20. import android.app.DownloadManager;
  21. import android.app.ProgressDialog;
  22. import android.content.DialogInterface;
  23. import android.content.Intent;
  24. import android.content.pm.ActivityInfo;
  25. import android.os.Bundle;
  26. import android.support.design.widget.NavigationView;
  27. import android.support.v4.widget.DrawerLayout;
  28. import android.support.v7.app.ActionBarDrawerToggle;
  29. import android.support.v7.app.AlertDialog;
  30. import android.support.v7.app.AppCompatActivity;
  31. import android.support.v7.widget.Toolbar;
  32. import android.util.Log;
  33. import android.view.Menu;
  34. import android.view.MenuItem;
  35. import android.view.View;
  36. import android.widget.AdapterView;
  37. import android.widget.ArrayAdapter;
  38. import android.widget.EditText;
  39. import android.widget.ImageView;
  40. import android.widget.LinearLayout;
  41. import android.widget.ListView;
  42. import android.widget.TextView;
  43. import android.widget.Toast;
  44.  
  45. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice;
  46. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
  47. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserAttributes;
  48. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails;
  49. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails;
  50. import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
  51. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler;
  52. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler;
  53. import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.UpdateAttributesHandler;
  54. import com.amazonaws.youruserpools.CognitoYourUserPoolsDemo.R;
  55. import com.android.volley.Request;
  56. import com.android.volley.RequestQueue;
  57. import com.android.volley.Response;
  58. import com.android.volley.VolleyError;
  59. import com.android.volley.toolbox.JsonArrayRequest;
  60. import com.android.volley.toolbox.JsonObjectRequest;
  61. import com.android.volley.toolbox.Volley;
  62.  
  63. import org.json.JSONArray;
  64. import org.json.JSONException;
  65. import org.json.JSONObject;
  66.  
  67. import java.util.ArrayList;
  68. import java.util.List;
  69.  
  70. public class UserActivity extends AppCompatActivity {
  71. private final String TAG="UserActivity";
  72.  
  73. private NavigationView nDrawer;
  74. private DrawerLayout mDrawer;
  75. private ActionBarDrawerToggle mDrawerToggle;
  76. private Toolbar toolbar;
  77. private AlertDialog userDialog;
  78. private ProgressDialog waitDialog;
  79. private ListView attributesList;
  80.  
  81. // Cognito user objects
  82. private CognitoUser user;
  83. private CognitoUserSession session;
  84. private CognitoUserDetails details;
  85.  
  86. // User details
  87. private String username;
  88.  
  89. // To track changes to user details
  90. private final List<String> attributesToDelete = new ArrayList<>();
  91.  
  92. @Override
  93. protected void onCreate(Bundle savedInstanceState) {
  94. super.onCreate(savedInstanceState);
  95. setContentView(R.layout.activity_user);
  96. Log.d("t","help us");
  97. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  98.  
  99. // Set toolbar for this screen
  100. toolbar = (Toolbar) findViewById(R.id.main_toolbar);
  101. toolbar.setTitle("");
  102. TextView main_title = (TextView) findViewById(R.id.main_toolbar_title);
  103. main_title.setText("Account");
  104. setSupportActionBar(toolbar);
  105.  
  106. // Set navigation drawer for this screen
  107. mDrawer = (DrawerLayout) findViewById(R.id.user_drawer_layout);
  108. mDrawerToggle = new ActionBarDrawerToggle(this,mDrawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
  109. mDrawer.addDrawerListener(mDrawerToggle);
  110. mDrawerToggle.syncState();
  111.  
  112. nDrawer = (NavigationView) findViewById(R.id.nav_view);
  113. setNavDrawer();
  114. init();
  115. View navigationHeader = nDrawer.getHeaderView(0);
  116. TextView navHeaderSubTitle = (TextView) navigationHeader.findViewById(R.id.textViewNavUserSub);
  117. navHeaderSubTitle.setText(username);
  118. }
  119.  
  120. @Override
  121. public boolean onCreateOptionsMenu(Menu menu) {
  122. // Inflate the menu; this adds items to the action bar if it is present.
  123. getMenuInflater().inflate(R.menu.activity_user_menu, menu);
  124. return true;
  125. }
  126.  
  127. @Override
  128. public boolean onOptionsItemSelected(MenuItem item) {
  129. // Find which menu item was selected
  130. int menuItem = item.getItemId();
  131.  
  132. // Do the task
  133. if(menuItem == R.id.user_update_attribute) {
  134. //updateAllAttributes();
  135. showWaitDialog("Updating...");
  136. getDetails();
  137. return true;
  138. }
  139.  
  140. return super.onOptionsItemSelected(item);
  141. }
  142.  
  143. @Override
  144. public void onBackPressed() {
  145. exit();
  146. }
  147.  
  148. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  149. super.onActivityResult(requestCode, resultCode, data);
  150.  
  151. switch (requestCode) {
  152. case 20:
  153. // Settings
  154. if(resultCode == RESULT_OK) {
  155. boolean refresh = data.getBooleanExtra("refresh", true);
  156. if (refresh) {
  157. showAttributes();
  158. }
  159. }
  160. break;
  161. case 21:
  162. // Verify attributes
  163. if(resultCode == RESULT_OK) {
  164. boolean refresh = data.getBooleanExtra("refresh", true);
  165. if (refresh) {
  166. showAttributes();
  167. }
  168. }
  169. break;
  170. case 22:
  171. // Add attributes
  172. if(resultCode == RESULT_OK) {
  173. boolean refresh = data.getBooleanExtra("refresh", true);
  174. if (refresh) {
  175. showAttributes();
  176. }
  177. }
  178. break;
  179. }
  180. }
  181.  
  182. // Handle when the a navigation item is selected
  183. private void setNavDrawer() {
  184. nDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
  185. @Override
  186. public boolean onNavigationItemSelected(MenuItem item) {
  187. performAction(item);
  188. return true;
  189. }
  190. });
  191. }
  192.  
  193. // Perform the action for the selected navigation item
  194. private void performAction(MenuItem item) {
  195. // Close the navigation drawer
  196. mDrawer.closeDrawers();
  197.  
  198. // Find which item was selected
  199. switch(item.getItemId()) {
  200. case R.id.nav_user_add_attribute:
  201. // Add a new attribute
  202. addAttribute();
  203. break;
  204.  
  205. case R.id.nav_user_change_password:
  206. // Change password
  207. changePassword();
  208. break;
  209. case R.id.nav_user_verify_attribute:
  210. // Confirm new user
  211. // confirmUser();
  212. attributesVerification();
  213. break;
  214. case R.id.nav_user_settings:
  215. // Show user settings
  216. showSettings();
  217. break;
  218. case R.id.nav_user_sign_out:
  219. // Sign out from this account
  220. signOut();
  221. break;
  222. case R.id.nav_user_trusted_devices:
  223. showTrustedDevices();
  224. break;
  225. case R.id.nav_user_about:
  226. // For the inquisitive
  227. Intent aboutAppActivity = new Intent(this, AboutApp.class);
  228. startActivity(aboutAppActivity);
  229. break;
  230. }
  231. }
  232.  
  233. // Get user details from CIP service
  234. private void getDetails() {
  235. AppHelper.getPool().getUser(username).getDetailsInBackground(detailsHandler);
  236. }
  237.  
  238. // Show user attributes from CIP service
  239. private void showAttributes() {
  240. Log.d("Jimmy","listView");
  241. /*
  242. final UserAttributesAdapter attributesAdapter = new UserAttributesAdapter(getApplicationContext());
  243. final ListView attributesListView;
  244. attributesListView = (ListView) findViewById(R.id.listViewUserAttributes);
  245. attributesListView.setAdapter(attributesAdapter);
  246. attributesList = attributesListView;
  247.  
  248.  
  249. attributesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  250. @Override
  251. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  252. TextView data = (TextView) view.findViewById(R.id.editTextUserDetailInput);
  253. String attributeType = data.getHint().toString();
  254. String attributeValue = data.getText().toString();
  255. showUserDetail(attributeType, attributeValue);
  256. }
  257. });
  258.  
  259. */
  260. final ListView attributesListView;
  261. attributesListView = (ListView) findViewById(R.id.listViewUserAttributes);
  262. final List<String> your_array_list = new ArrayList<String>();
  263.  
  264.  
  265. final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
  266. this,
  267. android.R.layout.simple_list_item_1,
  268. your_array_list );
  269.  
  270. attributesListView.setAdapter(arrayAdapter);
  271.  
  272. //setContentView(R.layout.activity_user);
  273. final TextView display = (TextView) findViewById(R.id.textViewUserDetailMessage);
  274.  
  275.  
  276.  
  277. //Request
  278. //final String url2 = "https://0d1mc6d1fk.execute-api.us-west-2.amazonaws.com/production/playlists?userId=1";
  279. final String url2 = "https://3l1ezvcp0c.execute-api.us-west-2.amazonaws.com/production/playlistnames";
  280. final String url3 = "https://3l1ezvcp0c.execute-api.us-west-2.amazonaws.com/production/playlists";
  281. final RequestQueue queue = Volley.newRequestQueue(this);
  282.  
  283. JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
  284. Request.Method.GET,
  285. url2,
  286. null,
  287. new Response.Listener<JSONArray>() {
  288. @Override
  289. public void onResponse(JSONArray response) {
  290. // Do something with response
  291. //mTextView.setText(response.toString());
  292.  
  293. // Process the JSON
  294. try{
  295. // Loop through the array elements
  296. for(int i=0;i<response.length();i++){
  297. // Get current json object
  298. JSONObject student = response.getJSONObject(i);
  299. your_array_list.add(student.getString("playlistName"));
  300. Log.d("Jimmy~~~~~~~~~~~~~~~~~ ",student.toString());
  301. }
  302. }catch (JSONException e){
  303. e.printStackTrace();
  304. }
  305. attributesListView.setAdapter(arrayAdapter);
  306.  
  307. attributesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  308. @Override
  309. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  310. String playlistname = your_array_list.get(position);
  311.  
  312. JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
  313. Request.Method.GET,
  314. url3,
  315. null,
  316. new Response.Listener<JSONObject>() {
  317. @Override
  318. public void onResponse(JSONObject response) {
  319. // Do something with response
  320. //mTextView.setText(response.toString());
  321.  
  322. // Process the JSON
  323. try{
  324. JSONObject songs = response.getJSONObject("Songs");
  325. your_array_list.clear();
  326. for (int i=0; i<songs.names().length(); i++){
  327. your_array_list.add(songs.names().getString(i).toString());
  328. }
  329. }catch (JSONException e){
  330. e.printStackTrace();
  331. }
  332. attributesListView.setAdapter(arrayAdapter);
  333. }
  334. },
  335. new Response.ErrorListener(){
  336. @Override
  337. public void onErrorResponse(VolleyError error){
  338. // Do something when error occurred
  339. }
  340. }
  341. );
  342.  
  343. // Add JsonArrayRequest to the RequestQueue
  344. queue.add(jsonObjectRequest);
  345.  
  346. attributesListView.setAdapter(arrayAdapter);
  347. }
  348. });
  349.  
  350. }
  351. },
  352. new Response.ErrorListener(){
  353. @Override
  354. public void onErrorResponse(VolleyError error){
  355. // Do something when error occurred
  356. }
  357. }
  358. );
  359.  
  360. // Add JsonArrayRequest to the RequestQueue
  361. queue.add(jsonArrayRequest);
  362.  
  363. }
  364.  
  365. // Update attributes
  366. private void updateAttribute(String attributeType, String attributeValue) {
  367.  
  368. if(attributeType == null || attributeType.length() < 1) {
  369. return;
  370. }
  371. CognitoUserAttributes updatedUserAttributes = new CognitoUserAttributes();
  372. updatedUserAttributes.addAttribute(attributeType, attributeValue);
  373. Toast.makeText(getApplicationContext(), attributeType + ": " + attributeValue, Toast.LENGTH_LONG);
  374. showWaitDialog("Updating...");
  375. AppHelper.getPool().getUser(AppHelper.getCurrUser()).updateAttributesInBackground(updatedUserAttributes, updateHandler);
  376. }
  377.  
  378. // Show user MFA Settings
  379. private void showSettings() {
  380. Intent userSettingsActivity = new Intent(this,SettingsActivity.class);
  381. startActivityForResult(userSettingsActivity, 20);
  382. }
  383.  
  384. // Add a new attribute
  385. private void addAttribute() {
  386. Intent addAttrbutesActivity = new Intent(this,AddAttributeActivity.class);
  387. startActivityForResult(addAttrbutesActivity, 22);
  388. }
  389.  
  390. // Delete attribute
  391. private void deleteAttribute(String attributeName) {
  392. showWaitDialog("Deleting...");
  393. List<String> attributesToDelete = new ArrayList<>();
  394. attributesToDelete.add(attributeName);
  395. AppHelper.getPool().getUser(AppHelper.getCurrUser()).deleteAttributesInBackground(attributesToDelete, deleteHandler);
  396. }
  397.  
  398. // Change user password
  399. private void changePassword() {
  400. Intent changePssActivity = new Intent(this, ChangePasswordActivity.class);
  401. startActivity(changePssActivity);
  402. }
  403.  
  404. // Verify attributes
  405. private void attributesVerification() {
  406. Intent attrbutesActivity = new Intent(this,VerifyActivity.class);
  407. startActivityForResult(attrbutesActivity, 21);
  408. }
  409.  
  410. private void showTrustedDevices() {
  411. Intent trustedDevicesActivity = new Intent(this, DeviceSettings.class);
  412. startActivity(trustedDevicesActivity);
  413. }
  414.  
  415. // Sign out user
  416. private void signOut() {
  417. user.signOut();
  418. exit();
  419. }
  420.  
  421. // Initialize this activity
  422. private void init() {
  423. // Get the user name
  424. Bundle extras = getIntent().getExtras();
  425. username = AppHelper.getCurrUser();
  426. user = AppHelper.getPool().getUser(username);
  427. getDetails();
  428. }
  429.  
  430. GetDetailsHandler detailsHandler = new GetDetailsHandler() {
  431. @Override
  432. public void onSuccess(CognitoUserDetails cognitoUserDetails) {
  433. closeWaitDialog();
  434. // Store details in the AppHandler
  435. AppHelper.setUserDetails(cognitoUserDetails);
  436. showAttributes();
  437. // Trusted devices?
  438. handleTrustedDevice();
  439. }
  440.  
  441. @Override
  442. public void onFailure(Exception exception) {
  443. closeWaitDialog();
  444. showDialogMessage("Could not fetch user details!", AppHelper.formatException(exception), true);
  445. }
  446. };
  447.  
  448. private void handleTrustedDevice() {
  449. CognitoDevice newDevice = AppHelper.getNewDevice();
  450. if (newDevice != null) {
  451. AppHelper.newDevice(null);
  452. trustedDeviceDialog(newDevice);
  453. }
  454. }
  455.  
  456. private void updateDeviceStatus(CognitoDevice device) {
  457. device.rememberThisDeviceInBackground(trustedDeviceHandler);
  458. }
  459.  
  460. private void trustedDeviceDialog(final CognitoDevice newDevice) {
  461. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  462. builder.setTitle("Remember this device?");
  463. //final EditText input = new EditText(UserActivity.this);
  464.  
  465. LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  466. LinearLayout.LayoutParams.MATCH_PARENT,
  467. LinearLayout.LayoutParams.MATCH_PARENT);
  468.  
  469. //input.setLayoutParams(lp);
  470. //input.requestFocus();
  471. //builder.setView(input);
  472.  
  473. builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  474. @Override
  475. public void onClick(DialogInterface dialog, int which) {
  476. try {
  477. //String newValue = input.getText().toString();
  478. showWaitDialog("Remembering this device...");
  479. updateDeviceStatus(newDevice);
  480. userDialog.dismiss();
  481. } catch (Exception e) {
  482. // Log failure
  483. }
  484. }
  485. }).setNegativeButton("No", new DialogInterface.OnClickListener() {
  486. @Override
  487. public void onClick(DialogInterface dialog, int which) {
  488. try {
  489. userDialog.dismiss();
  490. } catch (Exception e) {
  491. // Log failure
  492. }
  493. }
  494. });
  495. userDialog = builder.create();
  496. userDialog.show();
  497. }
  498.  
  499. // Callback handlers
  500.  
  501. UpdateAttributesHandler updateHandler = new UpdateAttributesHandler() {
  502. @Override
  503. public void onSuccess(List<CognitoUserCodeDeliveryDetails> attributesVerificationList) {
  504. // Update successful
  505. if(attributesVerificationList.size() > 0) {
  506. showDialogMessage("Updated", "The updated attributes has to be verified", false);
  507. }
  508. getDetails();
  509. }
  510.  
  511. @Override
  512. public void onFailure(Exception exception) {
  513. // Update failed
  514. closeWaitDialog();
  515. showDialogMessage("Update failed", AppHelper.formatException(exception), false);
  516. }
  517. };
  518.  
  519. GenericHandler deleteHandler = new GenericHandler() {
  520. @Override
  521. public void onSuccess() {
  522. closeWaitDialog();
  523. // Attribute was deleted
  524. Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT);
  525.  
  526. // Fetch user details from the the service
  527. getDetails();
  528. }
  529.  
  530. @Override
  531. public void onFailure(Exception e) {
  532. closeWaitDialog();
  533. // Attribute delete failed
  534. showDialogMessage("Delete failed", AppHelper.formatException(e), false);
  535.  
  536. // Fetch user details from the service
  537. getDetails();
  538. }
  539. };
  540.  
  541. GenericHandler trustedDeviceHandler = new GenericHandler() {
  542. @Override
  543. public void onSuccess() {
  544. // Close wait dialog
  545. closeWaitDialog();
  546. }
  547.  
  548. @Override
  549. public void onFailure(Exception exception) {
  550. closeWaitDialog();
  551. showDialogMessage("Failed to update device status", AppHelper.formatException(exception), true);
  552. }
  553. };
  554.  
  555. private void showUserDetail(final String attributeType, final String attributeValue) {
  556. Log.d("Jimmy","Alert box");
  557. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  558. builder.setTitle(attributeType);
  559. final EditText input = new EditText(UserActivity.this);
  560. input.setText(attributeValue);
  561.  
  562. LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  563. LinearLayout.LayoutParams.MATCH_PARENT,
  564. LinearLayout.LayoutParams.MATCH_PARENT);
  565.  
  566. input.setLayoutParams(lp);
  567. input.requestFocus();
  568. builder.setView(input);
  569.  
  570. builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
  571. @Override
  572. public void onClick(DialogInterface dialog, int which) {
  573. try {
  574. String newValue = input.getText().toString();
  575. if(!newValue.equals(attributeValue)) {
  576. showWaitDialog("Updating...");
  577. updateAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType), newValue);
  578. }
  579. userDialog.dismiss();
  580. } catch (Exception e) {
  581. // Log failure
  582. }
  583. }
  584. }).setPositiveButton("Delete", new DialogInterface.OnClickListener() {
  585. @Override
  586. public void onClick(DialogInterface dialog, int which) {
  587. try {
  588. userDialog.dismiss();
  589. deleteAttribute(AppHelper.getSignUpFieldsC2O().get(attributeType));
  590. } catch (Exception e) {
  591. // Log failure
  592. }
  593. }
  594. });
  595. userDialog = builder.create();
  596. userDialog.show();
  597. }
  598.  
  599. private void showWaitDialog(String message) {
  600. closeWaitDialog();
  601. waitDialog = new ProgressDialog(this);
  602. waitDialog.setTitle(message);
  603. waitDialog.show();
  604. }
  605.  
  606. private void showDialogMessage(String title, String body, final boolean exit) {
  607. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  608. builder.setTitle(title).setMessage(body).setNeutralButton("OK", new DialogInterface.OnClickListener() {
  609. @Override
  610. public void onClick(DialogInterface dialog, int which) {
  611. try {
  612. userDialog.dismiss();
  613. if(exit) {
  614. exit();
  615. }
  616. } catch (Exception e) {
  617. // Log failure
  618. Log.e(TAG," -- Dialog dismiss failed");
  619. if(exit) {
  620. exit();
  621. }
  622. }
  623. }
  624. });
  625. userDialog = builder.create();
  626. userDialog.show();
  627. }
  628.  
  629. private void closeWaitDialog() {
  630. try {
  631. waitDialog.dismiss();
  632. }
  633. catch (Exception e) {
  634. //
  635. }
  636. }
  637.  
  638. private void exit () {
  639. Intent intent = new Intent();
  640. if(username == null)
  641. username = "";
  642. intent.putExtra("name",username);
  643. setResult(RESULT_OK, intent);
  644. finish();
  645. }
  646. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement