1 package com.ljs.ootp.extract.html.rating;
2
3 import com.fasterxml.jackson.annotation.JsonValue;
4 import com.google.common.base.Objects;
5 import com.google.common.base.Preconditions;
6 import com.google.common.base.Throwables;
7
8
9
10
11
12 public final class Rating<T, S extends Scale<T>> {
13
14 private final T value;
15
16 private final S scale;
17
18 private Rating(T value, S scale) {
19 Preconditions.checkNotNull(value);
20 Preconditions.checkNotNull(scale);
21
22
23
24
25 this.value = (String.class.isInstance(value)
26 ? scale.parse(String.class.cast(value)).value
27 : value);
28
29 this.scale = scale;
30 }
31
32 @JsonValue
33 public T get() {
34 return value;
35 }
36
37 public Rating<Integer, OneToOneHundred> normalize() {
38 try {
39 return scale.normalize(value);
40 } catch (ClassCastException e) {
41 System.out.println(scale + ":" + value);
42 throw Throwables.propagate(e);
43 }
44 }
45
46 @Override
47 public boolean equals(Object obj) {
48 if (obj == null) {
49 return false;
50 }
51 if (obj == this) {
52 return true;
53 }
54 if (obj.getClass() != getClass()) {
55 return false;
56 }
57
58 Rating<?, ?> rhs = Rating.class.cast(obj);
59
60 return Objects.equal(value, rhs.value)
61 && Objects.equal(scale, rhs.scale);
62 }
63
64 @Override
65 public int hashCode() {
66 return Objects.hashCode(value, scale);
67 }
68
69 @Override
70 public String toString() {
71 return Objects
72 .toStringHelper(this)
73 .add("value", value)
74 .add("scale", scale)
75 .toString();
76 }
77
78 public static <T, S extends Scale<T>> Rating<T, S> create(
79 T value, S scale) {
80
81 return new Rating<T, S>(value, scale);
82 }
83
84 }