boot/src/main/java/org/apidesign/html/boot/spi/Fn.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 16 Dec 2013 16:59:43 +0100
branchnetbeans
changeset 362 92fb71afdc0e
parent 358 80702021b851
child 365 5c93ad8c7a15
permissions -rw-r--r--
Moving implementation classes into org.netbeans.html namespace
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 1997-2010 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 net.java.html.js.JavaScriptBody;
    55 import org.netbeans.html.boot.impl.FnContext;
    56 
    57 /** Represents single JavaScript function that can be invoked. 
    58  * Created via {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
    59  *
    60  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    61  */
    62 public abstract class Fn {
    63     private final Presenter presenter;
    64     
    65     /**
    66      * @deprecated Ineffective as of 0.6. 
    67      * Provide a presenter via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}
    68      * constructor
    69      */
    70     @Deprecated
    71     protected Fn() {
    72         this(null);
    73     }
    74     
    75     /** Creates new function object and associates it with given presenter.
    76      * 
    77      * @param presenter the browser presenter associated with this function
    78      * @since 0.6 
    79      */
    80     protected Fn(Presenter presenter) {
    81         this.presenter = presenter;
    82     }
    83 
    84     /** True, if currently active presenter is the same as presenter this
    85      * function has been created for via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}.
    86      * 
    87      * @return true, if proper presenter is used
    88      */
    89     public final boolean isValid() {
    90         return FnContext.currentPresenter() == presenter;
    91     }
    92     
    93     /** Helper method to check if the provided instance is valid function.
    94      * Checks if the parameter is non-null and if so, does {@link #isValid()}
    95      * check.
    96      * 
    97      * @param fnOrNull function or <code>null</code>
    98      * @return true if the parameter is non-null and valid
    99      * @since 0.7
   100      */
   101     public static boolean isValid(Fn fnOrNull) {
   102         return fnOrNull != null && fnOrNull.isValid();
   103     }
   104 
   105     /** Helper method to find current presenter and ask it to define new
   106      * function by calling {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
   107      * 
   108      * @param caller the class who wishes to define the function
   109      * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
   110      * @param names names of individual parameters
   111      * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
   112      * @since 0.7
   113      */
   114     public static Fn define(Class<?> caller, String code, String... names) {
   115         return FnContext.currentPresenter().defineFn(code, names);
   116     }
   117     
   118     private static final Map<String,Set<Presenter>> LOADED = new HashMap<String, Set<Presenter>>();
   119     public static Fn preload(final Fn fn, final Class<?> caller, final String resource) {
   120         return new Fn() {
   121             @Override
   122             public Object invoke(Object thiz, Object... args) throws Exception {
   123                 final Presenter p = FnContext.currentPresenter();
   124                 Set<Presenter> there = LOADED.get(resource);
   125                 if (there == null) {
   126                     there = new HashSet<Presenter>();
   127                     LOADED.put(resource, there);
   128                 }
   129                 if (there.add(p)) {
   130                     InputStream is = caller.getClassLoader().getResourceAsStream(resource);
   131                     try {
   132                         InputStreamReader r = new InputStreamReader(is, "UTF-8");
   133                         p.loadScript(r);
   134                     } finally {
   135                         is.close();
   136                     }
   137                 }
   138                 return fn.invoke(thiz, args);
   139             }
   140         };
   141     }
   142     
   143     /** The currently active presenter.
   144      * 
   145      * @return the currently active presenter or <code>null</code>
   146      * @since 0.7
   147      */
   148     public static Presenter activePresenter() {
   149         return FnContext.currentPresenter();
   150     }
   151     
   152     /** Activates given presenter. Used by the code generated by 
   153      * {@link JavaScriptBody} annotation: 
   154      * <pre>
   155      * try ({@link Closeable} c = Fn.activate(presenter)) {
   156      *   doCallsInPresenterContext();
   157      * }
   158      * </pre>
   159      * 
   160      * @param p the presenter that should be active until closable is closed
   161      * @return the closable to close
   162      * @since 0.7
   163      */
   164     public static Closeable activate(Presenter p) {
   165         return FnContext.activate(p);
   166     }
   167     
   168     /** Invokes the defined function with specified <code>this</code> and
   169      * appropriate arguments.
   170      * 
   171      * @param thiz the meaning of <code>this</code> inside of the JavaScript
   172      *   function - can be <code>null</code>
   173      * @param args arguments for the function
   174      * @return return value from the function
   175      * @throws Exception if something goes wrong, as exception may be thrown
   176      */
   177     public abstract Object invoke(Object thiz, Object... args) throws Exception;
   178 
   179     /** The representation of a <em>presenter</em> - usually a browser window.
   180      * Should be provided by a library included in the application and registered
   181      * in <code>META-INF/services</code>, for example with
   182      * <code>@ServiceProvider(service = Fn.Presenter.class)</code> annotation.
   183      */
   184     public interface Presenter {
   185         /** Creates new function with given parameter names and provided body.
   186          * 
   187          * @param code the body of the function. Can refer to variables named
   188          *   as <code>names</code>
   189          * @param names names of parameters of the function - these will be 
   190          *   available when the <code>code</code> body executes
   191          * 
   192          * @return function that can be later invoked
   193          */
   194         public Fn defineFn(String code, String... names);
   195         
   196         /** Opens the browser, loads provided page and when the
   197          * page is ready, it calls back to the provider runnable.
   198          * 
   199          * @param page the URL for the page to display
   200          * @param onPageLoad callback when the page is ready
   201          */
   202         public void displayPage(URL page, Runnable onPageLoad);
   203         
   204         /** Loads a script into the browser JavaScript interpreter and 
   205          * executes it.
   206          * @param code the script to execute
   207          * @throws Exception if something goes wrong, throw an exception
   208          */
   209         public void loadScript(Reader code) throws Exception;
   210     }
   211 }