Example usage for javax.script ScriptEngine get

List of usage examples for javax.script ScriptEngine get

Introduction

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

Prototype

public Object get(String key);

Source Link

Document

Retrieves a value set in the state of this engine.

Usage

From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElementTest.java

/**
 * This is not a test case but more a kind of a sandbox for fiddling around with the script engine
 *//*  www .j a  va  2s. co  m*/
@Test
public void testEvaluateScriptWithReturn() throws Exception {

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer, true);
    engine.getContext().setWriter(pw);

    engine.eval(new FileReader("/home/mnxfst/git/stream-analyzer/src/main/resources/spahql.js"));

    String script = "var result0 = '1';var result1 = '2';";
    engine.eval(script);
    StringBuffer sb = writer.getBuffer();
    System.out.println("StringBuffer contains: " + sb + " - " + engine.get("test"));
    System.out.println(engine.get("content"));

    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        String content = (String) engine.get("result" + i);
        if (StringUtils.isBlank(content))
            break;
        System.out.println(content);
    }

    ObjectMapper mapper = new ObjectMapper();
    StreamEventMessage message = new StreamEventMessage();
    message.setIdentifier("test-id");
    message.setOrigin("test-origin");
    message.setTimestamp("2014-03-05");
    message.setEvent("10");
    //      message.addCustomAttribute("test-key-1", "3");
    //      message.addCustomAttribute("test-key-2", "value-1");
    //      message.addCustomAttribute("test-key-3", "19");
    //      message.addCustomAttribute("errors", (String)engine.get("test"));

    String json = mapper.writeValueAsString(message);
    System.out.println(json);
    StreamEventMessage msg = mapper.readValue(json, StreamEventMessage.class);
    System.out.println(message.getCustomAttributes().get("json"));

}

From source file:org.quackbot.hooks.loaders.JSHookLoader.java

@Override
public QListener load(String fileLocation) throws Exception {
    if (fileLocation.endsWith("JS_Template.js") || fileLocation.endsWith("QuackUtils.js"))
        //Ignore this
        return null;

    String[] pathParts = StringUtils.split(fileLocation, System.getProperty("file.separator"));
    String name = StringUtils.split(pathParts[pathParts.length - 1], ".")[0];
    log.info("New JavaScript Plugin: " + name);

    //Add utilities and wrappings
    ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    jsEngine.put("log", LoggerFactory.getLogger("JSPlugins." + name));
    LinkedHashMap<String, String> sourceMap = new LinkedHashMap();
    evalResource(jsEngine, sourceMap, "JSPluginBase/QuackUtils.js");
    evalResource(jsEngine, sourceMap, "JSPluginBase/JSCommand.js");
    evalResource(jsEngine, sourceMap, fileLocation);

    //Should we just ignore this?
    if (castToBoolean(jsEngine.get("ignore"))) {
        log.debug("Ignore variable set, skipping");
        return null;
    }//from w w w. j  a  v  a 2 s  .c om

    //Return the appropiate hook
    if (jsEngine.get("onCommand") != null)
        //Has Command functions, return command
        return new JSCommandWrapper(jsEngine, sourceMap, fileLocation, name);

    //Assume hook
    return new JSHookWrapper(jsEngine, sourceMap, fileLocation, name);
}

From source file:org.jwebsocket.plugins.scripting.app.js.JavaScriptApp.java

/**
 * Constructor/*  ww  w .j a  v a 2 s  .  c  o  m*/
 *
 * @param aServer The ScriptingPlugIn reference that allows to script
 * applications to get access to the TokenServer instance.
 * @param aAppName The application name (unique value)
 * @param aAppPath The application directory path
 * @param aScriptApp The scripting engine that runs the application
 * @param aLoader The application class loader
 */
@SuppressWarnings("OverridableMethodCallInConstructor")
public JavaScriptApp(ScriptingPlugIn aServer, String aAppName, String aAppPath, ScriptEngine aScriptApp,
        LocalLoader aLoader) {
    super(aServer, aAppName, aAppPath, aScriptApp, aLoader);

    try {
        File lAppTemplate = new File(JWebSocketConfig.getConfigFolder("ScriptingPlugIn/js/AppTemplate.js"));
        if (!lAppTemplate.exists()) {
            throw new RuntimeException(
                    "The JavaScript application template does not exists in expected location: "
                            + lAppTemplate.getPath() + "!");
        }

        eval(lAppTemplate.getPath());
        mApp = aScriptApp.get("App");
    } catch (Exception lEx) {
        throw new RuntimeException(lEx);
    }
}

From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java

private void invokeFunctionOrMethod(Shell shellState, ScriptEngine engine, CommandLine cl, Object[] args) {
    try {//  w  ww . j a v  a 2s . c om
        Invocable inv = (Invocable) engine;
        if (cl.hasOption(function.getOpt())) {
            inv.invokeFunction(cl.getOptionValue(function.getOpt()), args);
        } else if (cl.hasOption(object.getOpt())) {
            String objectMethod = cl.getOptionValue(object.getOpt());
            String[] parts = objectMethod.split(":");
            if (!(parts.length == 2)) {
                shellState.printException(new Exception("Object and Method must be supplied"));
                return;
            }
            String objectName = parts[0];
            String methodName = parts[1];
            Object obj = engine.get(objectName);
            inv.invokeMethod(obj, methodName, args);

        }
    } catch (Exception e) {
        shellState.printException(e);
    }
}

From source file:org.red5.server.script.rhino.RhinoScriptUtils.java

/**
 * Create a new Rhino-scripted object from the given script source.
 * /*from w  ww  . j a v  a2 s. co  m*/
 * @param scriptSource
 *            the script source text
 * @param interfaces
 *            the interfaces that the scripted Java object is supposed to
 *            implement
 * @param extendedClass
 * @return the scripted Java object
 * @throws ScriptCompilationException
 *             in case of Rhino parsing failure
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static Object createRhinoObject(String scriptSource, Class[] interfaces, Class extendedClass)
        throws ScriptCompilationException, IOException, Exception {
    if (log.isDebugEnabled()) {
        log.debug("Script Engine Manager: " + mgr.getClass().getName());
    }
    ScriptEngine engine = mgr.getEngineByExtension("js");
    if (null == engine) {
        log.warn("Javascript is not supported in this build");
    }
    // set engine scope namespace
    Bindings nameSpace = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    // add the logger to the script
    nameSpace.put("log", log);
    // compile the wrapper script
    CompiledScript wrapper = ((Compilable) engine).compile(jsWrapper);
    nameSpace.put("Wrapper", wrapper);

    // get the function name ie. class name / ctor
    String funcName = RhinoScriptUtils.getFunctionName(scriptSource);
    if (log.isDebugEnabled()) {
        log.debug("New script: " + funcName);
    }
    // set the 'filename'
    nameSpace.put(ScriptEngine.FILENAME, funcName);

    if (null != interfaces) {
        nameSpace.put("interfaces", interfaces);
    }

    if (null != extendedClass) {
        if (log.isDebugEnabled()) {
            log.debug("Extended: " + extendedClass.getName());
        }
        nameSpace.put("supa", extendedClass.newInstance());
    }
    //
    // compile the script
    CompiledScript script = ((Compilable) engine).compile(scriptSource);
    // eval the script with the associated namespace
    Object o = null;
    try {
        o = script.eval();
    } catch (Exception e) {
        log.error("Problem evaluating script", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Result of script call: " + o);
    }
    // script didnt return anything we can use so try the wrapper
    if (null == o) {
        wrapper.eval();
    } else {
        wrapper.eval();
        o = ((Invocable) engine).invokeFunction("Wrapper", new Object[] { engine.get(funcName) });
        if (log.isDebugEnabled()) {
            log.debug("Result of invokeFunction: " + o);
        }
    }
    return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), interfaces,
            new RhinoObjectInvocationHandler(engine, o));
}

From source file:de.tor.tribes.ui.components.GroupSelectionList.java

private List<Village> getVillagesByEquation() {
    StringBuilder b = new StringBuilder();
    boolean isFirst = true;
    List<Tag> relevantTags = new LinkedList<>();
    for (int i = 1; i < getModel().getSize(); i++) {
        ListItem item = getItemAt(i);//from  w w  w  .j  a va 2s. c o m
        boolean ignore = false;
        if (!isFirst) {
            switch (item.getState()) {
            case NOT:
                b.append(" && !");
                break;
            case AND:
                b.append(" && ");
                break;
            case OR:
                b.append(" || ");
                break;
            default:
                ignore = true;
            }
        } else {
            if (item.getState() == ListItem.RELATION_TYPE.DISABLED) {//ignore
                ignore = true;
            } else if (item.getState() == ListItem.RELATION_TYPE.NOT) {//NOT Tag 1
                b.append("!");
                isFirst = false;
            } else {
                isFirst = false;
            }
        }

        if (!ignore) {
            b.append(item.getTag().toString()).append(" ");
            relevantTags.add(item.getTag());
        }
    }

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String baseEquation = b.toString();

    List<Village> result = new LinkedList<>();
    try {
        if (relevantVillages == null) {
            relevantVillages = GlobalOptions.getSelectedProfile().getTribe().getVillageList();
        }
        for (Village v : relevantVillages) {
            String evaluationEquation = baseEquation;
            for (Tag tag : relevantTags) {
                evaluationEquation = evaluationEquation.replaceFirst(Pattern.quote(tag.toString()),
                        Boolean.toString(tag.tagsVillage(v.getId())));
            }
            engine.eval("var b = eval(\"" + evaluationEquation + "\")");
            if ((Boolean) engine.get("b")) {
                result.add(v);
            }
        }
    } catch (Exception e) {
        //no result
    }
    return result;
}

From source file:tk.elevenk.restfulrobot.testcase.TestCase.java

/**
 * Runs the given test script file/*  ww w .j  a va  2  s  .  c  o  m*/
 * 
 * @param fileName
 */
public void runScript(String fileName) {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    if (!fileName.endsWith(".js")) {
        fileName = fileName.concat(".js");
    }

    FileReader scriptFile = null;
    // attempt to open the script file
    try {
        scriptFile = new FileReader(new File(RestfulRobot.SCRIPTS_PATH + fileName));
    } catch (FileNotFoundException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // run the script
    try {
        logger.info("Running script " + fileName);
        engine.eval(scriptFile);
    } catch (ScriptException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // pull data from script
    try {
        this.testCaseID = (String) engine.get("testCaseID");
        this.testCategory = (String) engine.get("testCategory");
        this.testPlan = (String) engine.get("testPlan");
        this.testProject = (String) engine.get("testProject");
        this.testType = (String) engine.get("testType");
        this.testName = (String) engine.get("testName");
    } catch (Exception e) {
        // TODO make this try each parameter
    }

    logger.info("Finished running script");
}

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

public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin,
        long timestamp) throws JsonParseException, JsonMappingException, IOException, ScriptException {

    Map<String, String> inputDocs = new HashMap<String, String>();
    for (Map.Entry<String, SensorUpdate> inputSUEntry : inputSUs.entrySet()) {
        inputDocs.put(inputSUEntry.getKey(), this.mapper.writeValueAsString(inputSUEntry.getValue()));
    }// w w  w  .j  av a  2 s  .co  m
    PSOStream pstream = this.streams.get(streamId);
    if (!checkFilter(pstream.preFilter, inputDocs)) {
        return null;
    }
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    SensorUpdate su = new SensorUpdate();

    su.setLastUpdate(timestamp);
    su.setChannels(new LinkedHashMap<String, SUChannel>());

    int nulls = 0;
    for (Entry<String, PSOChannel> channelEntry : pstream.channels.entrySet()) {
        PSOChannel pchannel = channelEntry.getValue();
        SUChannel suChannel = new SUChannel();
        if (pchannel.currentValue == null) {
            suChannel.setCurrentValue(null);
            nulls++;
        } else {
            String currentValueCode = pchannel.currentValue.replace(inputDocs);
            Class type;
            String typeName;
            Object result = null;
            typeName = pchannel.type.toLowerCase();
            if (typeName.equals("number")) {
                type = Double.class;
            } else if (typeName.equals("boolean")) {
                type = Boolean.class;
            } else if (typeName.equals("string")) {
                type = String.class;
            } else if (typeName.equals("geo_point")) {
                type = GeoPoint.class;

            } else {
                return null;
            }

            engine.eval("var result = JSON.stringify(" + currentValueCode + ")");
            result = this.mapper.readValue((String) engine.get("result"), type);
            if (type == GeoPoint.class)
                result = ((GeoPoint) result).getLat() + "," + ((GeoPoint) result).getLon();
            suChannel.setCurrentValue(result);

        }
        suChannel.setUnit(pchannel.unit);

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

    if (nulls >= su.getChannels().size()) {
        // This stream is mapping a Web Object.
        return null;
    }

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

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

    this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String resultSUDoc = this.mapper.writeValueAsString(su);
    if (!inputDocs.containsKey("result")) {
        inputDocs.put("result", resultSUDoc);
    }

    if (!checkFilter(pstream.postFilter, inputDocs)) {
        return null;
    }
    return su;
}

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

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

    PageContext pageContext = null;/*from w w w .  j  av a2s  . com*/
    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: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 .  ja  va  2s .co  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;
}