001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017 package org.apache.logging.log4j.core.config.plugins.validation.validators;
018
019 import java.util.Collection;
020 import java.util.Map;
021
022 import org.apache.logging.log4j.Logger;
023 import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator;
024 import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
025 import org.apache.logging.log4j.status.StatusLogger;
026
027 /**
028 * Validator that checks an object for emptiness. Emptiness is defined here as:
029 * <ul>
030 * <li>The value {@code null}</li>
031 * <li>An object of type {@link CharSequence} with length 0</li>
032 * <li>An empty array</li>
033 * <li>An empty {@link Collection}</li>
034 * <li>An empty {@link Map}</li>
035 * </ul>
036 *
037 * @since 2.1
038 */
039 public class RequiredValidator implements ConstraintValidator<Required> {
040
041 private static final Logger LOGGER = StatusLogger.getLogger();
042
043 private Required annotation;
044
045 @Override
046 public void initialize(final Required annotation) {
047 this.annotation = annotation;
048 }
049
050 @Override
051 public boolean isValid(final Object value) {
052 if (value == null) {
053 return err();
054 }
055 if (value instanceof CharSequence) {
056 final CharSequence sequence = (CharSequence) value;
057 return sequence.length() != 0 || err();
058 }
059 final Class<?> clazz = value.getClass();
060 if (clazz.isArray()) {
061 final Object[] array = (Object[]) value;
062 return array.length != 0 || err();
063 }
064 if (Collection.class.isAssignableFrom(clazz)) {
065 final Collection<?> collection = (Collection<?>) value;
066 return collection.size() != 0 || err();
067 }
068 if (Map.class.isAssignableFrom(clazz)) {
069 final Map<?, ?> map = (Map<?, ?>) value;
070 return map.size() != 0 || err();
071 }
072 LOGGER.debug("Encountered type [{}] which can only be checked for null.", clazz.getName());
073 return true;
074 }
075
076 private boolean err() {
077 LOGGER.error(annotation.message());
078 return false;
079 }
080 }