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.convert.TypeConverters; 021import org.apache.logging.log4j.core.config.plugins.validation.ConstraintValidator; 022import org.apache.logging.log4j.core.config.plugins.validation.constraints.ValidPort; 023import org.apache.logging.log4j.status.StatusLogger; 024 025/** 026 * Validator that checks an object to verify it is a valid port number (an integer between 0 and 65535). 027 * 028 * @since 2.8 029 */ 030public class ValidPortValidator implements ConstraintValidator<ValidPort> { 031 032 private static final Logger LOGGER = StatusLogger.getLogger(); 033 034 private ValidPort annotation; 035 036 @Override 037 public void initialize(final ValidPort annotation) { 038 this.annotation = annotation; 039 } 040 041 @Override 042 public boolean isValid(final String name, final Object value) { 043 if (value instanceof CharSequence) { 044 return isValid(name, TypeConverters.convert(value.toString(), Integer.class, -1)); 045 } 046 if (!Integer.class.isInstance(value)) { 047 LOGGER.error(annotation.message()); 048 return false; 049 } 050 final int port = (int) value; 051 if (port < 0 || port > 65535) { 052 LOGGER.error(annotation.message()); 053 return false; 054 } 055 return true; 056 } 057}