Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / android / java / src / org / chromium / chrome / browser / identity / UuidBasedUniqueIdentificationGenerator.java
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.chrome.browser.identity;
6
7 import android.content.Context;
8 import android.content.SharedPreferences;
9 import android.preference.PreferenceManager;
10
11 import org.chromium.base.VisibleForTesting;
12
13 import java.util.UUID;
14
15 import javax.annotation.Nullable;
16
17 /**
18  * Generates unique IDs that are {@link UUID} strings.
19  */
20 public class UuidBasedUniqueIdentificationGenerator implements UniqueIdentificationGenerator {
21     public static final String GENERATOR_ID = "UUID";
22     private final Context mContext;
23     private final String mPreferenceKey;
24
25     public UuidBasedUniqueIdentificationGenerator(Context context, String preferenceKey) {
26         mContext = context;
27         mPreferenceKey = preferenceKey;
28     }
29
30     @Override
31     public String getUniqueId(@Nullable String salt) {
32         SharedPreferences preferences = PreferenceManager
33                 .getDefaultSharedPreferences(mContext);
34         String storedUniqueId = preferences.getString(mPreferenceKey, null);
35         if (storedUniqueId != null) {
36             return storedUniqueId;
37         }
38
39         // Generate a new unique ID.
40         String uniqueId = getUUID();
41
42         // Store the field so we ensure we always return the same unique ID.
43         SharedPreferences.Editor editor = preferences.edit();
44         editor.putString(mPreferenceKey, uniqueId);
45         editor.apply();
46         return uniqueId;
47
48     }
49
50     @VisibleForTesting
51     String getUUID() {
52         return UUID.randomUUID().toString();
53     }
54 }