boot-script/src/main/java/net/java/html/boot/script/ScriptPresenter.java
changeset 674 a61fd3f48997
child 680 9fa36fee05e5
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/boot-script/src/main/java/net/java/html/boot/script/ScriptPresenter.java	Tue Jun 03 20:56:36 2014 +0200
     1.3 @@ -0,0 +1,244 @@
     1.4 +/**
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     1.6 + *
     1.7 + * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     1.8 + *
     1.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
    1.10 + * Other names may be trademarks of their respective owners.
    1.11 + *
    1.12 + * The contents of this file are subject to the terms of either the GNU
    1.13 + * General Public License Version 2 only ("GPL") or the Common
    1.14 + * Development and Distribution License("CDDL") (collectively, the
    1.15 + * "License"). You may not use this file except in compliance with the
    1.16 + * License. You can obtain a copy of the License at
    1.17 + * http://www.netbeans.org/cddl-gplv2.html
    1.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    1.19 + * specific language governing permissions and limitations under the
    1.20 + * License.  When distributing the software, include this License Header
    1.21 + * Notice in each file and include the License file at
    1.22 + * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    1.23 + * particular file as subject to the "Classpath" exception as provided
    1.24 + * by Oracle in the GPL Version 2 section of the License file that
    1.25 + * accompanied this code. If applicable, add the following below the
    1.26 + * License Header, with the fields enclosed by brackets [] replaced by
    1.27 + * your own identifying information:
    1.28 + * "Portions Copyrighted [year] [name of copyright owner]"
    1.29 + *
    1.30 + * Contributor(s):
    1.31 + *
    1.32 + * The Original Software is NetBeans. The Initial Developer of the Original
    1.33 + * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    1.34 + *
    1.35 + * If you wish your version of this file to be governed by only the CDDL
    1.36 + * or only the GPL Version 2, indicate your decision by adding
    1.37 + * "[Contributor] elects to include this software in this distribution
    1.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
    1.39 + * single choice of license, a recipient has the option to distribute
    1.40 + * your version of this file under either the CDDL, the GPL Version 2 or
    1.41 + * to extend the choice of license to its licensees as provided above.
    1.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
    1.43 + * Version 2 license, then the option applies only if the new code is
    1.44 + * made subject to such option by the copyright holder.
    1.45 + */
    1.46 +package net.java.html.boot.script;
    1.47 +
    1.48 +import java.io.Reader;
    1.49 +import java.net.URL;
    1.50 +import java.util.ArrayList;
    1.51 +import java.util.Arrays;
    1.52 +import java.util.List;
    1.53 +import java.util.logging.Level;
    1.54 +import java.util.logging.Logger;
    1.55 +import javax.script.Invocable;
    1.56 +import javax.script.ScriptEngine;
    1.57 +import javax.script.ScriptEngineManager;
    1.58 +import javax.script.ScriptException;
    1.59 +import org.apidesign.html.boot.spi.Fn;
    1.60 +import org.apidesign.html.boot.spi.Fn.Presenter;
    1.61 +
    1.62 +/** Implementation of {@link Presenter} that delegates
    1.63 + * to Java {@link ScriptEngine scripting} API. The presenter runs headless
    1.64 + * without appropriate simulation of browser APIs. Its primary usefulness
    1.65 + * is inside testing environments. 
    1.66 + * <p>
    1.67 + * One can load in browser simulation for example from 
    1.68 + * <a href="http://www.envjs.com/">env.js</a>. The best way to achieve so,
    1.69 + * is to add dependency on XXX
    1.70 + * 
    1.71 + *
    1.72 + * @author Jaroslav Tulach
    1.73 + */
    1.74 +public final class ScriptPresenter implements Presenter, Fn.FromJavaScript, Fn.ToJavaScript {
    1.75 +    private final ScriptEngine eng;
    1.76 +
    1.77 +    public ScriptPresenter() {
    1.78 +        try {
    1.79 +            eng = new ScriptEngineManager().getEngineByName("javascript");
    1.80 +            eng.eval("function alert(msg) { Packages.java.lang.System.out.println(msg); };");
    1.81 +        } catch (ScriptException ex) {
    1.82 +            throw new IllegalStateException(ex);
    1.83 +        }
    1.84 +    }
    1.85 +
    1.86 +    @Override
    1.87 +    public Fn defineFn(String code, String... names) {
    1.88 +        return defineImpl(code, names);
    1.89 +    }
    1.90 +    private FnImpl defineImpl(String code, String... names) {
    1.91 +        StringBuilder sb = new StringBuilder();
    1.92 +        sb.append("(function() {");
    1.93 +        sb.append("  return function(");
    1.94 +        String sep = "";
    1.95 +        if (names != null) for (String n : names) {
    1.96 +            sb.append(sep).append(n);
    1.97 +            sep = ",";
    1.98 +        }
    1.99 +        sb.append(") {\n");
   1.100 +        sb.append(code);
   1.101 +        sb.append("};");
   1.102 +        sb.append("})()");
   1.103 +
   1.104 +        final Object fn;
   1.105 +        try {
   1.106 +            fn = eng.eval(sb.toString());
   1.107 +        } catch (ScriptException ex) {
   1.108 +            throw new IllegalStateException(ex);
   1.109 +        }
   1.110 +        return new FnImpl(this, fn);
   1.111 +    }
   1.112 +
   1.113 +    @Override
   1.114 +    public void displayPage(URL page, Runnable onPageLoad) {
   1.115 +        // not really displaying anything
   1.116 +        if (onPageLoad != null) {
   1.117 +            onPageLoad.run();
   1.118 +        }
   1.119 +    }
   1.120 +
   1.121 +    @Override
   1.122 +    public void loadScript(Reader code) throws Exception {
   1.123 +        eng.eval(code);
   1.124 +    }
   1.125 +    
   1.126 +    //
   1.127 +    // array conversions
   1.128 +    //
   1.129 +    
   1.130 +    final Object convertArrays(Object[] arr) throws Exception {
   1.131 +        for (int i = 0; i < arr.length; i++) {
   1.132 +            if (arr[i] instanceof Object[]) {
   1.133 +                arr[i] = convertArrays((Object[]) arr[i]);
   1.134 +            }
   1.135 +        }
   1.136 +        final Object wrapArr = wrapArrFn().invokeImpl(null, false, arr); // NOI18N
   1.137 +        return wrapArr;
   1.138 +    }
   1.139 +
   1.140 +    private FnImpl wrapArrImpl;
   1.141 +    private FnImpl wrapArrFn() {
   1.142 +        if (wrapArrImpl == null) {
   1.143 +            try {
   1.144 +                wrapArrImpl = defineImpl("return Array.prototype.slice.call(arguments);");
   1.145 +            } catch (Exception ex) {
   1.146 +                throw new IllegalStateException(ex);
   1.147 +            }
   1.148 +        }
   1.149 +        return wrapArrImpl;
   1.150 +    }
   1.151 +
   1.152 +    final Object checkArray(Object val) throws Exception {
   1.153 +        final FnImpl fn = arraySizeFn();
   1.154 +        final Object fnRes = fn.invokeImpl(null, false, val, null);
   1.155 +        int length = ((Number) fnRes).intValue();
   1.156 +        if (length == -1) {
   1.157 +            return val;
   1.158 +        }
   1.159 +        Object[] arr = new Object[length];
   1.160 +        fn.invokeImpl(null, false, val, arr);
   1.161 +        return arr;
   1.162 +    }
   1.163 +    private FnImpl arraySize;
   1.164 +    private FnImpl arraySizeFn() {
   1.165 +        if (arraySize == null) {
   1.166 +            try {
   1.167 +                arraySize = defineImpl("\n"
   1.168 +                    + "if (to === null) {\n"
   1.169 +                    + "  if (Object.prototype.toString.call(arr) === '[object Array]') return arr.length;\n"
   1.170 +                    + "  else return -1;\n"
   1.171 +                    + "} else {\n"
   1.172 +                    + "  var l = arr.length;\n"
   1.173 +                    + "  for (var i = 0; i < l; i++) to[i] = arr[i];\n"
   1.174 +                    + "  return l;\n"
   1.175 +                    + "}", "arr", "to"
   1.176 +                );
   1.177 +            } catch (Exception ex) {
   1.178 +                throw new IllegalStateException(ex);
   1.179 +            }
   1.180 +        }
   1.181 +        return arraySize;
   1.182 +    }
   1.183 +
   1.184 +    @Override
   1.185 +    public Object toJava(Object jsArray) {
   1.186 +        try {
   1.187 +            return checkArray(jsArray);
   1.188 +        } catch (Exception ex) {
   1.189 +            throw new IllegalStateException(ex);
   1.190 +        }
   1.191 +    }
   1.192 +    
   1.193 +    @Override
   1.194 +    public Object toJavaScript(Object toReturn) {
   1.195 +        if (toReturn instanceof Object[]) {
   1.196 +            try {
   1.197 +                return convertArrays((Object[])toReturn);
   1.198 +            } catch (Exception ex) {
   1.199 +                throw new IllegalStateException(ex);
   1.200 +            }
   1.201 +        } else {
   1.202 +            return toReturn;
   1.203 +        }
   1.204 +    }
   1.205 +
   1.206 +    private class FnImpl extends Fn {
   1.207 +
   1.208 +        private final Object fn;
   1.209 +
   1.210 +        public FnImpl(Presenter presenter, Object fn) {
   1.211 +            super(presenter);
   1.212 +            this.fn = fn;
   1.213 +        }
   1.214 +
   1.215 +        @Override
   1.216 +        public Object invoke(Object thiz, Object... args) throws Exception {
   1.217 +            return invokeImpl(thiz, true, args);
   1.218 +        }
   1.219 +
   1.220 +            final Object invokeImpl(Object thiz, boolean arrayChecks, Object... args) throws Exception {
   1.221 +                List<Object> all = new ArrayList<Object>(args.length + 1);
   1.222 +                all.add(thiz == null ? fn : thiz);
   1.223 +                for (int i = 0; i < args.length; i++) {
   1.224 +                    if (arrayChecks) {
   1.225 +                        if (args[i] instanceof Object[]) {
   1.226 +                            Object[] arr = (Object[]) args[i];
   1.227 +                            Object conv = ((ScriptPresenter)presenter()).convertArrays(arr);
   1.228 +                            args[i] = conv;
   1.229 +                        }
   1.230 +                        if (args[i] instanceof Character) {
   1.231 +                            args[i] = (int)((Character)args[i]);
   1.232 +                        }
   1.233 +                    }
   1.234 +                    all.add(args[i]);
   1.235 +                }
   1.236 +                Object ret = ((Invocable)eng).invokeMethod(fn, "call", all.toArray()); // NOI18N
   1.237 +                if (ret == fn) {
   1.238 +                    return null;
   1.239 +                }
   1.240 +                if (!arrayChecks) {
   1.241 +                    return ret;
   1.242 +                }
   1.243 +                return ((ScriptPresenter)presenter()).checkArray(ret);
   1.244 +            }
   1.245 +    }
   1.246 +    
   1.247 +}