DataHolderUtil.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Nextcloud Android client application
  3. *
  4. * @author Mario Danic
  5. * Copyright (C) 2017 Mario Danic
  6. * <p>
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * at your option) any later version.
  11. * <p>
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. * <p>
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.owncloud.android.utils;
  21. import android.annotation.SuppressLint;
  22. import java.lang.ref.WeakReference;
  23. import java.math.BigInteger;
  24. import java.security.SecureRandom;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. /**
  28. * Data holder utility to store & retrieve stuff
  29. */
  30. public class DataHolderUtil {
  31. private Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
  32. private static DataHolderUtil instance;
  33. @SuppressLint("TrulyRandom")
  34. private SecureRandom random = new SecureRandom();
  35. public static synchronized DataHolderUtil getInstance() {
  36. if (instance == null) {
  37. instance = new DataHolderUtil();
  38. }
  39. return instance;
  40. }
  41. public void save(String id, Object object) {
  42. data.put(id, new WeakReference<Object>(object));
  43. }
  44. public Object retrieve(String id) {
  45. WeakReference<Object> objectWeakReference = data.get(id);
  46. return objectWeakReference.get();
  47. }
  48. public void delete(String id) {
  49. if (id != null) {
  50. data.remove(id);
  51. }
  52. }
  53. public String nextItemId() {
  54. String nextItemId = new BigInteger(130, random).toString(32);
  55. while (data.containsKey(nextItemId)) {
  56. nextItemId = new BigInteger(130, random).toString(32);
  57. }
  58. return nextItemId;
  59. }
  60. }