1 /*
2 * Copyright 2012-2017 CodeLibs Project and the Others.
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,
13 * either express or implied. See the License for the specific language
14 * governing permissions and limitations under the License.
15 */
16 package org.codelibs.fess.util;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import org.lastaflute.di.core.factory.SingletonLaContainerFactory;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import groovy.lang.Binding;
26 import groovy.lang.GroovyClassLoader;
27 import groovy.lang.GroovyShell;
28
29 public final class GroovyUtil {
30 private static final Logger logger = LoggerFactory.getLogger(GroovyUtil.class);
31
32 private GroovyUtil() {
33 // nothing
34 }
35
36 public static Object evaluate(final String template, final Map<String, Object> paramMap) {
37 final Map<String, Object> bindingMap = new HashMap<>(paramMap);
38 bindingMap.put("container", SingletonLaContainerFactory.getContainer());
39 final GroovyShell groovyShell = new GroovyShell(new Binding(bindingMap));
40 try {
41 return groovyShell.evaluate(template);
42 } catch (final Exception e) {
43 logger.warn("Failed to evalue groovy script: " + template + " => " + paramMap, e);
44 return null;
45 } finally {
46 final GroovyClassLoader loader = groovyShell.getClassLoader();
47 // StreamUtil.of(loader.getLoadedClasses()).forEach(c -> {
48 // try {
49 // GroovySystem.getMetaClassRegistry().removeMetaClass(c);
50 // } catch (Throwable t) {
51 // logger.warn("Failed to delete " + c, t);
52 // }
53 // });
54 loader.clearCache();
55 }
56 }
57 }