View Javadoc
1   /*
2    * Copyright 2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *     
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.openehealth.ipf.platform.camel.core.closures;
17  
18  import groovy.lang.Closure;
19  
20  import org.openehealth.ipf.commons.core.modules.api.ValidationException;
21  import org.openehealth.ipf.commons.core.modules.api.Validator;
22  
23  /**
24   * A validator that delegates to a {@link Closure}.
25   * 
26   * @author Martin Krasser
27   */
28  public class DelegatingValidator extends ClosureAdapter implements Validator<Object, Object> {
29  
30      public DelegatingValidator(Closure closure) {
31          super(closure);
32      }
33  
34      @Override
35      public void validate(Object message, Object profile) {
36          Object result;
37          result = validateInternal(message, profile);
38          if (!(result instanceof Boolean)) {
39              return;
40          }
41          if (!(Boolean)result) {
42              throw new ValidationException("validation closure returned false");
43          }
44      }
45      
46      private Object validateInternal(Object message, Object profile) {
47          if (getClosure().getParameterTypes().length == 2) {
48              return call(message, profile);
49          } else {
50              return call(message);
51          }
52      }
53      
54  }