summaryrefslogtreecommitdiffstats
path: root/mobile/android/base/java/org/mozilla/gecko/push/Fetched.java
blob: 42a7c6a90b2c7561401d3c0615c7053a57e2cff1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.push;

import android.support.annotation.NonNull;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Pair a (String) value with a timestamp.  The timestamp is usually when the
 * value was fetched from a remote service or when the value was locally
 * generated.
 *
 * It's awkward to serialize generic values to JSON -- that requires lots of
 * factory classes -- so we specialize to String instances.
 */
public class Fetched {
    public final String value;
    public final long timestamp;

    public Fetched(String value, long timestamp) {
        this.value = value;
        this.timestamp = timestamp;
    }

    public static Fetched now(String value) {
        return new Fetched(value, System.currentTimeMillis());
    }

    public static @NonNull Fetched fromJSONObject(@NonNull JSONObject json) {
        final String value = json.optString("value", null);
        final String timestampString = json.optString("timestamp", null);
        final long timestamp = timestampString != null ? Long.valueOf(timestampString) : 0L;
        return new Fetched(value, timestamp);
    }

    public JSONObject toJSONObject() throws JSONException {
        final JSONObject jsonObject = new JSONObject();
        if (value != null) {
            jsonObject.put("value", value);
        } else {
            jsonObject.remove("value");
        }
        jsonObject.put("timestamp", Long.toString(timestamp));
        return jsonObject;
    }

    @Override
    public boolean equals(Object o) {
        // Auto-generated.
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Fetched fetched = (Fetched) o;

        if (timestamp != fetched.timestamp) return false;
        return !(value != null ? !value.equals(fetched.value) : fetched.value != null);

    }

    @Override
    public int hashCode() {
        // Auto-generated.
        int result = value != null ? value.hashCode() : 0;
        result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
        return result;
    }
}