Use optional dependency on asm-5.0.jar, so we don't have to bundle it when the classes are post processed.
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
6 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7 * Other names may be trademarks of their respective owners.
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]"
29 * The Original Software is NetBeans. The Initial Developer of the Original
30 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
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.
43 package net.java.html.boot;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.lang.reflect.Method;
49 import java.net.HttpURLConnection;
50 import java.net.JarURLConnection;
51 import java.net.MalformedURLException;
53 import java.net.URLConnection;
54 import java.security.ProtectionDomain;
55 import java.util.Arrays;
56 import java.util.Collection;
57 import java.util.Enumeration;
58 import java.util.Locale;
59 import java.util.ServiceLoader;
60 import java.util.concurrent.Executor;
61 import java.util.logging.Level;
62 import java.util.logging.Logger;
63 import net.java.html.BrwsrCtx;
64 import net.java.html.js.JavaScriptBody;
65 import org.netbeans.html.boot.spi.Fn;
66 import org.netbeans.html.boot.spi.Fn.Presenter;
67 import org.netbeans.html.context.spi.Contexts;
68 import org.netbeans.html.boot.impl.FindResources;
69 import org.netbeans.html.boot.impl.FnContext;
70 import org.netbeans.html.boot.impl.FnUtils;
72 /** Use this builder to launch your Java/HTML based application. Typical
73 * usage in a main method of your application looks like this:
76 * <b>public static void</b> <em>main</em>(String... args) {
77 * BrowserBuilder.{@link #newBrowser newBrowser()}.
78 * {@link #loadClass(java.lang.Class) loadClass(YourMain.class)}.
79 * {@link #loadPage(java.lang.String) loadPage("index.html")}.
80 * {@link #locale(java.util.Locale) locale}({@link Locale#getDefault()}).
81 * {@link #invoke(java.lang.String, java.lang.String[]) invoke("initialized", args)}.
82 * {@link #showAndWait()};
86 * The above will load <code>YourMain</code> class via
87 * a special classloader, it will locate an <code>index.html</code> (relative
88 * to <code>YourMain</code> class) and show it in a browser window. When the
89 * initialization is over, a <b>public static</b> method <em>initialized</em>
90 * in <code>YourMain</code> will be called with provided string parameters.
92 * This module provides only API for building browsers. To use it properly one
93 * also needs an implementation on the classpath of one's application. For example
96 * <groupId>org.netbeans.html</groupId>
97 * <artifactId>net.java.html.boot.fx</artifactId>
98 * <scope>runtime</scope>
102 * @author Jaroslav Tulach
104 public final class BrowserBuilder {
105 private static final Logger LOG = Logger.getLogger(BrowserBuilder.class.getName());
107 private String resource;
108 private Class<?> clazz;
109 private Class[] browserClass;
110 private Runnable onLoad;
111 private String methodName;
112 private String[] methodArgs;
113 private final Object[] context;
114 private ClassLoader loader;
115 private Locale locale;
117 private BrowserBuilder(Object[] context) {
118 this.context = context;
121 /** Entry method to obtain a new browser builder. Follow by calling
122 * its instance methods like {@link #loadClass(java.lang.Class)} and
123 * {@link #loadPage(java.lang.String)}.
125 * @param context any instances that should be available to the builder -
126 * implementation dependant
127 * @return new browser builder
129 public static BrowserBuilder newBrowser(Object... context) {
130 return new BrowserBuilder(context);
133 /** The class to load when the browser is initialized. This class
134 * is loaded by a special classloader (that supports {@link JavaScriptBody}
137 * @param mainClass the class to load and resolve when the browser is ready
138 * @return this builder
140 public BrowserBuilder loadClass(Class<?> mainClass) {
141 this.clazz = mainClass;
145 /** Allows one to specify a runnable that should be invoked when a load
146 * of a page is finished. This method may be used in addition or instead
147 * of {@link #loadClass(java.lang.Class)} and
148 * {@link #invoke(java.lang.String, java.lang.String...)} methods.
150 * @param r the code to run when the page is loaded
151 * @return this builder
154 public BrowserBuilder loadFinished(Runnable r) {
159 /** Page to load into the browser. If the <code>page</code> represents
160 * a {@link URL} known to the Java system, the URL is passed to the browser.
161 * If system property <code>browser.rootdir</code> is specified, then a
162 * file <code>page</code> relative to this directory is used as the URL.
163 * If no such file exists, the system seeks for the
164 * resource via {@link Class#getResource(java.lang.String)}
165 * method (relative to the {@link #loadClass(java.lang.Class) specified class}).
166 * If such resource is not found, a file relative to the location JAR
167 * that contains the {@link #loadClass(java.lang.Class) main class} is
170 * The search honors provided {@link #locale}, if specified.
171 * E.g. it will prefer <code>index_cs.html</code> over <code>index.html</code>
172 * if the locale is set to <code>cs_CZ</code>.
174 * @param page the location (relative, absolute, or URL) of a page to load
175 * @return this builder
177 public BrowserBuilder loadPage(String page) {
178 this.resource = page;
182 /** Locale to use when searching for an initial {@link #loadPage(java.lang.String) page to load}.
183 * Localization is best done by providing different versions of the
184 * initial page with appropriate suffixes (like <code>index_cs.html</code>).
185 * Then one can call this method with value of {@link Locale#getDefault()}
186 * to instruct the builder to use the user's current locale.
188 * @param locale the locale to use or <code>null</code> if no suffix search should be performed
189 * @return this builder
192 public BrowserBuilder locale(Locale locale) {
193 this.locale = locale;
197 /** Specifies callback method to notify the application that the browser is ready.
198 * There should be a <b>public static</b> method in the class specified
199 * by {@link #loadClass(java.lang.Class)} which takes an array of {@link String}
200 * argument. The method is called on the browser dispatch thread one
201 * the browser finishes loading of the {@link #loadPage(java.lang.String) HTML page}.
203 * @param methodName name of a method to seek for
204 * @param args parameters to pass to the method
205 * @return this builder
207 public BrowserBuilder invoke(String methodName, String... args) {
208 this.methodName = methodName;
209 this.methodArgs = args;
213 /** Loader to use when searching for classes to initialize.
214 * If specified, this loader is going to be used to load {@link Presenter}
215 * and {@link Contexts#fillInByProviders(java.lang.Class, org.netbeans.html.context.spi.Contexts.Builder) fill} {@link BrwsrCtx} in.
216 * Specifying special classloader may be useful in modular systems,
217 * like OSGi, where one needs to load classes from many otherwise independent
220 * @param l the loader to use (or <code>null</code>)
221 * @return this builder
224 public BrowserBuilder classloader(ClassLoader l) {
229 /** Shows the browser, loads specified page in and executes the
230 * {@link #invoke(java.lang.String, java.lang.String[]) initialization method}.
231 * The method returns when the browser is closed.
233 * @throws NullPointerException if some of essential parameters (like {@link #loadPage(java.lang.String) page} or
234 * {@link #loadClass(java.lang.Class) class} have not been specified
236 public void showAndWait() {
237 if (resource == null) {
238 throw new NullPointerException("Need to specify resource via loadPage method");
241 final Class<?> myCls;
244 } else if (onLoad != null) {
245 myCls = onLoad.getClass();
247 throw new NullPointerException("loadClass, neither loadFinished was called!");
249 IOException mal[] = { null };
250 URL url = findLocalizedResourceURL(resource, locale, mal, myCls);
252 Fn.Presenter dfnr = null;
253 for (Object o : context) {
254 if (o instanceof Fn.Presenter) {
255 dfnr = (Fn.Presenter)o;
260 if (dfnr == null && loader != null) for (Fn.Presenter o : ServiceLoader.load(Fn.Presenter.class, loader)) {
265 if (dfnr == null) for (Fn.Presenter o : ServiceLoader.load(Fn.Presenter.class)) {
271 throw new IllegalStateException("Can't find any Fn.Presenter");
274 final ClassLoader activeLoader;
275 if (loader != null) {
276 if (!FnContext.isJavaScriptCapable(loader)) {
277 throw new IllegalStateException("Loader cannot resolve @JavaScriptBody: " + loader);
279 activeLoader = loader;
280 } else if (FnContext.isJavaScriptCapable(myCls.getClassLoader())) {
281 activeLoader = myCls.getClassLoader();
283 if (!FnContext.isAsmPresent()) {
284 throw new IllegalStateException("Cannot find asm-5.0.jar classes!");
286 FImpl impl = new FImpl(myCls.getClassLoader());
287 activeLoader = FnUtils.newLoader(impl, dfnr, myCls.getClassLoader().getParent());
290 final Fn.Presenter dP = dfnr;
292 class OnPageLoad implements Runnable {
296 final Fn.Presenter aP = Fn.activePresenter();
297 final Fn.Presenter currentP = aP != null ? aP : dP;
299 Thread.currentThread().setContextClassLoader(activeLoader);
300 final Class<?> newClazz = Class.forName(myCls.getName(), true, activeLoader);
301 if (browserClass != null) {
302 browserClass[0] = newClazz;
304 Contexts.Builder cb = Contexts.newBuilder();
305 if (!Contexts.fillInByProviders(newClazz, cb)) {
306 LOG.log(Level.WARNING, "Using empty technology for {0}", newClazz);
308 if (currentP instanceof Executor) {
309 cb.register(Executor.class, (Executor)currentP, 1000);
311 cb.register(Fn.Presenter.class, currentP, 1000);
312 BrwsrCtx c = cb.build();
314 class CallInitMethod implements Runnable {
317 Throwable firstError = null;
318 if (onLoad != null) {
320 FnContext.currentPresenter(currentP);
322 } catch (Throwable ex) {
325 FnContext.currentPresenter(null);
328 INIT: if (methodName != null) {
329 if (methodArgs.length == 0) {
331 Method m = newClazz.getMethod(methodName);
332 FnContext.currentPresenter(currentP);
336 } catch (Throwable ex) {
339 FnContext.currentPresenter(null);
343 Method m = newClazz.getMethod(methodName, String[].class);
344 FnContext.currentPresenter(currentP);
345 m.invoke(m, (Object) methodArgs);
347 } catch (Throwable ex) {
348 LOG.log(Level.SEVERE, "Can't call " + methodName + " with args " + Arrays.toString(methodArgs), ex);
350 FnContext.currentPresenter(null);
353 if (firstError != null) {
354 LOG.log(Level.SEVERE, "Can't initialize the view", firstError);
359 c.execute(new CallInitMethod());
360 } catch (ClassNotFoundException ex) {
361 LOG.log(Level.SEVERE, "Can't load " + myCls.getName(), ex);
365 dfnr.displayPage(url, new OnPageLoad());
368 private static URL findResourceURL(String resource, String suffix, IOException[] mal, Class<?> relativeTo) {
369 if (suffix != null) {
370 int lastDot = resource.lastIndexOf('.');
372 resource = resource.substring(0, lastDot) + suffix + resource.substring(lastDot);
374 resource = resource + suffix;
380 String baseURL = System.getProperty("browser.rootdir"); // NOI18N
381 if (baseURL != null) {
382 URL u = new File(baseURL, resource).toURI().toURL();
389 URL u = new URL(resource);
390 if (suffix == null || isReal(u)) {
395 } catch (MalformedURLException ex) {
400 url = relativeTo.getResource(resource);
403 final ProtectionDomain pd = relativeTo.getProtectionDomain();
404 if (pd != null && pd.getCodeSource() != null) {
405 URL jar = pd.getCodeSource().getLocation();
407 URL u = new URL(jar, resource);
411 } catch (MalformedURLException ex) {
412 ex.initCause(mal[0]);
418 URL res = BrowserBuilder.class.getResource("html4j.txt");
419 LOG.log(Level.FINE, "Found html4j {0}", res);
422 URLConnection c = res.openConnection();
423 LOG.log(Level.FINE, "testing : {0}", c);
424 if (c instanceof JarURLConnection) {
425 JarURLConnection jc = (JarURLConnection) c;
426 URL base = jc.getJarFileURL();
427 for (int i = 0; i < 50; i++) {
428 URL u = new URL(base, resource);
433 base = new URL(base, "..");
436 } catch (IOException ex) {
444 static URL findLocalizedResourceURL(String resource, Locale l, IOException[] mal, Class<?> relativeTo) {
447 url = findResourceURL(resource, "_" + l.getLanguage() + "_" + l.getCountry(), mal, relativeTo);
451 url = findResourceURL(resource, "_" + l.getLanguage(), mal, relativeTo);
456 return findResourceURL(resource, null, mal, relativeTo);
459 private static boolean isReal(URL u) {
461 URLConnection conn = u.openConnection();
462 if (conn instanceof HttpURLConnection) {
463 HttpURLConnection hc = (HttpURLConnection) conn;
464 hc.setReadTimeout(5000);
465 if (hc.getResponseCode() >= 300) {
466 throw new IOException("Wrong code: " + hc.getResponseCode());
469 InputStream is = conn.getInputStream();
471 LOG.log(Level.FINE, "found real url: {0}", u);
473 } catch (IOException ignore) {
474 LOG.log(Level.FINE, "Cannot open " + u, ignore);
479 private static final class FImpl implements FindResources {
482 public FImpl(ClassLoader l) {
487 public void findResources(String path, Collection<? super URL> results, boolean oneIsEnough) {
489 URL u = l.getResource(path);
495 Enumeration<URL> en = l.getResources(path);
496 while (en.hasMoreElements()) {
497 results.add(en.nextElement());
499 } catch (IOException ex) {