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.processor.validation;
018
019import org.apache.camel.Exchange;
020import org.apache.camel.Predicate;
021import org.apache.camel.Processor;
022import org.apache.camel.Traceable;
023import org.apache.camel.support.ServiceSupport;
024import org.apache.camel.util.ObjectHelper;
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027
028/**
029 * A processor which validates the content of the inbound message body against a {@link Predicate}.
030 * 
031 * @version 
032 */
033public class PredicateValidatingProcessor extends ServiceSupport implements Processor, Traceable {
034    
035    private static final Logger LOG = LoggerFactory.getLogger(PredicateValidatingProcessor.class);
036
037    private final Predicate predicate;
038    
039    public PredicateValidatingProcessor(Predicate predicate) {
040        ObjectHelper.notNull(predicate, "predicate", this);
041        this.predicate = predicate;
042    }
043
044    public void process(Exchange exchange) throws Exception {
045        boolean matches = predicate.matches(exchange);
046
047        if (LOG.isDebugEnabled()) {
048            LOG.debug("Validation {} for {} with Predicate[{}]", matches ? "succeed" : "failed", exchange, predicate);
049        }
050
051        if (!matches) {
052            throw new PredicateValidationException(exchange, predicate);
053        }
054    }
055
056    public Predicate getPredicate() {
057        return predicate;
058    }
059
060    @Override
061    public String toString() {
062        return "validate(" + predicate + ")";
063    }
064
065    public String getTraceLabel() {
066        return "validate[" + predicate + "]";
067    }
068
069    @Override
070    protected void doStart() throws Exception {
071        // noop
072    }
073
074    @Override
075    protected void doStop() throws Exception {
076        // noop
077    }
078}