Line data Source code
1 : // Copyright (C) 2018 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.server; 16 : 17 : import com.google.inject.Module; 18 : import java.util.List; 19 : import java.util.Map; 20 : import java.util.stream.Collectors; 21 : 22 : public class ModuleOverloader { 23 : public static List<Module> override(List<Module> modules, List<Module> overrideCandidates) { 24 138 : if (overrideCandidates == null || overrideCandidates.isEmpty()) { 25 15 : return modules; 26 : } 27 : 28 : // group candidates by annotation existence 29 138 : Map<Boolean, List<Module>> grouped = 30 138 : overrideCandidates.stream() 31 138 : .collect( 32 138 : Collectors.groupingBy(m -> m.getClass().getAnnotation(ModuleImpl.class) != null)); 33 : 34 : // add all non annotated libs to modules list 35 138 : List<Module> libs = grouped.get(Boolean.FALSE); 36 138 : if (libs != null) { 37 138 : modules.addAll(libs); 38 : } 39 : 40 138 : List<Module> overrides = grouped.get(Boolean.TRUE); 41 138 : if (overrides == null) { 42 137 : return modules; 43 : } 44 : 45 : // swap module implementations with the matching alternative ones provided in lib 46 2 : return modules.stream() 47 2 : .map( 48 : m -> { 49 2 : ModuleImpl a = m.getClass().getAnnotation(ModuleImpl.class); 50 2 : if (a == null) { 51 2 : return m; 52 : } 53 2 : return overrides.stream() 54 2 : .filter( 55 : o -> 56 2 : o.getClass() 57 2 : .getAnnotation(ModuleImpl.class) 58 2 : .name() 59 2 : .equalsIgnoreCase(a.name())) 60 2 : .findFirst() 61 2 : .orElse(m); 62 : }) 63 2 : .collect(Collectors.toList()); 64 : } 65 : 66 : private ModuleOverloader() {} 67 : }