Line data Source code
1 : // Copyright (C) 2016 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.index; 16 : 17 : import static com.google.common.base.Preconditions.checkArgument; 18 : import static java.util.Objects.requireNonNull; 19 : 20 : import com.google.common.collect.ImmutableSortedMap; 21 : import com.google.common.collect.Iterables; 22 : import com.google.gerrit.common.Nullable; 23 : 24 : /** 25 : * Definitions of the various schema versions over a given Gerrit data type. 26 : * 27 : * <p>A <em>schema</em> is a description of the fields that are indexed over the given data type. 28 : * This class contains all the versions of a schema defined over its data type, exposed as a map of 29 : * version number to schema definition. If you are interested in the classes responsible for 30 : * backend-specific runtime implementations, see the implementations of {@link IndexDefinition}. 31 : */ 32 : public abstract class SchemaDefinitions<V> { 33 : private final String name; 34 : private final ImmutableSortedMap<Integer, Schema<V>> schemas; 35 : 36 154 : protected SchemaDefinitions(String name, Class<V> valueClass) { 37 154 : this.name = requireNonNull(name); 38 154 : this.schemas = SchemaUtil.schemasFromClass(getClass(), valueClass); 39 154 : } 40 : 41 : public final String getName() { 42 152 : return name; 43 : } 44 : 45 : /** Returns all schemas sorted by version (ascending). */ 46 : public final ImmutableSortedMap<Integer, Schema<V>> getSchemas() { 47 148 : return schemas; 48 : } 49 : 50 : public final Schema<V> get(int version) { 51 0 : Schema<V> schema = schemas.get(version); 52 0 : checkArgument(schema != null, "Unrecognized %s schema version: %s", name, version); 53 0 : return schema; 54 : } 55 : 56 : public final Schema<V> getLatest() { 57 32 : return schemas.lastEntry().getValue(); 58 : } 59 : 60 : @Nullable 61 : public final Schema<V> getPrevious() { 62 10 : if (schemas.size() <= 1) { 63 0 : return null; 64 : } 65 10 : return Iterables.get(schemas.descendingMap().values(), 1); 66 : } 67 : }