Search in sources :

Example 1 with BSFException

use of org.apache.bsf.BSFException in project groovy by apache.

the class CachingGroovyEngine method exec.

/**
     * Execute a script.
     */
public void exec(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        //          shell.run(script.toString(), source, EMPTY_ARGS);
        Class scriptClass = execScripts.get(script);
        if (scriptClass == null) {
            scriptClass = loader.parseClass(script.toString(), source);
            execScripts.put(script, scriptClass);
        } else {
            LOG.fine("exec() - Using cached version of class...");
        }
        InvokerHelper.invokeMethod(scriptClass, "main", EMPTY_ARGS);
    } catch (Exception e) {
        LOG.log(Level.WARNING, "BSF trace", e);
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
Also used : BSFException(org.apache.bsf.BSFException) BSFException(org.apache.bsf.BSFException)

Example 2 with BSFException

use of org.apache.bsf.BSFException in project groovy by apache.

the class CachingGroovyEngine method eval.

/**
     * Evaluate an expression.
     */
public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        Class scriptClass = evalScripts.get(script);
        if (scriptClass == null) {
            scriptClass = loader.parseClass(script.toString(), source);
            evalScripts.put(script, scriptClass);
        } else {
            LOG.fine("eval() - Using cached script...");
        }
        //can't cache the script because the context may be different.
        //but don't bother loading parsing the class again
        Script s = InvokerHelper.createScript(scriptClass, context);
        return s.run();
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
Also used : Script(groovy.lang.Script) BSFException(org.apache.bsf.BSFException) BSFException(org.apache.bsf.BSFException)

Example 3 with BSFException

use of org.apache.bsf.BSFException in project groovy by apache.

the class GroovyEngine method exec.

/**
     * Execute a script.
     */
public void exec(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        // use evaluate to pass in the BSF variables
        source = convertToValidJavaClassname(source);
        getEvalShell().evaluate(script.toString(), source);
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
Also used : BSFException(org.apache.bsf.BSFException) BSFException(org.apache.bsf.BSFException)

Example 4 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class BSFMonitor method executeScript.

private synchronized PollStatus executeScript(MonitoredService svc, Map<String, Object> map) {
    PollStatus pollStatus = PollStatus.unavailable();
    String fileName = ParameterMap.getKeyedString(map, "file-name", null);
    String lang = ParameterMap.getKeyedString(map, "lang-class", null);
    String langEngine = ParameterMap.getKeyedString(map, "bsf-engine", null);
    String[] langExtensions = ParameterMap.getKeyedString(map, "file-extensions", "").split(",");
    String runType = ParameterMap.getKeyedString(map, "run-type", "eval");
    File file = new File(fileName);
    try {
        if (lang == null)
            lang = BSFManager.getLangFromFilename(fileName);
        if (langEngine != null && lang != null && langExtensions.length > 0) {
            // We register the scripting engine again no matter what since
            // BSFManager doesn't let us know what engine is currently registered
            // for this language and it might not be the same as what we want.
            LOG.debug("Registering scripting engine '{}' for '{}'", langEngine, lang);
            BSFManager.registerScriptingEngine(lang, langEngine, langExtensions);
        }
        if (file.exists() && file.canRead()) {
            String code = IOUtils.getStringFromReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
            HashMap<String, String> results = new HashMap<String, String>();
            LinkedHashMap<String, Number> times = new LinkedHashMap<String, Number>();
            // Declare some beans that can be used inside the script
            m_bsfManager.declareBean("map", map, Map.class);
            m_bsfManager.declareBean("ip_addr", svc.getIpAddr(), String.class);
            m_bsfManager.declareBean("node_id", svc.getNodeId(), int.class);
            m_bsfManager.declareBean("node_label", svc.getNodeLabel(), String.class);
            m_bsfManager.declareBean("svc_name", svc.getSvcName(), String.class);
            m_bsfManager.declareBean("bsf_monitor", this, BSFMonitor.class);
            m_bsfManager.declareBean("results", results, Map.class);
            m_bsfManager.declareBean("times", times, Map.class);
            for (final Entry<String, Object> entry : map.entrySet()) {
                m_bsfManager.declareBean(entry.getKey(), entry.getValue(), String.class);
            }
            pollStatus = PollStatus.unknown("The script did not update the service status");
            long startTime = System.currentTimeMillis();
            if ("eval".equals(runType)) {
                LOG.debug("m_bsfManager's hashCode is " + (m_bsfManager == null ? "null" : m_bsfManager.hashCode()) + "; lang is " + lang + "; code's hashCode is " + (code == null ? "null" : code.hashCode()));
                results.put("status", m_bsfManager.eval(lang, "BSFMonitor", 0, 0, code).toString());
            } else if ("exec".equals(runType)) {
                m_bsfManager.exec(lang, "BSFMonitor", 0, 0, code);
            } else {
                LOG.warn("Invalid run-type parameter value '{}' for service '{}'. Only 'eval' and 'exec' are supported.", runType, svc.getSvcName());
                throw new RuntimeException("Invalid run-type '" + runType + "'");
            }
            long endTime = System.currentTimeMillis();
            if (!times.containsKey(PollStatus.PROPERTY_RESPONSE_TIME)) {
                times.put(PollStatus.PROPERTY_RESPONSE_TIME, endTime - startTime);
            }
            if (STATUS_UNKNOWN.equals(results.get("status"))) {
                pollStatus = PollStatus.unknown(results.get("reason"));
            } else if (STATUS_UNRESPONSIVE.equals(results.get("status"))) {
                pollStatus = PollStatus.unresponsive(results.get("reason"));
            } else if (STATUS_AVAILABLE.equals(results.get("status"))) {
                pollStatus = PollStatus.available();
            } else if (STATUS_UNAVAILABLE.equals(results.get("status"))) {
                pollStatus = PollStatus.unavailable(results.get("reason"));
            } else {
                // Fall through to the old default of treating any other non-OK
                // code as meaning unavailable and also carrying the reason code
                pollStatus = PollStatus.unavailable(results.get("status"));
            }
            LOG.debug("Setting {} times for service '{}'", times.size(), svc.getSvcName());
            pollStatus.setProperties(times);
            if ("exec".equals(runType) && !results.containsKey("status")) {
                LOG.warn("The exec script '{}' for service '{}' never put a 'status' entry in the 'results' bean. Exec scripts should put this entry with a value of 'OK' for up.", fileName, svc.getSvcName());
            }
        } else {
            LOG.warn("Cannot locate or read BSF script file '{}'. Marking service '{}' down.", fileName, svc.getSvcName());
            pollStatus = PollStatus.unavailable("Cannot locate or read BSF script file: " + fileName);
        }
    } catch (BSFException e) {
        LOG.warn("BSFMonitor poll for service '{}' failed with BSFException: {}", svc.getSvcName(), e.getMessage(), e);
        pollStatus = PollStatus.unavailable(e.getMessage());
    } catch (FileNotFoundException e) {
        LOG.warn("Could not find BSF script file '{}'. Marking service '{}' down.", fileName, svc.getSvcName());
        pollStatus = PollStatus.unavailable("Could not find BSF script file: " + fileName);
    } catch (IOException e) {
        pollStatus = PollStatus.unavailable(e.getMessage());
        LOG.warn("BSFMonitor poll for service '{}' failed with IOException: {}", svc.getSvcName(), e.getMessage(), e);
    } catch (Throwable e) {
        // Catch any RuntimeException throws
        pollStatus = PollStatus.unavailable(e.getMessage());
        LOG.warn("BSFMonitor poll for service '{}' failed with unexpected throwable: {}", svc.getSvcName(), e.getMessage(), e);
    } finally {
        // remove the beans we've declared so the manager is ready for the next poll
        undeclareBeans(map);
    }
    return pollStatus;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) LinkedHashMap(java.util.LinkedHashMap) BSFException(org.apache.bsf.BSFException) File(java.io.File)

Example 5 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class BSFNorthbounder method initializeBSFEngine.

/**
 * Initialize BSF engine.
 *
 * @throws Exception the exception
 */
private void initializeBSFEngine() throws Exception {
    if (!BSFManager.isLanguageRegistered(m_engine.getLanguage())) {
        LOG.debug("registering BSF language {} using {}", m_engine.getLanguage(), m_engine.getClassName());
        BSFManager.registerScriptingEngine(m_engine.getLanguage(), m_engine.getClassName(), m_engine.getExtensions().split(","));
    }
    m_manager.registerBean("log", LOG);
    if (m_engine.getOnStart() != null) {
        LOG.debug("running start script for BSF engine {}", getName());
        try {
            m_manager.exec(m_engine.getLanguage(), "", 0, 0, m_engine.getOnStart());
        } catch (BSFException e) {
            throw new NorthbounderException("Cannot execute start script", e);
        }
    }
}
Also used : BSFException(org.apache.bsf.BSFException) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException)

Aggregations

BSFException (org.apache.bsf.BSFException)25 BSFManager (org.apache.bsf.BSFManager)11 File (java.io.File)5 IOException (java.io.IOException)5 FileInputStream (java.io.FileInputStream)4 FileNotFoundException (java.io.FileNotFoundException)3 InputStreamReader (java.io.InputStreamReader)3 BSFEngine (org.apache.bsf.BSFEngine)3 Script (groovy.lang.Script)2 HashMap (java.util.HashMap)2 SampleResult (org.apache.jmeter.samplers.SampleResult)2 NorthbounderException (org.opennms.netmgt.alarmd.api.NorthbounderException)2 BufferedInputStream (java.io.BufferedInputStream)1 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)1 LinkedHashMap (java.util.LinkedHashMap)1 StringTokenizer (java.util.StringTokenizer)1 WebContext (org.directwebremoting.WebContext)1 EvaluatorException (org.mozilla.javascript.EvaluatorException)1 JavaScriptException (org.mozilla.javascript.JavaScriptException)1 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)1