boot/src/main/java/org/apidesign/html/boot/spi/Fn.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Thu, 09 Jan 2014 20:39:23 +0100
branchUniversalKO
changeset 446 6dce58c06f58
parent 434 e1fe37b03c3f
child 451 b75c076615a3
permissions -rw-r--r--
ko4j registers implementation of Transfer and WSTransfer based on XHR and WebSocket from a browser. The Java implementations of these interfaces has been moved to ko-ws-tyrus module. JavaScript arrays passed as parameters to Java callback methods need to be wrapped.
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2013 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package org.apidesign.html.boot.spi;
    44 
    45 import java.io.Closeable;
    46 import java.io.InputStream;
    47 import java.io.InputStreamReader;
    48 import java.io.Reader;
    49 import java.net.URL;
    50 import java.util.HashMap;
    51 import java.util.HashSet;
    52 import java.util.Map;
    53 import java.util.Set;
    54 import java.util.concurrent.Executor;
    55 import net.java.html.js.JavaScriptBody;
    56 import org.netbeans.html.boot.impl.FnContext;
    57 
    58 /** Represents single JavaScript function that can be invoked. 
    59  * Created via {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
    60  *
    61  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    62  */
    63 public abstract class Fn {
    64     private final Presenter presenter;
    65     
    66     /**
    67      * @deprecated Ineffective as of 0.6. 
    68      * Provide a presenter via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}
    69      * constructor
    70      */
    71     @Deprecated
    72     protected Fn() {
    73         this(null);
    74     }
    75     
    76     /** Creates new function object and associates it with given presenter.
    77      * 
    78      * @param presenter the browser presenter associated with this function
    79      * @since 0.6 
    80      */
    81     protected Fn(Presenter presenter) {
    82         this.presenter = presenter;
    83     }
    84 
    85     /** True, if currently active presenter is the same as presenter this
    86      * function has been created for via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}.
    87      * 
    88      * @return true, if proper presenter is used
    89      */
    90     public final boolean isValid() {
    91         return FnContext.currentPresenter(false) == presenter;
    92     }
    93     
    94     /** Helper method to check if the provided instance is valid function.
    95      * Checks if the parameter is non-null and if so, does {@link #isValid()}
    96      * check.
    97      * 
    98      * @param fnOrNull function or <code>null</code>
    99      * @return true if the parameter is non-null and valid
   100      * @since 0.7
   101      */
   102     public static boolean isValid(Fn fnOrNull) {
   103         return fnOrNull != null && fnOrNull.isValid();
   104     }
   105 
   106     /** Helper method to find current presenter and ask it to define new
   107      * function by calling {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
   108      * 
   109      * @param caller the class who wishes to define the function
   110      * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
   111      * @param names names of individual parameters
   112      * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
   113      * @since 0.7
   114      */
   115     public static Fn define(Class<?> caller, String code, String... names) {
   116         return FnContext.currentPresenter(false).defineFn(code, names);
   117     }
   118     
   119     private static final Map<String,Set<Presenter>> LOADED = new HashMap<String, Set<Presenter>>();
   120     
   121     /** Wraps function to ensure that the script represented by <code>resource</code>
   122      * gets loaded into the browser environment before the function <code>fn</code>
   123      * is executed.
   124      * 
   125      * @param fn original function to call
   126      * @param caller the class who wishes to define/call the function
   127      * @param resource resources (accessible via {@link ClassLoader#getResource(java.lang.String)}) 
   128      *   with a <em>JavaScript</em> that is supposed to loaded into the browser
   129      *   environment
   130      * @return function that ensures the script is loaded and then delegates
   131      *   to <code>fn</code>
   132      * @since 0.7
   133      */
   134     public static Fn preload(final Fn fn, final Class<?> caller, final String resource) {
   135         return new Fn() {
   136             @Override
   137             public Object invoke(Object thiz, Object... args) throws Exception {
   138                 final Presenter p = FnContext.currentPresenter(false);
   139                 Set<Presenter> there = LOADED.get(resource);
   140                 if (there == null) {
   141                     there = new HashSet<Presenter>();
   142                     LOADED.put(resource, there);
   143                 }
   144                 if (there.add(p)) {
   145                     InputStream is = caller.getClassLoader().getResourceAsStream(resource);
   146                     try {
   147                         InputStreamReader r = new InputStreamReader(is, "UTF-8");
   148                         p.loadScript(r);
   149                     } finally {
   150                         is.close();
   151                     }
   152                 }
   153                 return fn.invoke(thiz, args);
   154             }
   155         };
   156     }
   157     
   158     /** The currently active presenter.
   159      * 
   160      * @return the currently active presenter or <code>null</code>
   161      * @since 0.7
   162      */
   163     public static Presenter activePresenter() {
   164         return FnContext.currentPresenter(false);
   165     }
   166     
   167     /** Activates given presenter. Used by the code generated by 
   168      * {@link JavaScriptBody} annotation: 
   169      * <pre>
   170      * try ({@link Closeable} c = Fn.activate(presenter)) {
   171      *   doCallsInPresenterContext();
   172      * }
   173      * </pre>
   174      * 
   175      * @param p the presenter that should be active until closable is closed
   176      * @return the closable to close
   177      * @since 0.7
   178      */
   179     public static Closeable activate(Presenter p) {
   180         return FnContext.activate(p);
   181     }
   182     
   183     /** Invokes the defined function with specified <code>this</code> and
   184      * appropriate arguments.
   185      * 
   186      * @param thiz the meaning of <code>this</code> inside of the JavaScript
   187      *   function - can be <code>null</code>
   188      * @param args arguments for the function
   189      * @return return value from the function
   190      * @throws Exception if something goes wrong, as exception may be thrown
   191      */
   192     public abstract Object invoke(Object thiz, Object... args) throws Exception;
   193     
   194     /** Provides the function implementation access to the presenter provided
   195      * in {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter) the constructor).
   196      * 
   197      * @return presenter passed in in the constructor (may be, but should not be <code>null</code>)
   198      * @since 0.7
   199      */
   200     protected final Presenter presenter() {
   201         return presenter;
   202     }
   203 
   204     /** The representation of a <em>presenter</em> - usually a browser window.
   205      * Should be provided by a library included in the application and registered
   206      * in <code>META-INF/services</code>, for example with
   207      * <code>@ServiceProvider(service = Fn.Presenter.class)</code> annotation.
   208      * <p>
   209      * Since 0.7 a presenter may implement {@link Executor} interface, in case
   210      * it supports single threaded execution environment. The executor's
   211      * {@link Executor#execute(java.lang.Runnable)} method is then supposed
   212      * to invoke the runnable immediately (in case we are on the right thread
   213      * already) or return and asynchronously invoke the runnable later on the
   214      * right thread (if we are on wrong thread).
   215      */
   216     public interface Presenter {
   217         /** Creates new function with given parameter names and provided body.
   218          * 
   219          * @param code the body of the function. Can refer to variables named
   220          *   as <code>names</code>
   221          * @param names names of parameters of the function - these will be 
   222          *   available when the <code>code</code> body executes
   223          * 
   224          * @return function that can be later invoked
   225          */
   226         public Fn defineFn(String code, String... names);
   227         
   228         /** Opens the browser, loads provided page and when the
   229          * page is ready, it calls back to the provider runnable.
   230          * 
   231          * @param page the URL for the page to display
   232          * @param onPageLoad callback when the page is ready
   233          */
   234         public void displayPage(URL page, Runnable onPageLoad);
   235         
   236         /** Loads a script into the browser JavaScript interpreter and 
   237          * executes it.
   238          * @param code the script to execute
   239          * @throws Exception if something goes wrong, throw an exception
   240          */
   241         public void loadScript(Reader code) throws Exception;
   242     }
   243     
   244     /** Additional interface to be implemented by {@link Presenter}s that
   245      * wish to control what objects are passed into the JavaScript virtual 
   246      * machine.
   247      * <p>
   248      * If a JavaScript engine makes callback to Java method that returns 
   249      * a value, the {@link #toJavaScript(java.lang.Object)} method is
   250      * consulted to convert the Java value to something reasonable inside
   251      * JavaScript VM.
   252      * <p>
   253      * <em>Note:</em> The implementation based on <em>JavaFX</em> <code>WebView</code>
   254      * uses this interface to convert Java arrays to JavaScript ones.
   255      * 
   256      * @see Presenter
   257      * @since 0.7
   258      */
   259     public interface ToJavaScript {
   260         /** Convert a Java return value into some object suitable for
   261          * JavaScript virtual machine.
   262          * 
   263          * @param toReturn the Java object to be returned
   264          * @return the replacement value to return instead
   265          */
   266         public Object toJavaScript(Object toReturn);
   267     }
   268     
   269     /** Additional interface to be implemented by {@link Presenter}s that
   270      * need to convert JavaScript object (usually array) to Java object 
   271      * when calling back from JavaScript to Java.
   272      * <p>
   273      * <em>Note:</em> The implementation based on <em>JavaFX</em>
   274      * <code>WebView</code> uses this interface to convert JavaScript arrays to
   275      * Java ones.
   276       * 
   277      * @since 0.7
   278      */
   279     public interface FromJavaScript {
   280         /** Convert a JavaScript object into suitable Java representation
   281          * before a Java method is called with this object as an argument.
   282          * 
   283          * @param js the JavaScript object
   284          * @return replacement object for 
   285          */
   286         public Object toJava(Object js);
   287     }
   288 }