001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.joran.conditional;
015
016import java.lang.reflect.InvocationTargetException;
017import java.lang.reflect.Method;
018import java.util.HashMap;
019import java.util.Map;
020
021import ch.qos.logback.core.spi.PropertyContainer;
022import org.codehaus.commons.compiler.CompileException;
023import org.codehaus.janino.ClassBodyEvaluator;
024
025import ch.qos.logback.core.spi.ContextAwareBase;
026
027public class PropertyEvalScriptBuilder extends ContextAwareBase {
028
029    private static String SCRIPT_PREFIX = "" + "public boolean evaluate() { return ";
030    private static String SCRIPT_SUFFIX = "" + "; }";
031
032    final PropertyContainer localPropContainer;
033
034    PropertyEvalScriptBuilder(PropertyContainer localPropContainer) {
035        this.localPropContainer = localPropContainer;
036    }
037
038    Map<String, String> map = new HashMap<String, String>();
039
040    public Condition build(String script) throws IllegalAccessException, CompileException, InstantiationException, SecurityException, NoSuchMethodException,
041                    IllegalArgumentException, InvocationTargetException {
042
043        ClassBodyEvaluator cbe = new ClassBodyEvaluator();
044        cbe.setImplementedInterfaces(new Class[] { Condition.class });
045        cbe.setExtendedClass(PropertyWrapperForScripts.class);
046        cbe.setParentClassLoader(ClassBodyEvaluator.class.getClassLoader());
047        cbe.cook(SCRIPT_PREFIX + script + SCRIPT_SUFFIX);
048
049        Class<?> clazz = cbe.getClazz();
050        Condition instance = (Condition) clazz.getDeclaredConstructor().newInstance();
051        Method setMapMethod = clazz.getMethod("setPropertyContainers", PropertyContainer.class, PropertyContainer.class);
052        setMapMethod.invoke(instance, localPropContainer, context);
053
054        return instance;
055    }
056
057}