View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.joran.conditional;
15  
16  import java.lang.reflect.InvocationTargetException;
17  import java.lang.reflect.Method;
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import ch.qos.logback.core.spi.PropertyContainer;
22  import org.codehaus.commons.compiler.CompileException;
23  import org.codehaus.janino.ClassBodyEvaluator;
24  
25  import ch.qos.logback.core.spi.ContextAwareBase;
26  
27  public class PropertyEvalScriptBuilder extends ContextAwareBase {
28  
29      private static String SCRIPT_PREFIX = "" + "public boolean evaluate() { return ";
30      private static String SCRIPT_SUFFIX = "" + "; }";
31  
32      final PropertyContainer localPropContainer;
33  
34      public PropertyEvalScriptBuilder(PropertyContainer localPropContainer) {
35          this.localPropContainer = localPropContainer;
36      }
37  
38      Map<String, String> map = new HashMap<String, String>();
39  
40      public Condition build(String script) throws IllegalAccessException, CompileException, InstantiationException,
41              SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
42  
43          ClassBodyEvaluator cbe = new ClassBodyEvaluator();
44          cbe.setImplementedInterfaces(new Class[] { Condition.class });
45          cbe.setExtendedClass(PropertyWrapperForScripts.class);
46          cbe.setParentClassLoader(ClassBodyEvaluator.class.getClassLoader());
47          cbe.cook(SCRIPT_PREFIX + script + SCRIPT_SUFFIX);
48  
49          Class<?> clazz = cbe.getClazz();
50          Condition instance = (Condition) clazz.getDeclaredConstructor().newInstance();
51          Method setMapMethod = clazz.getMethod("setPropertyContainers", PropertyContainer.class,
52                  PropertyContainer.class);
53          setMapMethod.invoke(instance, localPropContainer, context);
54  
55          return instance;
56      }
57  
58  }