PageRenderTime 24ms CodeModel.GetById 6ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/hazelcast/src/main/java/com/hazelcast/impl/management/ScriptExecutorCallable.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 149 lines | 115 code | 16 blank | 18 comment | 15 complexity | 341f6bf12a2f6ec442fdbe67b9caecc7 MD5 | raw file
  1/*
  2 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  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
 17package com.hazelcast.impl.management;
 18
 19import com.hazelcast.core.HazelcastInstance;
 20import com.hazelcast.core.HazelcastInstanceAware;
 21import com.hazelcast.logging.ILogger;
 22import com.hazelcast.logging.Logger;
 23import com.hazelcast.nio.DataSerializable;
 24import com.hazelcast.nio.SerializationHelper;
 25
 26import java.io.DataInput;
 27import java.io.DataOutput;
 28import java.io.IOException;
 29import java.lang.reflect.Method;
 30import java.util.HashMap;
 31import java.util.Map;
 32import java.util.Map.Entry;
 33import java.util.Set;
 34import java.util.concurrent.Callable;
 35import java.util.concurrent.ExecutionException;
 36import java.util.logging.Level;
 37
 38public class ScriptExecutorCallable<V> implements DataSerializable, Callable<V>, HazelcastInstanceAware {
 39
 40    private static final long serialVersionUID = -4729129143589252665L;
 41
 42    private static final ILogger logger = Logger.getLogger(ScriptExecutorCallable.class.getName());
 43    private static final String SCRIPT_ENGINE_MANAGER_CLASS = "javax.script.ScriptEngineManager";
 44    private static final Object/*ScriptEngineManager*/ scriptEngineManager;
 45    private static final Method/*ScriptEngineManager.getEngineByName*/ mGetEngineByName;
 46    private static final Exception scriptEngineLoadError;
 47
 48    static {
 49        Object manager = null;
 50        Method method = null;
 51        Exception error = null;
 52        try {
 53            final Class scriptEngineManagerClass = Class.forName(SCRIPT_ENGINE_MANAGER_CLASS);
 54            manager = scriptEngineManagerClass.newInstance();
 55            method = scriptEngineManagerClass.getMethod("getEngineByName", new Class[]{String.class});
 56        } catch (Exception e) {
 57            error = e;
 58            logger.log(Level.WARNING, "ScriptEngineManager could not be loaded!", e);
 59        }
 60        scriptEngineManager = manager;
 61        mGetEngineByName = method;
 62        scriptEngineLoadError = error;
 63    }
 64
 65    private String engineName;
 66    private String script;
 67    private Map<String, Object> bindings;
 68    private transient HazelcastInstance hazelcast;
 69
 70    public ScriptExecutorCallable() {
 71    }
 72
 73    public ScriptExecutorCallable(String engineName, String script) {
 74        super();
 75        this.engineName = engineName;
 76        this.script = script;
 77    }
 78
 79    public ScriptExecutorCallable(String engineName, String script, Map<String, Object> bindings) {
 80        super();
 81        this.engineName = engineName;
 82        this.script = script;
 83        this.bindings = bindings;
 84    }
 85
 86    public V call() throws Exception {
 87        if (scriptEngineLoadError != null) {
 88            throw new ExecutionException("ScriptEngineManager could not be loaded!", scriptEngineLoadError);
 89        }
 90        // ScriptEngine engine = ScriptEngineManager.getEngineByName(engineName);
 91        Object/*ScriptEngine*/ engine = mGetEngineByName.invoke(scriptEngineManager, engineName);
 92        if (engine == null) {
 93            throw new IllegalArgumentException("Could not find ScriptEngine named '" + engineName + "'.");
 94        }
 95        Method put = engine.getClass().getMethod("put", new Class[]{String.class, Object.class});
 96        put.invoke(engine, "hazelcast", hazelcast);
 97        if (bindings != null) {
 98            Set<Entry<String, Object>> entries = bindings.entrySet();
 99            for (Entry<String, Object> entry : entries) {
100                // ScriptEngine.put(key, value);
101                put.invoke(engine, entry.getKey(), entry.getValue());
102            }
103        }
104        Method eval = engine.getClass().getMethod("eval", new Class[]{String.class});
105        // Object result = ScriptEngine.eval(script);
106        Object result = eval.invoke(engine, script);
107        if (result == null) {
108            return null;
109        }
110        return (V) result;
111    }
112
113    public void writeData(DataOutput out) throws IOException {
114        out.writeUTF(engineName);
115        out.writeUTF(script);
116        if (bindings != null) {
117            out.writeInt(bindings.size());
118            Set<Entry<String, Object>> entries = bindings.entrySet();
119            for (Entry<String, Object> entry : entries) {
120                out.writeUTF(entry.getKey());
121                SerializationHelper.writeObject(out, entry.getValue());
122            }
123        } else {
124            out.writeInt(0);
125        }
126    }
127
128    public void readData(DataInput in) throws IOException {
129        engineName = in.readUTF();
130        script = in.readUTF();
131        int size = in.readInt();
132        if (size > 0) {
133            bindings = new HashMap<String, Object>(size);
134            for (int i = 0; i < size; i++) {
135                String key = in.readUTF();
136                Object value = SerializationHelper.readObject(in);
137                bindings.put(key, value);
138            }
139        }
140    }
141
142    public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
143        this.hazelcast = hazelcastInstance;
144    }
145
146    public void setBindings(Map<String, Object> bindings) {
147        this.bindings = bindings;
148    }
149}