1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.shardingsphere.infra.rule.attribute; 19 20 import java.util.Arrays; 21 import java.util.Collection; 22 import java.util.Optional; 23 24 /** 25 * Rule attribute. 26 */ 27 public final class RuleAttributes { 28 29 private final Collection<RuleAttribute> attributes; 30 31 public RuleAttributes(final RuleAttribute... attributes) { 32 this.attributes = Arrays.asList(attributes); 33 } 34 35 /** 36 * Find rule attribute. 37 * 38 * @param attributeClass rule attribute class 39 * @param <T> type of rule attribute 40 * @return found rule attribute 41 */ 42 @SuppressWarnings("unchecked") 43 public <T extends RuleAttribute> Optional<T> findAttribute(final Class<T> attributeClass) { 44 for (RuleAttribute each : attributes) { 45 if (attributeClass.isAssignableFrom(each.getClass())) { 46 return Optional.of((T) each); 47 } 48 } 49 return Optional.empty(); 50 } 51 52 /** 53 * Get rule attribute. 54 * 55 * @param attributeClass rule attribute class 56 * @param <T> type of rule attribute 57 * @return got rule attribute 58 */ 59 public <T extends RuleAttribute> T getAttribute(final Class<T> attributeClass) { 60 return findAttribute(attributeClass).orElseThrow(() -> new IllegalStateException(String.format("Can not find rule attribute: %s", attributeClass))); 61 } 62 }