|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch B.V. under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch B.V. licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.logstash.settings; |
| 21 | + |
| 22 | +import java.util.List; |
| 23 | + |
| 24 | +public class CoercibleStringSetting extends Coercible<Object> { |
| 25 | + |
| 26 | + private final List<String> possibleStrings; |
| 27 | + |
| 28 | + @SuppressWarnings("this-escape") |
| 29 | + public CoercibleStringSetting(String name, Object defaultValue, boolean strict, List<String> possibleStrings) { |
| 30 | + // this super doesn't call validate, with strict false it permits to set |
| 31 | + // possibleStrings field used in validate later. |
| 32 | + super(name, defaultValue, false, noValidator()); |
| 33 | + this.possibleStrings = possibleStrings; |
| 34 | + |
| 35 | + if (strict) { |
| 36 | + String coercedDefault = coerce(defaultValue); |
| 37 | + validate(coercedDefault); |
| 38 | + this.defaultValue = coercedDefault; |
| 39 | + } else { |
| 40 | + this.defaultValue = defaultValue; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public String coerce(Object value) { |
| 46 | + if (value == null) { |
| 47 | + return ""; |
| 48 | + } |
| 49 | + return value.toString(); |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + public void validate(Object input) throws IllegalArgumentException { |
| 54 | + super.validate(input); |
| 55 | + |
| 56 | + staticValidate(input.toString(), possibleStrings, this.getName()); |
| 57 | + } |
| 58 | + |
| 59 | + private static void staticValidate(String input, List<String> possibleStrings, String name) { |
| 60 | + if (!possibleStrings.isEmpty() && !possibleStrings.contains(input)) { |
| 61 | + throw new IllegalArgumentException(String.format("Invalid value \"%s\". Options are: %s", input, possibleStrings)); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | +} |
0 commit comments