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.camel.reifier.validator;
018
019import org.apache.camel.CamelContext;
020import org.apache.camel.model.validator.CustomValidatorDefinition;
021import org.apache.camel.model.validator.ValidatorDefinition;
022import org.apache.camel.spi.Validator;
023
024public class CustomValidatorReifier extends ValidatorReifier<CustomValidatorDefinition> {
025
026    public CustomValidatorReifier(ValidatorDefinition definition) {
027        super((CustomValidatorDefinition)definition);
028    }
029
030    @Override
031    protected Validator doCreateValidator(CamelContext context) throws Exception {
032        if (definition.getRef() == null && definition.getClassName() == null) {
033            throw new IllegalArgumentException("'ref' or 'type' must be specified for customValidator");
034        }
035        Validator validator;
036        if (definition.getRef() != null) {
037            validator = context.getRegistry().lookupByNameAndType(definition.getRef(), Validator.class);
038            if (validator == null) {
039                throw new IllegalArgumentException("Cannot find validator with ref:" + definition.getRef());
040            }
041            if (validator.getType() != null) {
042                throw new IllegalArgumentException(String.format("Validator '%s' is already in use. Please check if duplicate validator exists.", definition.getRef()));
043            }
044        } else {
045            Class<Validator> validatorClass = context.getClassResolver().resolveMandatoryClass(definition.getClassName(), Validator.class);
046            if (validatorClass == null) {
047                throw new IllegalArgumentException("Cannot find validator class: " + definition.getClassName());
048            }
049            validator = context.getInjector().newInstance(validatorClass, false);
050
051        }
052        validator.setCamelContext(context);
053        return validator.setType(definition.getType());
054    }
055
056}