Example usage for javax.script ScriptEngine eval

List of usage examples for javax.script ScriptEngine eval

Introduction

In this page you can find the example usage for javax.script ScriptEngine eval.

Prototype

public Object eval(Reader reader) throws ScriptException;

Source Link

Document

Same as eval(String) except that the source of the script is provided as a Reader

Usage

From source file:org.apache.nifi.reporting.script.ScriptedReportingTask.java

@Override
public void onTrigger(final ReportingContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }// w  ww  .  j  a va 2s.c o  m
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }

    try {

        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("vmMetrics", vmMetrics);

            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }

            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());

            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }

}

From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java

/**
 * Start monitoring (as a thread) return when stopped
 *//*from w ww  .ja  v  a2 s  .c om*/
@Override
public void run() {
    try {
        while (!stopping) {

            long currentRun = new Date().getTime();
            logger.debug("Checking interval for {} at {}", name, currentRun);

            ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
            if (lastRun == null || lastRun + interval < currentRun) {
                logger.debug("Running interval for {} at {}", name, currentRun);

                // Run Monitors
                for (String monitorUrlHolderKey : monitorUrlHolders.keySet()) {
                    MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlHolderKey);

                    if (isFailed(monitorUrlHolder)) {
                        logger.debug("Reinitialising monitors as they are not connected");
                        initialiseMonitorUrl(monitorUrlHolder.getUrl(), monitorsConfiguration);
                    } else {
                        logger.debug("Executing Monitors");
                        Map<String, Object> results = new HashMap<String, Object>();
                        for (Monitor monitor : monitorUrlHolder.getMonitors()) {
                            try {
                                results.put(monitor.getName(), monitor.getReading());
                            } catch (ReadingFailedException e) {
                                results.put(monitor.getName(), e);
                                logger.error("{}", e);
                            }
                        }

                        for (String key : results.keySet()) {
                            scriptEngine.put(key, results.get(key));
                        }
                    }
                }
                for (String expression : expressions) {
                    try {
                        Object output = scriptEngine.eval(expression);
                        outputLogger.info("{}", output);
                    } catch (ScriptException e) {
                        logger.warn("Script Error {}", e);
                    }
                }
                // Run and output expressions
                lastRun = currentRun;
            }
            Thread.sleep(4000);
        }
    } catch (InterruptedException e) {
        logger.info("Interrupted", e);
    } catch (MalformedObjectNameException e) {
        logger.error("{}", e);
        throw new RuntimeException(e);
    } catch (MalformedURLException e) {
        logger.error("{}", e);
        throw new RuntimeException(e);
    } finally {
        // Tidy up all monitors / expressions IF possible
        alive = false;

    }

}

From source file:org.apache.jsp.fileUploader_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;/*w  ww  . j av a  2  s. c o  m*/
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<!--\n");
        out.write("Copyright 2012 The Infinit.e Open Source Project\n");
        out.write("\n");
        out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
        out.write("you may not use this file except in compliance with the License.\n");
        out.write("You may obtain a copy of the License at\n");
        out.write("\n");
        out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
        out.write("\n");
        out.write("Unless required by applicable law or agreed to in writing, software\n");
        out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
        out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
        out.write("See the License for the specific language governing permissions and\n");
        out.write("limitations under the License.\n");
        out.write("-->\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        out.write("<head>\n");
        out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
        out.write("<title>Infinit.e File Upload Tool</title>\n");
        out.write("<style media=\"screen\" type=\"text/css\">\n");
        out.write("\n");
        out.write("body \n");
        out.write("{\n");
        out.write("\tfont: 14px Arial,sans-serif;\n");
        out.write("}\n");
        out.write("h2\n");
        out.write("{\n");
        out.write("\tfont-family: \"Times New Roman\";\n");
        out.write("\tfont-style: italic;\n");
        out.write("\tfont-variant: normal;\n");
        out.write("\tfont-weight: normal;\n");
        out.write("\tfont-size: 24px;\n");
        out.write("\tline-height: 29px;\n");
        out.write("\tfont-size-adjust: none;\n");
        out.write("\tfont-stretch: normal;\n");
        out.write("\t-x-system-font: none;\n");
        out.write("\tcolor: #d2331f;\n");
        out.write("\tmargin-bottom: 25px;\n");
        out.write("}\n");
        out.write(".show {\n");
        out.write("display: ;\n");
        out.write("visibility: visible;\n");
        out.write("}\n");
        out.write(".hide {\n");
        out.write("display: none;\n");
        out.write("visibility: hidden;\n");
        out.write("}\n");
        out.write("</style>\n");
        out.write("<script language=\"javascript\" src=\"AppConstants.js\"> </script>\n");
        out.write("</head>\n");
        out.write("\n");
        out.write("<body onload=\"populate()\">\n");

        if (API_ROOT == null) {
            ServletContext context = session.getServletContext();
            String realContextPath = context.getRealPath("/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try { // EC2 Machines
                FileReader reader = new FileReader(realContextPath + "/AppConstants.js");
                engine.eval(reader);
                reader.close();
                engine.eval("output = getEndPointUrl();");
                API_ROOT = (String) engine.get("output");
                SHARE_ROOT = API_ROOT + "share/get/";
            } catch (Exception je) {
                try { ////////////Windows + Tomcat
                    FileReader reader = new FileReader(realContextPath + "\\..\\AppConstants.js");
                    engine.eval(reader);
                    reader.close();
                    engine.eval("output = getEndPointUrl();");
                    API_ROOT = (String) engine.get("output");
                    SHARE_ROOT = API_ROOT + "share/get/";
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (null == API_ROOT) {
                // Default to localhost
                API_ROOT = "http://localhost:8080/api/";
                SHARE_ROOT = "$infinite/share/get/";
            }

            if (API_ROOT.contains("localhost"))
                localCookie = true;
            else
                localCookie = false;
        }
        Boolean isLoggedIn = isLoggedIn(request, response);
        if (isLoggedIn == null) {
            out.println("The Infinit.e API cannot be reached.");
            out.println(API_ROOT);
        }

        else if (isLoggedIn == true) {
            showAll = (request.getParameter("sudo") != null);
            DEBUG_MODE = (request.getParameter("debug") != null);
            communityList = generateCommunityList(request, response);

            if (request.getParameter("logout") != null) {
                logOut(request, response);
                out.println("<div style=\" text-align: center;\">");
                out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                out.println("</div>");
            } else {

                out.println("<div style=\" text-align: center;\">");
                String contentType = request.getContentType();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                    //      Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                    //      Parse the request
                    FileItemIterator iter = upload.getItemIterator(request);
                    byte[] fileBytes = null;
                    String fileDS = null;
                    byte[] iconBytes = null;
                    String iconDS = null;
                    Set<String> communities = new HashSet<String>();
                    boolean isFileSet = false;
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        if (item.isFormField()) {
                            if (name.equalsIgnoreCase("communities")) {
                                communities.add(Streams.asString(stream));
                            } else
                                request.setAttribute(name, Streams.asString(stream));

                            //out.println("<b>" + name + ":</b>" + request.getAttribute(name).toString()+"</br>");
                        } else {
                            if (name.equalsIgnoreCase("file")) {
                                if (!item.getName().equals(""))
                                    isFileSet = true;
                                fileDS = item.getContentType();
                                fileBytes = IOUtils.toByteArray(stream);

                                // Check if this should be a java-archive (rather than just an octet stream)
                                if (fileDS.equals("application/octet-stream")) {
                                    ZipInputStream zis = new ZipInputStream(
                                            new ByteArrayInputStream(fileBytes));
                                    ZipEntry entry;
                                    while ((entry = zis.getNextEntry()) != null) {
                                        if (entry.getName().endsWith(".class")) {
                                            fileDS = "application/java-archive";
                                            break;
                                        }
                                    }
                                }
                                // Reset stream, and read
                            }
                        }
                    }

                    ////////////////////////////////////Delete Share ////////////////////////////////
                    if (request.getAttribute("deleteId") != null) {
                        String fileId = request.getAttribute("deleteId").toString();
                        if (fileId != null && fileId != "")
                            removeFromShare(fileId, request, response).toString();

                    }
                    ////////////////////////////////////Update Community Info////////////////////////////////
                    else if (null == fileBytes) {
                        String shareId = request.getAttribute("DBId").toString();
                        if (shareId != null && shareId != "")
                            addRemoveCommunities(shareId, communities, request, response);
                    } else {
                        //////////////////////////////////////////////////////////////////////////////////

                        Boolean newUpload = (request.getAttribute("DBId").toString().length() == 0);

                        ///////////////////////////////// SWF Manip  /////////////////////////////////
                        String shareId = request.getAttribute("DBId").toString();
                        String fileUrl = "";
                        String fileId = "";
                        String bin = request.getAttribute("binary").toString();
                        if (request.getAttribute("title") != null && request.getAttribute("description") != null
                                && fileBytes != null) {
                            if (!isFileSet) //if not a binary file or file was not changed
                            {
                                fileId = shareId;
                                if (shareId != null && shareId != "")
                                    addRemoveCommunities(shareId, communities, request, response);
                                out.println("File was not set, just updated communities.");
                            } else if (bin.equals("null")) //is a json file, make sure its okay and upload it
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        true, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            } else //is a binary, do normal
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        false, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            }

                            if (fileId.contains("Failed")) {
                                out.println(fileId);
                            } else {
                                fileUrl = SHARE_ROOT + fileId;
                                if (newUpload)
                                    out.println(
                                            "You have successfully added a file to the share, its location is: "
                                                    + fileUrl);
                                else
                                    out.println(
                                            "You have successfully updated a file on the share, its location is: "
                                                    + fileUrl);
                            }
                        } else {
                            fileUrl = null;
                            out.println("Error: Not enough information provided for file Upload");
                        }

                        ///////////////////////////////// End File Manip  /////////////////////////////////

                        out.println("</div>");
                    }
                } else {
                }

                out.write("\n");
                out.write("\t\n");
                out.write("\t<script>\n");
                out.write("\tfunction clearCommList()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  o.selected = false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction highlightComms(commList)\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  if(commList.indexOf(o.value) == -1)\n");
                out.write("\t\t\t\to.selected = false;\n");
                out.write("\t\t\t  else  \n");
                out.write("\t\t\t  \to.selected = true;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\tfunction populate()\n");
                out.write("\t{\n");
                out.write("\t\tvar typerow = document.getElementById('typerow');\n");
                out.write("\t\tvar type = document.getElementById('type');\n");
                out.write("\t\tvar title = document.getElementById('title');\n");
                out.write("\t\tvar description = document.getElementById('description');\n");
                out.write("\t\tvar file = document.getElementById('file');\n");
                out.write("\t\tvar created = document.getElementById('created');\n");
                out.write("\t\tvar DBId = document.getElementById('DBId');\n");
                out.write("\t\tvar deleteId = document.getElementById('deleteId');\n");
                out.write("\t\tvar deleteButton = document.getElementById('deleteButton');\n");
                out.write("\t\tvar share_url = document.getElementById('share_url');\n");
                out.write("\t\tvar owner_text = document.getElementById('owner_text');\n");
                out.write("\t\tvar owner = document.getElementById('owner');\n");
                out.write("\t\tvar url_row = document.getElementById('url_row');\n");
                out.write("\t\tvar dropdown = document.getElementById(\"upload_info\");\n");
                out.write("\t\tvar list = dropdown.options[dropdown.selectedIndex].value;\n");
                out.write("\t\tvar binary = document.getElementById(\"binary\");\n");
                out.write("\t\t\n");
                out.write("\t\tif (list == \"new\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"binary\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\tif ( list == \"newJSON\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"null\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\t//_id, created, title, description\n");
                out.write("\t\tsplit = list.split(\"$$$\");\n");
                out.write("\t\t\n");
                out.write("\t\tres_id = split[0];\n");
                out.write("\t\tres_created = split[1];\n");
                out.write("\t\tres_title = split[2];\n");
                out.write("\t\tres_description = split[3];\n");
                out.write("\t\tres_url = split[4];\n");
                out.write("\t\tcommunities = split[5];\n");
                out.write("\t\tres_owner = split[6];\n");
                out.write("\t\tres_binary = split[7];\t\t\n");
                out.write("\t\tres_type = split[8];\t\t\t\n");
                out.write("\t\t\n");
                out.write("\t\tif ( res_binary == \"null\" )\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t}\n");
                out.write("\t\telse\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t}\n");
                out.write("\t\ttitle.value = res_title;\n");
                out.write("\t\tdescription.value = res_description;\n");
                out.write("\t\tcreated.value = res_created;\n");
                out.write("\t\tDBId.value = res_id;\n");
                out.write("\t\tdeleteId.value = res_id;\n");
                out.write("\t\tshare_url.value = res_url;\n");
                out.write("\t\towner.value = res_owner;\t\t\n");
                out.write("\t\tdeleteButton.className = \"show\";\n");
                out.write("\t\towner.className = \"show\";\n");
                out.write("\t\towner_text.className = \"show\";\n");
                out.write("\t\turl_row.className = \"show\";\n");
                out.write("\t\thighlightComms(communities);\t\t\n");
                out.write("\t\tbinary.value = res_binary;\n");
                out.write("\t\ttype.value = res_type;\n");
                out.write("\t}\n");
                out.write("\t\tfunction validate_fields()\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle = document.getElementById('title').value;\n");
                out.write("\t\t\tdescription = document.getElementById('description').value;\n");
                out.write("\t\t\tfile = document.getElementById('file').value;\n");
                out.write("\t\t\tbinary = document.getElementById(\"binary\").value;\n");
                out.write("\t\t\ttype = document.getElementById(\"type\").value;\n");
                out.write("\t\t\t//share_url = document.getElementById('share_url').value;\n");
                out.write("\t\t\t//file_url = document.getElementById('file_url').value;\n");
                out.write("\t\t\t//file_check = document.getElementById('file_check').checked;\n");
                out.write("\t\t\t\n");
                out.write("\t\t\tif (title == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a title.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif (description == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a description.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif ( binary == \"null\" && type == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a type.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\t\n");
                out.write("\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction confirmDelete()\n");
                out.write("\t\t{\n");
                out.write(
                        "\t\t\tvar agree=confirm(\"Are you sure you wish to Delete this file from the File Share?\");\n");
                out.write("\t\t\tif (agree)\n");
                out.write("\t\t\t\treturn true ;\n");
                out.write("\t\t\telse\n");
                out.write("\t\t\t\treturn false ;\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction showResults()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tvar title = document.getElementById('DBId').value;\n");
                out.write("\t\t\tvar url = getEndPointUrl() + \"share/get/\" + title;\n");
                out.write("\t\t\twindow.open(url, '_blank');\n");
                out.write("\t\t\twindow.focus();\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\t// -->\n");
                out.write("\t\t</script>\n");
                out.write("\t</script>\n");
                out.write(
                        "\t\t<div id=\"uploader_outter_div\" name=\"uploader_outter_div\" align=\"center\" style=\"width:100%\" >\n");
                out.write(
                        "\t    \t<div id=\"uploader_div\" name=\"uploader_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:475px; margin:auto\">\n");
                out.write("\t        \t<h2>File Uploader</h2>\n");
                out.write("\t        \t<form id=\"search_form\" name=\"search_form\" method=\"get\">\n");
                out.write("\t        \t\t<div align=\"center\"\">\n");
                out.write("\t        \t\t<label for=\"ext\">Filter On</label>\n");
                out.write("\t\t\t\t\t  <select name=\"ext\" id=\"ext\" onchange=\"this.form.submit();\">\n");
                out.write("\t\t\t\t\t    ");

                out.print(populateMediaTypes(request, response));

                out.write("\n");
                out.write("\t\t\t\t\t  </select>\n");
                out.write("\t\t\t\t\t </div>\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t        \t<form id=\"delete_form\" name=\"delete_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return confirmDelete()\" >\n");
                out.write(
                        "\t        \t\t<select id=\"upload_info\" onchange=\"populate()\" name=\"upload_info\"><option value=\"new\">Upload New File</option><option value=\"newJSON\">Upload New JSON</option> ");

                out.print(populatePreviousUploads(request, response));

                out.write("</select>\n");
                out.write(
                        "\t        \t\t<input type=\"submit\" name=\"deleteButton\" id=\"deleteButton\" class=\"hidden\" value=\"Delete\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteId\" id=\"deleteId\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteFile\" id=\"deleteFile\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t            <form id=\"upload_form\" name=\"upload_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return validate_fields();\" >\n");
                out.write(
                        "\t                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px; padding-right:10px\">\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td colspan=\"2\" align=\"center\"></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Title:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"title\" id=\"title\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Description:</td>\n");
                out.write(
                        "\t                    <td><textarea rows=\"4\" cols=\"30\" name=\"description\" id=\"description\" ></textarea></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"typerow\">\n");
                out.write("\t                    <td>Type:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"type\" id=\"type\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td>Communities:</td>\n");
                out.write("\t                  \t<td>");

                out.print(communityList);

                out.write("</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td id=\"owner_text\">Owner:</td>\n");
                out.write("\t                  \t<td>\n");
                out.write(
                        "\t                    <input type=\"text\" name=\"owner\" id=\"owner\" readonly=\"readonly\" size=\"25\" />\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>File:</td>\n");
                out.write("\t                    <td><input type=\"file\" name=\"file\" id=\"file\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"url_row\" class=\"hide\">\n");
                out.write("\t                  \t<td>Share URL:</td>\n");
                out.write(
                        "\t                  \t<td><input type=\"text\" name=\"share_url\" id=\"share_url\" readonly=\"readonly\" size=\"38\"/>\n");
                out.write(
                        "\t                  \t<input type=\"button\" onclick=\"showResults()\" value=\"View\"/>\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                \t<td></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write(
                        "\t                    <td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"Submit\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                </table>\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"created\" id=\"created\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"DBId\" id=\"DBId\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"fileUrl\" id=\"fileUrl\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"binary\" id=\"binary\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t\t\t\t</form>\n");
                out.write("\t        </div>\n");
                out.write("\t        <form id=\"logout_form\" name=\"logout_form\" method=\"post\">\n");
                out.write(
                        "\t        \t<input type=\"submit\" name=\"logout\" id = \"logout\" value=\"Log Out\" />\n");
                out.write("\t        </form>\n");
                out.write("\t    </div>\n");
                out.write("\t    </p>\n");
                out.write("\t\n");

            }
        } else if (isLoggedIn == false) {
            //localCookie =(request.getParameter("local") != null);
            //System.out.println("LocalCookie = " + localCookie.toString());
            String errorMsg = "";
            if (request.getParameter("logintext") != null || request.getParameter("passwordtext") != null) {
                if (logMeIn(request.getParameter("logintext"), request.getParameter("passwordtext"), request,
                        response)) {
                    showAll = (request.getParameter("sudo") != null);
                    out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                    out.println("Login Success");
                } else {
                    errorMsg = "Log in Failed, Please Try again";
                }

            }

            out.write("\n");
            out.write("\n");
            out.write("<script>\n");
            out.write("\tfunction validate_fields()\n");
            out.write("\t{\n");
            out.write("\t\tuname = document.getElementById('logintext').value;\n");
            out.write("\t\tpword = document.getElementById('passwordtext').value;\n");
            out.write("\t\t\n");
            out.write("\t\tif (uname == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your username.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t\tif (pword == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your password.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t}\n");
            out.write("\n");
            out.write("\n");
            out.write("</script>\n");
            out.write(
                    "\t<div id=\"login_outter_div\" name=\"login_outter_div\" align=\"center\" style=\"width:100%\" >\n");
            out.write(
                    "    \t<div id=\"login_div\" name=\"login_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:450px; margin:auto\">\n");
            out.write("        \t<h2>Login</h2>\n");
            out.write(
                    "            <form id=\"login_form\" name=\"login_form\" method=\"post\" onsubmit=\"javascript:return validate_fields();\" >\n");
            out.write(
                    "                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px\">\n");
            out.write("                  <tr>\n");
            out.write("                    <td>User Name</td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write("                    <td>Password</td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td><input type=\"text\" name=\"logintext\" id=\"logintext\" width=\"190px\" /></td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write(
                    "                    <td><input type=\"password\" name=\"passwordtext\" id=\"passwordtext\" width=\"190px\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td colspan=\"3\" align=\"right\"><input name=\"Login\" type=\"submit\" value=\"Login\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                </table>\n");
            out.write("\t\t\t</form>\n");
            out.write("        </div>\n");
            out.write("    </div>\n");
            out.write("\t<div style=\"color: red; text-align: center;\"> ");
            out.print(errorMsg);
            out.write(" </div>\n");

        }

        out.write("\n");
        out.write("    \n");
        out.write("    \n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

private void execAppBeforeLoadChecks(final String aAppName, String aAppPath) throws Exception {
    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");
    if (!lManifestFile.exists() || !lManifestFile.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Manifest file no found!";
        mLog.error(lMsg);// ww  w  . ja va2  s  .  co m
        throw new FileNotFoundException(lMsg);
    }
    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // checking jWebSocket version 
    Manifest.checkJwsVersion(lManifestJSON.getString(Manifest.JWEBSOCKET_VERSION, "1.0.0"));

    // checking jWebSocket plug-ins dependencies
    Manifest.checkJwsDependencies(
            lManifestJSON.getList(Manifest.JWEBSOCKET_PLUGINS_DEPENDENCIES, new ArrayList<String>()));

    // checking sandbox permissions dependency
    Manifest.checkPermissions(lManifestJSON.getList(Manifest.PERMISSIONS, new ArrayList()),
            mSettings.getAppPermissions(aAppName, aAppPath), aAppPath);

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);
    if (!lBootstrap.exists() || !lBootstrap.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Bootstrap file not found!";
        mLog.error(lMsg);
        throw new FileNotFoundException(lMsg);
    }

    LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
    ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

    final ScriptEngine lScriptApp;
    final BaseScriptApp lApp;
    if ("js".equals(lExt)) {
        // making "nashorn" the default engine for JavaScript
        if (null != lManager.getEngineByName("nashorn")) {
            lScriptApp = lManager.getEngineByName("nashorn");
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }
    } else {
        lScriptApp = lManager.getEngineByExtension(lExt);
    }

    // creating the high level script app instance
    if ("js".equals(lExt)) {
        lApp = new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader);
    } else {
        String lMsg = "The extension '" + lExt + "' is not currently supported!";
        mLog.error(lMsg);
        throw new Exception(lMsg);
    }

    // loading application into security sandbox
    Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                // evaluating app content
                lScriptApp.eval(FileUtils.readFileToString(lBootstrap));
                return null;
            } catch (Exception lEx) {
                String lAction = (mApps.containsKey(aAppName)) ? "reloaded" : "loaded";
                String lMsg = "Script applicaton '" + aAppName + "' not " + lAction
                        + " because it failed the 'before-load' checks: " + lEx.getMessage();
                mLog.info(lMsg);
                throw new RuntimeException(lMsg);
            }
        }
    });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application passed the 'before-load' checks successfully!");
    }
}

From source file:org.apache.nifi.processors.script.ExecuteScript.java

/**
 * Evaluates the given script body (or file) using the current session, context, and flowfile. The script
 * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script
 * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a
 * FlowFile, the original FlowFile will be routed to no-flowfile
 *
 * @param context        the current process context
 * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which
 *                       can be used for accessing FlowFiles, etc.
 * @throws ProcessException if the scripted processor's onTrigger() method throws an exception
 */// w  ww  . j a va 2 s  .c  o  m
@Override
public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }
    ProcessSession session = sessionFactory.createSession();
    try {

        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("session", session);
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("REL_SUCCESS", REL_SUCCESS);
            bindings.put("REL_FAILURE", REL_FAILURE);

            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }

            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());

            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }

            // Commit this session for the user. This plus the outermost catch statement mimics the behavior
            // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base
            // class with InvokeScriptedProcessor
            session.commit();
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        session.rollback(true);
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }
}

From source file:org.apache.solr.update.processor.StatelessScriptUpdateProcessorFactory.java

/**
 * Initializes a list of script engines - an engine per script file.
 *
 * @param req The solr request.// ww  w .ja v  a 2s  . c o m
 * @param rsp The solr response
 * @return The list of initialized script engines.
 */
private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp) throws SolrException {

    List<EngineInfo> scriptEngines = new ArrayList<>();

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager(resourceLoader.getClassLoader());

    scriptEngineManager.put("logger", log);
    scriptEngineManager.put("req", req);
    scriptEngineManager.put("rsp", rsp);
    if (params != null) {
        scriptEngineManager.put("params", params);
    }

    for (ScriptFile scriptFile : scriptFiles) {
        ScriptEngine engine = null;
        if (null != engineName) {
            engine = scriptEngineManager.getEngineByName(engineName);
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, false);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by name: "
                        + engineName + (null != details ? " -- supported names: " + details : ""));
            }
        } else {
            engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension());
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, true);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "No ScriptEngine found by file extension: " + scriptFile.getFileName()
                                + (null != details ? " -- supported extensions: " + details : ""));

            }
        }

        if (!(engine instanceof Invocable)) {
            String msg = "Engine "
                    + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName()))
                    + " does not support function invocation (via Invocable): " + engine.getClass().toString()
                    + " (" + engine.getFactory().getEngineName() + ")";
            log.error(msg);
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);
        }

        if (scriptEngineCustomizer != null) {
            scriptEngineCustomizer.customize(engine);
        }

        scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile));
        try {
            Reader scriptSrc = scriptFile.openReader(resourceLoader);

            try {
                engine.eval(scriptSrc);
            } catch (ScriptException e) {
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "Unable to evaluate script: " + scriptFile.getFileName(), e);
            } finally {
                IOUtils.closeQuietly(scriptSrc);
            }
        } catch (IOException ioe) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unable to evaluate script: " + scriptFile.getFileName(), ioe);
        }
    }
    return scriptEngines;
}

From source file:com.servioticy.dispatcher.SOProcessor020.java

public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin,
        long timestamp) throws IOException, ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    SensorUpdate su = new SensorUpdate();

    su.setLastUpdate(timestamp);//from   w w w  . j av  a2  s  . c  o m
    su.setChannels(new LinkedHashMap<String, SUChannel>());

    SOStream stream = so.getStreams(this.mapper).get(streamId);
    for (Map.Entry<String, SOChannel> channelEntry : stream.getChannels().entrySet()) {
        SOChannel channel = channelEntry.getValue();
        SUChannel suChannel = new SUChannel();
        String currentValueCode = channel.getCurrentValue();
        // TODO Check for invalid calls
        // TODO Check for an invalid header
        if (isFunction(currentValueCode)) {
            // There is no code for one of the channels. Invalid.
            return null;
        } else {
            TypeReference type;
            Class dataClass;
            boolean array = false;

            switch (parseType(channel.getType())) {
            case TYPE_ARRAY_NUMBER:
                type = new TypeReference<List<Double>>() {
                };
                array = true;
                break;
            case TYPE_NUMBER:
                type = new TypeReference<Double>() {
                };
                break;
            case TYPE_ARRAY_BOOLEAN:
                type = new TypeReference<List<Boolean>>() {
                };
                array = true;
                break;
            case TYPE_BOOLEAN:
                type = new TypeReference<Boolean>() {
                };
                break;
            case TYPE_ARRAY_STRING:
                type = new TypeReference<List<String>>() {
                };
                array = true;
                break;
            case TYPE_STRING:
                type = new TypeReference<String>() {
                };
                break;
            // non-primitive types
            case TYPE_ARRAY_GEOPOINT:
                type = new TypeReference<List<GeoPoint>>() {
                };
                array = true;
                break;
            case TYPE_GEOPOINT:
                type = new TypeReference<GeoPoint>() {
                };
                break;
            default:
                return null;
            }

            String resultVar = "$" + Long.toHexString(UUID.randomUUID().getMostSignificantBits());

            engine.eval(initializationCode(inputSUs, origin) + "var " + resultVar + " = JSON.stringify("
                    + currentValueCode + "(" + functionArgsString(currentValueCode) + ")" + ")");
            Object result = this.mapper.readValue((String) engine.get(resultVar), type);

            if (result == null) {
                // Filtered output. The type is not the expected one.
                return null;
            }
            suChannel.setCurrentValue(result);
        }
        suChannel.setUnit(channel.getUnit());

        su.getChannels().put(channelEntry.getKey(), suChannel);
    }

    su.setTriggerPath(new ArrayList<ArrayList<String>>());

    su.setPathTimestamps(new ArrayList<Long>());

    return su;
}

From source file:org.jumpmind.metl.core.runtime.component.Script.java

@Override
protected void start() {
    String importStatements = getComponent().get(IMPORTS);
    String initScript = getComponent().get(INIT_SCRIPT);
    String handleMessageScript = getComponent().get(HANDLE_SCRIPT);
    String methods = getComponent().get(METHODS);
    String onSuccess = getComponent().get(ON_FLOW_SUCCESS);
    String onError = getComponent().get(ON_FLOW_ERROR);

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("groovy");

    engine.put("component", this);
    StringBuilder script = new StringBuilder();
    try {//from   w ww . j av  a  2s  . co  m
        script.append(String.format("import %s;\n", ISendMessageCallback.class.getName()));
        script.append(String.format("import %s;\n", File.class.getName()));
        script.append(String.format("import %s;\n", FileUtils.class.getName()));
        script.append(String.format("import static %s.*;\n", FileUtils.class.getName()));
        script.append(String.format("import %s.*;\n", Message.class.getPackage().getName()));
        script.append(String.format("import %s;\n", ScriptHelper.class.getName()));
        script.append(String.format("import %s;\n", EntityDataMessage.class.getName()));
        script.append(String.format("import %s;\n", TextMessage.class.getName()));
        script.append(String.format("import %s;\n", ControlMessage.class.getName()));
        script.append(String.format("import %s;\n", BinaryMessage.class.getName()));
        script.append(String.format("import %s;\n", MisconfiguredException.class.getName()));
        script.append(String.format("import %s;\n", AssertException.class.getName()));
        script.append(
                String.format("import %s.%s;\n", EntityData.class.getName(), ChangeType.class.getSimpleName()));
        script.append("import org.jumpmind.db.sql.*;\n");
        if (isNotBlank(importStatements)) {
            script.append(importStatements);
        }
        script.append("\n");
        script.append(String.format("helper = new %1$s(component) { \n", ScriptHelper.class.getSimpleName()));

        if (isNotBlank(methods)) {
            script.append("\n");
            script.append(String.format("%s\n", methods));
        }

        if (isNotBlank(initScript)) {
            script.append("\n");
            script.append(String.format(" protected void onInit() { %s \n} \n", initScript));
        }
        if (isNotBlank(handleMessageScript)) {
            script.append("\n");
            script.append(String.format(" protected void onHandle() { %s \n} \n", handleMessageScript));
        }
        if (isNotBlank(onSuccess)) {
            script.append("\n");
            script.append(String.format(" protected void onSuccess() { %s \n} \n", onSuccess));
        }
        if (isNotBlank(onError)) {
            script.append("\n");
            script.append(String.format(" protected void onError(Throwable myError) { %s \n} \n", onError));
        }
        script.append("\n};\n");

        log(LogLevel.DEBUG, script.toString());
        script.append("helper.onInit();");
        engine.eval(script.toString());
        this.engine = engine;
    } catch (ScriptException e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null) {
            if (rootCause instanceof RuntimeException) {
                throw (RuntimeException) rootCause;
            } else {
                throw new RuntimeException(rootCause);
            }
        } else {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.samjoey.gui.GraphicalViewer.java

private void selectedPGN(File file) {

    String fileLoc = file.getAbsolutePath();
    //fileLoc = "File:" + fileLoc.substring(2);
    if (fileLoc.substring(fileLoc.length() - 3).equals("pgn")) {
        for (int i = 0; i < fileLoc.length(); i++) {
            if (fileLoc.substring(i, i + 1).equals("/")) {
                fileLoc = fileLoc.substring(0, i) + "\\" + fileLoc.substring(i + 1);
            }/*w  ww  .  j ava2  s.  co  m*/
        }
        try {
            // Below: Talk to JavaScript
            ScriptEngineManager factory = new ScriptEngineManager();
            // create JavaScript engine
            final ScriptEngine engine = factory.getEngineByName("JavaScript");
            // evaluate JavaScript code from given file - specified by first argument
            engine.put("engine", engine);
            ClassLoader cl = GraphicalViewer.class.getClassLoader();
            // Talk to GameLooper_1
            URL url = cl.getResource("\\org\\samjoey\\gameLooper\\GameLooper_1.js");
            String loopLoc = url.toString().substring(5);
            for (int i = 0; i < loopLoc.length() - 3; i++) {
                if (loopLoc.substring(i, i + 3).equals("%5c")) {
                    loopLoc = loopLoc.substring(0, i) + "/" + loopLoc.substring(i + 3);
                }
            }
            engine.put("loopLoc", loopLoc);
            // Talk to calcDefs_1
            url = cl.getResource("\\org\\samjoey\\calculator\\calcDefs_1.js");
            String defsLoc = url.toString().substring(5);
            for (int i = 0; i < defsLoc.length() - 3; i++) {
                if (defsLoc.substring(i, i + 3).equals("%5c")) {
                    defsLoc = defsLoc.substring(0, i) + "/" + defsLoc.substring(i + 3);
                }
            }
            engine.put("defsLoc", defsLoc);
            // Talk to Calculator
            url = cl.getResource("\\org\\samjoey\\calculator\\Calculator.js");
            String calcLoc = url.toString().substring(5);
            for (int i = 0; i < calcLoc.length() - 3; i++) {
                if (calcLoc.substring(i, i + 3).equals("%5c")) {
                    calcLoc = calcLoc.substring(0, i) + "/" + calcLoc.substring(i + 3);
                }
            }
            engine.put("calcLoc", calcLoc);
            String args[] = { "-g:false", fileLoc };
            engine.put("arguments", args);

            // Create a Thread to update the parser's progress bar
            parserProgress.setStringPainted(true);
            running = false;
            running = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    long last = 0l;
                    boolean print = true;
                    double p = .01;
                    while (engine.get("progress") == null || engine.get("size") == null
                            || Integer.parseInt((String) engine.get("progress")) != Integer
                                    .parseInt((String) engine.get("size"))) {
                        //if (Parser.numGames > 0 && Parser.progress == Parser.numGames) {
                        try {
                            parserProgress.setValue(Integer.parseInt((String) engine.get("progress")));
                            parserProgress.setMaximum(Integer.parseInt((String) engine.get("size")));
                            if (last == 0l) {
                                last = System.nanoTime();
                            }
                            if ((double) parserProgress.getValue() / (double) parserProgress.getMaximum() > p
                                    && print) {
                                //System.out.println(p + ": " + (System.nanoTime() - last));
                                //print = false;
                                p += .01;
                            }
                        } catch (Exception e) {
                        }
                        //} else {
                        //    parserProgress.setMaximum(Parser.numGames - 1);
                        //    parserProgress.setMinimum(0);
                        //    parserProgress.setValue(Parser.progress);
                        //}
                    }
                    // finally
                    parserProgress.setValue(parserProgress.getMaximum());
                }
            };
            thread.start();

            // I have no clue what's here!??
            engine.eval(new java.io.FileReader(
                    GraphicalViewer.class.getClassLoader().getResource("driver_1.js").toString().substring(5)));
            while (games == null || games.get((int) (Math.random() * games.size())).getVarData().size() < 20) {
                games = (LinkedList<Game>) engine.get("gameList");
            }
        } catch (ScriptException | FileNotFoundException ex) {
            Logger.getLogger(GraphicalViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (fileLoc.substring(fileLoc.length() - 4).equals("jsca")) {
        JSCAParser jsca = new JSCAParser(fileLoc);
        games = (LinkedList<Game>) jsca.getGamesList();
    }

    Set<String> keys = games.get(0).getVarData().keySet();
    for (String key : keys) {
        Variable_Chooser.addItem(key);
    }
    graphs = GraphUtility.getGraphs(games);

    setViewer(0, 0);
}

From source file:org.unitime.timetable.server.script.ScriptExecution.java

@Override
protected void execute() throws Exception {
    org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession();

    Transaction tx = hibSession.beginTransaction();
    try {/*from   ww w.j  av a 2 s  . co m*/
        setStatus("Starting up...", 3);

        Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession);

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName(script.getEngine());
        engine.put("hibSession", hibSession);
        engine.put("session", SessionDAO.getInstance().get(getSessionId()));
        engine.put("log", this);

        incProgress();

        engine.getContext().setWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    info(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });
        engine.getContext().setErrorWriter(new Writer() {
            @Override
            public void write(char[] cbuf, int off, int len) throws IOException {
                String line = String.valueOf(cbuf, off, len);
                if (line.endsWith("\n"))
                    line = line.substring(0, line.length() - 1);
                if (!line.isEmpty())
                    warn(line);
            }

            @Override
            public void flush() throws IOException {
            }

            @Override
            public void close() throws IOException {
            }
        });

        incProgress();

        debug("Engine: " + engine.getFactory().getEngineName() + " (ver. "
                + engine.getFactory().getEngineVersion() + ")");
        debug("Language: " + engine.getFactory().getLanguageName() + " (ver. "
                + engine.getFactory().getLanguageVersion() + ")");

        for (ScriptParameter parameter : script.getParameters()) {
            String value = iRequest.getParameters().get(parameter.getName());

            if ("file".equals(parameter.getType()) && iFile != null) {
                debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)");
                engine.put(parameter.getName(), iFile);
                continue;
            }

            if (value == null)
                value = parameter.getDefaultValue();
            if (value == null) {
                engine.put(parameter.getName(), null);
                continue;
            }
            debug(parameter.getName() + ": " + value);

            if (parameter.getType().equalsIgnoreCase("boolean")) {
                engine.put(parameter.getName(), "true".equalsIgnoreCase(value));
            } else if (parameter.getType().equalsIgnoreCase("long")) {
                engine.put(parameter.getName(), Long.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("int")
                    || parameter.getType().equalsIgnoreCase("integer")) {
                engine.put(parameter.getName(), Integer.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("double")) {
                engine.put(parameter.getName(), Double.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("float")) {
                engine.put(parameter.getName(), Float.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("short")) {
                engine.put(parameter.getName(), Short.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("byte")) {
                engine.put(parameter.getName(), Byte.valueOf(value));
            } else if (parameter.getType().equalsIgnoreCase("department")) {
                engine.put(parameter.getName(),
                        DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("departments")) {
                List<Department> departments = new ArrayList<Department>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), departments);
            } else if (parameter.getType().equalsIgnoreCase("subject")) {
                engine.put(parameter.getName(),
                        SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("subjects")) {
                List<SubjectArea> subjects = new ArrayList<SubjectArea>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), subjects);
            } else if (parameter.getType().equalsIgnoreCase("building")) {
                engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("buildings")) {
                List<Building> buildings = new ArrayList<Building>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), buildings);
            } else if (parameter.getType().equalsIgnoreCase("room")) {
                engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("rooms")) {
                List<Room> rooms = new ArrayList<Room>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), rooms);
            } else if (parameter.getType().equalsIgnoreCase("location")) {
                engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession));
            } else if (parameter.getType().equalsIgnoreCase("locations")) {
                List<Location> locations = new ArrayList<Location>();
                for (String id : value.split(","))
                    if (!id.isEmpty())
                        locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession));
                engine.put(parameter.getName(), locations);
            } else {
                engine.put(parameter.getName(), value);
            }
        }

        incProgress();

        if (engine instanceof Compilable) {
            setStatus("Compiling script...", 1);
            CompiledScript compiled = ((Compilable) engine).compile(script.getScript());
            incProgress();
            setStatus("Running script...", 100);
            compiled.eval();
        } else {
            setStatus("Running script...", 100);
            engine.eval(script.getScript());
        }

        hibSession.flush();
        tx.commit();

        setStatus("All done.", 1);
        incProgress();
    } catch (Exception e) {
        tx.rollback();
        error("Execution failed: " + e.getMessage(), e);
    } finally {
        hibSession.close();
    }
}