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 */
017package org.apache.logging.log4j.core.config.plugins.validation.validators;
018
019import org.apache.logging.log4j.Logger;
020import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator;
021import org.apache.logging.log4j.core.config.plugins.validation.constraints.ValidHost;
022import org.apache.logging.log4j.status.StatusLogger;
023
024import java.net.InetAddress;
025import java.net.UnknownHostException;
026
027/**
028 * Validator that checks an object to verify it is a valid hostname or IP address. Validation rules follow the same
029 * logic as in {@link InetAddress#getByName(String)}.
030 *
031 * @since 2.8
032 */
033public class ValidHostValidator implements ConstraintValidator<ValidHost> {
034
035    private static final Logger LOGGER = StatusLogger.getLogger();
036
037    private ValidHost annotation;
038
039    @Override
040    public void initialize(final ValidHost annotation) {
041        this.annotation = annotation;
042    }
043
044    @Override
045    public boolean isValid(final String name, final Object value) {
046        if (value == null) {
047            LOGGER.error(annotation.message());
048            return false;
049        }
050        if (value instanceof InetAddress) {
051            // InetAddress factory methods all have built in validation
052            return true;
053        }
054        try {
055            InetAddress.getByName(value.toString());
056            return true;
057        } catch (final UnknownHostException e) {
058            LOGGER.error(annotation.message(), e);
059            return false;
060        }
061    }
062}