aboutsummaryrefslogtreecommitdiff
path: root/validation/geonames/src/main/java/com/android/timezone/location/validation/Types.java
blob: 17c3d1f5ba3623d54e6cbf9d124979c798c42714 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.timezone.location.validation;

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;

import com.android.timezone.location.validation.proto.ValidationProtos;
import com.google.common.geometry.S2CellId;
import com.google.protobuf.Message;
import com.google.protobuf.TextFormat;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/** Support classes and methods associated with geolocation data comparison / validation. */
class Types {

    private Types() {
    }

    /** A collection of known differences from a KnownDifferences proto file. */
    static class KnownDifferences {

        private final List<KnownDifference> mKnownDifferences;

        private KnownDifferences(List<KnownDifference> knownDifferences) {
            mKnownDifferences = Objects.requireNonNull(knownDifferences);
        }

        /** Creates a {@link KnownDifferences} from a list of {@link KnownDifference} objects. */
        static KnownDifferences create(List<KnownDifference> knownDifferences) {
            return new KnownDifferences(new ArrayList<>(knownDifferences));
        }

        /** Loads a known differences proto txt format file. */
        static KnownDifferences load(File inputFile) throws IOException {
            ValidationProtos.KnownDifferences.Builder builder =
                    ValidationProtos.KnownDifferences.newBuilder();
            try (FileReader reader = new FileReader(inputFile)) {
                TextFormat.getParser().merge(reader, builder);
            }
            ValidationProtos.KnownDifferences knownDifferencesProto = builder.build();

            List<KnownDifference> knownDifferenceList =
                    knownDifferencesProto.getKnownDifferencesList()
                            .stream()
                            .map(KnownDifference::fromProto)
                            .collect(toList());
            return KnownDifferences.create(knownDifferenceList);
        }

        /** Builds a map from the known differences. Each difference is mapped from a {@link
         * TestCaseId} to the {@link KnownDifference} it came from. */
        Map<TestCaseId, KnownDifference> buildIdMap() {
            return mKnownDifferences.stream()
                    .collect(toMap(KnownDifference::getTestCaseId, identity()));
        }

        private ValidationProtos.KnownDifferences toProto() {
            List<ValidationProtos.KnownDifference> knownDifferenceProtos = new ArrayList<>();
            for (KnownDifference knownDifference : mKnownDifferences) {
                knownDifferenceProtos.add(knownDifference.toProto());
            }
            return ValidationProtos.KnownDifferences.newBuilder()
                    .addAllKnownDifferences(knownDifferenceProtos)
                    .build();
        }

        /** Returns the proto txt string form for the known differences. */
        String toProtoText() {
            ValidationProtos.KnownDifferences knownDifferencesProto = toProto();
            return Types.toProtoText(knownDifferencesProto);
        }
    }

    /**
     * An identifier for an individual city test case. It consists of a city's name and its
     * location.
     */
    static class TestCaseId {

        private final String mCityName;

        private final S2CellId mCellId;

        /** Creates a city test case identifier. */
        TestCaseId(String cityName, S2CellId cellId) {
            this.mCityName = Objects.requireNonNull(cityName);
            this.mCellId = Objects.requireNonNull(cellId);
        }

        String getCityName() {
            return mCityName;
        }

        S2CellId getCellId() {
            return mCellId;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            TestCaseId that = (TestCaseId) o;
            return mCityName.equals(that.mCityName) &&
                    mCellId.equals(that.mCellId);
        }

        @Override
        public int hashCode() {
            return Objects.hash(mCityName, mCellId);
        }

        @Override
        public String toString() {
            return "TestCaseId{" +
                    "mCityName='" + mCityName + '\'' +
                    ", mCellId=" + mCellId +
                    '}';
        }
    }

    /**
     * Represents a case where there is a recorded {@link KnownDifference}, but where the
     * actual data didn't match it somehow.
     */
    static class KnownDifferenceMismatch {
        /** The referenceData known difference. */
        private final KnownDifference mKnownDifference;

        /** The expected result according to the reference data. */
        private final Result mReferenceDataResult;

        /** The actual result. */
        private final Result mActualResult;

        KnownDifferenceMismatch(KnownDifference knownDifference,
                Result referenceDataResult, Result actualResult) {
            this.mKnownDifference = Objects.requireNonNull(knownDifference);
            this.mReferenceDataResult = Objects.requireNonNull(referenceDataResult);
            this.mActualResult = Objects.requireNonNull(actualResult);
        }

        KnownDifference getReferenceDataKnownDifference() {
            return mKnownDifference;
        }

        KnownDifference getActualKnownDifference() {
            return new KnownDifference(mKnownDifference.mTestCaseId, mReferenceDataResult,
                    mActualResult,
                    mKnownDifference.mType, mKnownDifference.mComment, mKnownDifference.mBugUri);
        }
    }

    /** An historic known difference between an actual result and reference data. */
    static class KnownDifference {

        static KnownDifference fromProto(
                ValidationProtos.KnownDifference knownDifferenceProto) {
            TestCaseId testCaseId = new TestCaseId(
                    knownDifferenceProto.getCityName(),
                    new S2CellId(knownDifferenceProto.getS2CellId()));
            return new KnownDifference(
                    testCaseId,
                    Result.fromProto(knownDifferenceProto.getReferenceDataResult()),
                    Result.fromProto(knownDifferenceProto.getActualResult()),
                    Type.valueOf(knownDifferenceProto.getType()),
                    knownDifferenceProto.getComment(),
                    URI.create(knownDifferenceProto.getBugUri())
            );
        }

        ValidationProtos.KnownDifference toProto() {
            return ValidationProtos.KnownDifference.newBuilder()
                    .setCityName(mTestCaseId.getCityName())
                    .setS2CellId(mTestCaseId.getCellId().id())
                    .setReferenceDataResult(mReferenceDataResult.toProto())
                    .setActualResult(mActualResult.toProto())
                    .setComment(mComment)
                    .setType(mType.toString())
                    .setBugUri(mBugUri.toString())
                    .build();
        }

        /** A categorization for causes of known differences. */
        enum Type {
            /** Uncategorized. */
            UNKNOWN,
            /** A known bug in the data generation pipeline. */
            PIPELINE_BUG,
            /** A difference due to geopolitical position. */
            GEOPOLITICS,
            /** A generic difference in data not generated by Android. */
            UPSTREAM_DIFFERENCE,
        }

        private final TestCaseId mTestCaseId;

        private final Result mReferenceDataResult;

        private final Result mActualResult;

        /** A broad categorization of the cause for the difference. */
        private final Type mType;

        /** Free-form details about the difference. */
        private final String mComment;

        /** A bug URL tracking the investigation / fix for the difference, if there is one. */
        private final URI mBugUri;

        KnownDifference(TestCaseId testCaseId, Result referenceDataResult,
                Result actualResult, Type type, String comment, URI bugUri) {
            this.mTestCaseId = Objects.requireNonNull(testCaseId);
            this.mReferenceDataResult = Objects.requireNonNull(referenceDataResult);
            this.mActualResult = Objects.requireNonNull(actualResult);
            this.mType = Objects.requireNonNull(type);
            this.mComment = Objects.requireNonNull(comment);
            this.mBugUri = Objects.requireNonNull(bugUri);
        }

        /** Returns the identifier for the test case that differed. */
        TestCaseId getTestCaseId() {
            return mTestCaseId;
        }

        /** Returns the answer according to the reference data set. */
        Result getReferenceDataResult() {
            return mReferenceDataResult;
        }

        /** REturns the answer according to Android's data set. */
        Result getActualResult() {
            return mActualResult;
        }

        String toProtoText() {
            ValidationProtos.KnownDifference proto = toProto();
            return Types.toProtoText(proto);
        }
    }

    private static String toProtoText(Message proto) {
        try (StringWriter writer = new StringWriter()) {
            TextFormat.print(proto, writer);
            return writer.getBuffer().toString();
        } catch (IOException e) {
            throw new IllegalStateException("This will never happen", e);
        }
    }

    /** The result of a city lookup. */
    static class Result {

        private final List<String> mIsoCountryCodes;
        private final List<String> mZoneIds;

        Result(List<String> isoCountryCodes, List<String> zoneIds) {
            this.mIsoCountryCodes = isoCountryCodes;
            this.mZoneIds = new ArrayList<>(zoneIds);
        }

        boolean hasMultipleZoneIds() {
            return mZoneIds.size() > 1;
        }

        /**
         * Returns {@code true} if there is an intersection between the country codes and zone IDs.
         */
        boolean intersects(Result other) {
            boolean zonesIntersect = intersect(mZoneIds, other.mZoneIds);
            boolean countriesIntersect = intersect(mIsoCountryCodes, other.mIsoCountryCodes);
            return countriesIntersect && zonesIntersect;
        }

        private static <T> boolean intersect(List<T> one, List<T> two) {
            Set<T> intersectionSet = new HashSet<>(one);
            intersectionSet.retainAll(two);
            return !intersectionSet.isEmpty();
        }

        ValidationProtos.Result toProto() {
            return ValidationProtos.Result.newBuilder()
                    .addAllIsoCountryCodes(mIsoCountryCodes)
                    .addAllZoneIds(mZoneIds)
                    .build();
        }

        static Result fromProto(ValidationProtos.Result proto) {
            return new Result(proto.getIsoCountryCodesList(), proto.getZoneIdsList());
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            Result result = (Result) o;
            return mIsoCountryCodes.equals(result.mIsoCountryCodes)
                    && mZoneIds.equals(result.mZoneIds);
        }

        @Override
        public int hashCode() {
            return Objects.hash(mIsoCountryCodes, mZoneIds);
        }

        @Override
        public String toString() {
            return "Result{"
                    + "mIsoCountryCodes=" + mIsoCountryCodes
                    + ", mZoneIds=" + mZoneIds
                    + '}';
        }
    }
}