boot/src/main/java/org/netbeans/html/boot/spi/Fn.java
author Jaroslav Tulach <jtulach@netbeans.org>
Fri, 12 Dec 2014 11:22:40 +0100
branchgc
changeset 900 2ee22312e414
parent 838 bdc3d696dd4a
child 902 5c65f811cf55
permissions -rw-r--r--
Giving API users better control over GC aspects of their objects
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 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-2014 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.netbeans.html.boot.spi;
    44 
    45 import java.io.Closeable;
    46 import java.io.IOException;
    47 import java.io.InputStream;
    48 import java.io.InputStreamReader;
    49 import java.io.Reader;
    50 import java.net.URL;
    51 import java.util.HashMap;
    52 import java.util.HashSet;
    53 import java.util.Map;
    54 import java.util.Set;
    55 import java.util.concurrent.Executor;
    56 import net.java.html.js.JavaScriptBody;
    57 import org.netbeans.html.boot.impl.FnContext;
    58 
    59 /** Represents single JavaScript function that can be invoked. 
    60  * Created via {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
    61  *
    62  * @author Jaroslav Tulach
    63  */
    64 public abstract class Fn {
    65     private final Presenter presenter;
    66     
    67     /**
    68      * @deprecated Ineffective as of 0.6. 
    69      * Provide a presenter via {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter)}
    70      * constructor
    71      */
    72     @Deprecated
    73     protected Fn() {
    74         this(null);
    75     }
    76     
    77     /** Creates new function object and associates it with given presenter.
    78      * 
    79      * @param presenter the browser presenter associated with this function
    80      * @since 0.6 
    81      */
    82     protected Fn(Presenter presenter) {
    83         this.presenter = presenter;
    84     }
    85 
    86     /** True, if currently active presenter is the same as presenter this
    87      * function has been created for via {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter)}.
    88      * 
    89      * @return true, if proper presenter is used
    90      */
    91     public final boolean isValid() {
    92         return presenter != null && FnContext.currentPresenter(false) == presenter;
    93     }
    94     
    95     /** Helper method to check if the provided instance is valid function.
    96      * Checks if the parameter is non-null and if so, does {@link #isValid()}
    97      * check.
    98      * 
    99      * @param fnOrNull function or <code>null</code>
   100      * @return true if the parameter is non-null and valid
   101      * @since 0.7
   102      */
   103     public static boolean isValid(Fn fnOrNull) {
   104         return fnOrNull != null && fnOrNull.isValid();
   105     }
   106 
   107     /** Helper method to find current presenter and ask it to define new
   108      * function by calling {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
   109      * 
   110      * @param caller the class who wishes to define the function
   111      * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
   112      * @param names names of individual parameters
   113      * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
   114      *    - can return <code>null</code> if there is {@link #activePresenter() no presenter}
   115      * @since 0.7
   116      */
   117     public static Fn define(Class<?> caller, String code, String... names) {
   118         return define(caller, false, code, names);
   119     }
   120 
   121     /** Helper method to find current presenter and ask it to define new
   122      * function.
   123      * 
   124      * @param caller the class who wishes to define the function
   125      * @param keepParametersAlive whether Java parameters should survive in JavaScript
   126      *   after the method invocation is over
   127      * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
   128      * @param names names of individual parameters
   129      * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
   130      *    - can return <code>null</code> if there is {@link #activePresenter() no presenter}
   131      * @since 1.1
   132      */
   133     public static Fn define(Class<?> caller, boolean keepParametersAlive, String code, String... names) {
   134         final Presenter p = FnContext.currentPresenter(false);
   135         if (p == null) {
   136             return null;
   137         }
   138         if (p instanceof KeepAlive) {
   139             boolean[] arr;
   140             if (!keepParametersAlive) {
   141                 arr = new boolean[names.length];
   142                 for (int i = 0; i < arr.length; i++) {
   143                     arr[i] = false;
   144                 }
   145             } else {
   146                 arr = null;
   147             }
   148             return ((KeepAlive)p).defineFn(code, names, arr);
   149         }
   150         return p.defineFn(code, names);
   151     }
   152     
   153     private static final Map<String,Set<Presenter>> LOADED = new HashMap<String, Set<Presenter>>();
   154     
   155     /** Wraps function to ensure that the script represented by <code>resource</code>
   156      * gets loaded into the browser environment before the function <code>fn</code>
   157      * is executed.
   158      * 
   159      * @param fn original function to call (if <code>null</code> returns <code>null</code>)
   160      * @param caller the class who wishes to define/call the function
   161      * @param resource resources (accessible via {@link ClassLoader#getResource(java.lang.String)}) 
   162      *   with a <em>JavaScript</em> that is supposed to loaded into the browser
   163      *   environment
   164      * @return function that ensures the script is loaded and then delegates
   165      *   to <code>fn</code>. Returns <code>null</code> if the input <code>fn</code> is null
   166      * @since 0.7
   167      */
   168     public static Fn preload(final Fn fn, final Class<?> caller, final String resource) {
   169         if (fn == null) {
   170             return null;
   171         }
   172         return new Fn(fn.presenter()) {
   173             @Override
   174             public Object invoke(Object thiz, Object... args) throws Exception {
   175                 loadResource();
   176                 return fn.invoke(thiz, args);
   177             }
   178 
   179             @Override
   180             public void invokeLater(Object thiz, Object... args) throws Exception {
   181                 loadResource();
   182                 fn.invokeLater(thiz, args);
   183             }
   184             
   185             private void loadResource() throws Exception {
   186                 Presenter p = presenter();
   187                 if (p == null) {
   188                     p = FnContext.currentPresenter(false);
   189                 }
   190                 if (p != null) {
   191                     Set<Presenter> there = LOADED.get(resource);
   192                     if (there == null) {
   193                         there = new HashSet<Presenter>();
   194                         LOADED.put(resource, there);
   195                     }
   196                     if (there.add(p)) {
   197                         final ClassLoader l = caller.getClassLoader();
   198                         InputStream is = l.getResourceAsStream(resource);
   199                         if (is == null && resource.startsWith("/")) {
   200                             is = l.getResourceAsStream(resource.substring(1));
   201                         }
   202                         if (is == null) {
   203                             throw new IOException("Cannot find " + resource + " in " + l);
   204                         }
   205                         try {
   206                             InputStreamReader r = new InputStreamReader(is, "UTF-8");
   207                             p.loadScript(r);
   208                         } finally {
   209                             is.close();
   210                         }
   211                     }
   212                 }
   213             }
   214         };
   215     }
   216 
   217     
   218     /** The currently active presenter.
   219      * 
   220      * @return the currently active presenter or <code>null</code>
   221      * @since 0.7
   222      */
   223     public static Presenter activePresenter() {
   224         return FnContext.currentPresenter(false);
   225     }
   226     
   227     /** Activates given presenter. Used to associate the native 
   228      * JavaScript code specified by 
   229      * {@link JavaScriptBody} annotation with certain presenter:
   230      * <pre>
   231      * try ({@link Closeable} c = Fn.activate(presenter)) {
   232      *   doCallsInPresenterContext();
   233      * }
   234      * </pre>
   235      * 
   236      * @param p the presenter that should be active until closable is closed
   237      * @return the closable to close
   238      * @since 0.7
   239      */
   240     public static Closeable activate(Presenter p) {
   241         return FnContext.activate(p);
   242     }
   243     
   244     /** Invokes the defined function with specified <code>this</code> and
   245      * appropriate arguments.
   246      * 
   247      * @param thiz the meaning of <code>this</code> inside of the JavaScript
   248      *   function - can be <code>null</code>
   249      * @param args arguments for the function
   250      * @return return value from the function
   251      * @throws Exception if something goes wrong, as exception may be thrown
   252      */
   253     public abstract Object invoke(Object thiz, Object... args) throws Exception;
   254 
   255     /** Invokes the defined function with specified <code>this</code> and
   256      * appropriate arguments asynchronously. The invocation may be 
   257      * happen <em>"later"</em>.
   258      * 
   259      * @param thiz the meaning of <code>this</code> inside of the JavaScript
   260      *   function - can be <code>null</code>
   261      * @param args arguments for the function
   262      * @throws Exception if something goes wrong, as exception may be thrown
   263      * @since 0.7.6
   264      */
   265     public void invokeLater(Object thiz, Object... args) throws Exception {
   266         invoke(this, args);
   267     }
   268     
   269     /** Provides the function implementation access to the presenter provided
   270      * in {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter) the constructor}.
   271      * 
   272      * @return presenter passed in the constructor (may be, but should not be <code>null</code>)
   273      * @since 0.7
   274      */
   275     protected final Presenter presenter() {
   276         return presenter;
   277     }
   278     
   279     /** The representation of a <em>presenter</em> - usually a browser window.
   280      * Should be provided by a library included in the application and registered
   281      * in <code>META-INF/services</code>, for example with
   282      * <code>@ServiceProvider(service = Fn.Presenter.class)</code> annotation.
   283      * <p>
   284      * Since 0.7 a presenter may implement {@link Executor} interface, in case
   285      * it supports single threaded execution environment. The executor's
   286      * {@link Executor#execute(java.lang.Runnable)} method is then supposed
   287      * to invoke the runnable immediately (in case we are on the right thread
   288      * already) or return and asynchronously invoke the runnable later on the
   289      * right thread (if we are on wrong thread).
   290      */
   291     public interface Presenter {
   292         /** Creates new function with given parameter names and provided body.
   293          * 
   294          * @param code the body of the function. Can refer to variables named
   295          *   as <code>names</code>
   296          * @param names names of parameters of the function - these will be 
   297          *   available when the <code>code</code> body executes
   298          * 
   299          * @return function that can be later invoked
   300          */
   301         public Fn defineFn(String code, String... names);
   302         
   303         /** Opens the browser, loads provided page and when the
   304          * page is ready, it calls back to the provider runnable.
   305          * 
   306          * @param page the URL for the page to display
   307          * @param onPageLoad callback when the page is ready
   308          */
   309         public void displayPage(URL page, Runnable onPageLoad);
   310         
   311         /** Loads a script into the browser JavaScript interpreter and 
   312          * executes it.
   313          * @param code the script to execute
   314          * @throws Exception if something goes wrong, throw an exception
   315          */
   316         public void loadScript(Reader code) throws Exception;
   317     }
   318     
   319     /** Additional interface to be implemented by {@link Presenter}s that
   320      * wish to control what objects are passed into the JavaScript virtual 
   321      * machine.
   322      * <p>
   323      * If a JavaScript engine makes callback to Java method that returns 
   324      * a value, the {@link #toJavaScript(java.lang.Object)} method is
   325      * consulted to convert the Java value to something reasonable inside
   326      * JavaScript VM.
   327      * <p>
   328      * <em>Note:</em> The implementation based on <em>JavaFX</em> <code>WebView</code>
   329      * uses this interface to convert Java arrays to JavaScript ones.
   330      * 
   331      * @see Presenter
   332      * @since 0.7
   333      */
   334     public interface ToJavaScript {
   335         /** Convert a Java return value into some object suitable for
   336          * JavaScript virtual machine.
   337          * 
   338          * @param toReturn the Java object to be returned
   339          * @return the replacement value to return instead
   340          */
   341         public Object toJavaScript(Object toReturn);
   342     }
   343     
   344     /** Additional interface to be implemented by {@link Presenter}s that
   345      * need to convert JavaScript object (usually array) to Java object 
   346      * when calling back from JavaScript to Java.
   347      * <p>
   348      * <em>Note:</em> The implementation based on <em>JavaFX</em>
   349      * <code>WebView</code> uses this interface to convert JavaScript arrays to
   350      * Java ones.
   351       * 
   352      * @since 0.7
   353      */
   354     public interface FromJavaScript {
   355         /** Convert a JavaScript object into suitable Java representation
   356          * before a Java method is called with this object as an argument.
   357          * 
   358          * @param js the JavaScript object
   359          * @return replacement object for 
   360          */
   361         public Object toJava(Object js);
   362     }
   363 
   364     /** Additional interface to {@link Presenter} to control more precisely
   365      * garbage collection behavior of individual parameters. See 
   366      * {@link JavaScriptBody#keepAlive()} attribute for description of the
   367      * actual behavior of the interface.
   368      * 
   369      * @since 1.1
   370      */
   371     public interface KeepAlive {
   372         /** Creates new function with given parameter names and provided body.
   373          * 
   374          * @param code the body of the function. Can refer to variables named
   375          *   as <code>names</code>
   376          * @param names names of parameters of the function - these will be 
   377          *   available when the <code>code</code> body executes
   378          * @param keepAlive array of booleans describing for each parameter
   379          *   whether it should be kept alive or not. Length of the array
   380          *   must be the same as length of <code>names</code> array. The
   381          *   array may be <code>null</code> to signal that all parameters
   382          *   should be <em>kept alive</em>.
   383          * 
   384          * @return function that can be later invoked
   385          */
   386         public Fn defineFn(String code, String[] names, boolean[] keepAlive);
   387     }
   388 }