boot/src/main/java/net/java/html/boot/BrowserBuilder.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 04 Dec 2014 09:21:55 +0100
changeset 886 88d62267a0b5
parent 884 af690d50d7d6
child 897 2e416426cab0
permissions -rw-r--r--
#248918: Introducing technology identifiers
jaroslav@123
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@123
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jaroslav@123
     5
 *
jaroslav@358
     6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
jaroslav@358
     7
 * Other names may be trademarks of their respective owners.
jaroslav@123
     8
 *
jaroslav@358
     9
 * The contents of this file are subject to the terms of either the GNU
jaroslav@358
    10
 * General Public License Version 2 only ("GPL") or the Common
jaroslav@358
    11
 * Development and Distribution License("CDDL") (collectively, the
jaroslav@358
    12
 * "License"). You may not use this file except in compliance with the
jaroslav@358
    13
 * License. You can obtain a copy of the License at
jaroslav@358
    14
 * http://www.netbeans.org/cddl-gplv2.html
jaroslav@358
    15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jaroslav@358
    16
 * specific language governing permissions and limitations under the
jaroslav@358
    17
 * License.  When distributing the software, include this License Header
jaroslav@358
    18
 * Notice in each file and include the License file at
jaroslav@358
    19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
jaroslav@358
    20
 * particular file as subject to the "Classpath" exception as provided
jaroslav@358
    21
 * by Oracle in the GPL Version 2 section of the License file that
jaroslav@358
    22
 * accompanied this code. If applicable, add the following below the
jaroslav@358
    23
 * License Header, with the fields enclosed by brackets [] replaced by
jaroslav@358
    24
 * your own identifying information:
jaroslav@358
    25
 * "Portions Copyrighted [year] [name of copyright owner]"
jaroslav@358
    26
 *
jaroslav@358
    27
 * Contributor(s):
jaroslav@358
    28
 *
jaroslav@358
    29
 * The Original Software is NetBeans. The Initial Developer of the Original
jaroslav@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
jaroslav@358
    31
 *
jaroslav@358
    32
 * If you wish your version of this file to be governed by only the CDDL
jaroslav@358
    33
 * or only the GPL Version 2, indicate your decision by adding
jaroslav@358
    34
 * "[Contributor] elects to include this software in this distribution
jaroslav@358
    35
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
jaroslav@358
    36
 * single choice of license, a recipient has the option to distribute
jaroslav@358
    37
 * your version of this file under either the CDDL, the GPL Version 2 or
jaroslav@358
    38
 * to extend the choice of license to its licensees as provided above.
jaroslav@358
    39
 * However, if you add GPL Version 2 code and therefore, elected the GPL
jaroslav@358
    40
 * Version 2 license, then the option applies only if the new code is
jaroslav@358
    41
 * made subject to such option by the copyright holder.
jaroslav@123
    42
 */
jaroslav@123
    43
package net.java.html.boot;
jaroslav@123
    44
jaroslav@202
    45
import java.io.File;
jaroslav@127
    46
import java.io.IOException;
jtulach@653
    47
import java.io.InputStream;
jaroslav@156
    48
import java.lang.reflect.Method;
jtulach@834
    49
import java.net.HttpURLConnection;
jtulach@653
    50
import java.net.JarURLConnection;
jaroslav@148
    51
import java.net.MalformedURLException;
jaroslav@127
    52
import java.net.URL;
jtulach@653
    53
import java.net.URLConnection;
jtulach@653
    54
import java.security.ProtectionDomain;
jaroslav@156
    55
import java.util.Arrays;
jaroslav@127
    56
import java.util.Collection;
jaroslav@127
    57
import java.util.Enumeration;
jtulach@834
    58
import java.util.Locale;
jaroslav@127
    59
import java.util.ServiceLoader;
jaroslav@574
    60
import java.util.concurrent.Executor;
jaroslav@156
    61
import java.util.logging.Level;
jaroslav@156
    62
import java.util.logging.Logger;
jtulach@569
    63
import net.java.html.BrwsrCtx;
jaroslav@166
    64
import net.java.html.js.JavaScriptBody;
jtulach@838
    65
import org.netbeans.html.boot.spi.Fn;
jtulach@882
    66
import org.netbeans.html.boot.spi.Fn.Presenter;
jtulach@838
    67
import org.netbeans.html.context.spi.Contexts;
jtulach@886
    68
import org.netbeans.html.context.spi.Contexts.Id;
jaroslav@362
    69
import org.netbeans.html.boot.impl.FindResources;
jaroslav@362
    70
import org.netbeans.html.boot.impl.FnContext;
jaroslav@509
    71
import org.netbeans.html.boot.impl.FnUtils;
jaroslav@127
    72
jaroslav@166
    73
/** Use this builder to launch your Java/HTML based application. Typical
jaroslav@166
    74
 * usage in a main method of your application looks like this: 
jaroslav@166
    75
 * <pre>
jaroslav@166
    76
 * 
jaroslav@166
    77
 * <b>public static void</b> <em>main</em>(String... args) {
jtulach@700
    78
 *     BrowserBuilder.{@link #newBrowser newBrowser()}.
jaroslav@166
    79
 *          {@link #loadClass(java.lang.Class) loadClass(YourMain.class)}.
jaroslav@166
    80
 *          {@link #loadPage(java.lang.String) loadPage("index.html")}.
jtulach@836
    81
 *          {@link #locale(java.util.Locale) locale}({@link Locale#getDefault()}).
jaroslav@166
    82
 *          {@link #invoke(java.lang.String, java.lang.String[]) invoke("initialized", args)}.
jaroslav@166
    83
 *          {@link #showAndWait()};
jaroslav@166
    84
 *     System.exit(0);
jaroslav@166
    85
 * }
jaroslav@166
    86
 * </pre>
jaroslav@166
    87
 * The above will load <code>YourMain</code> class via
jaroslav@166
    88
 * a special classloader, it will locate an <code>index.html</code> (relative
jaroslav@166
    89
 * to <code>YourMain</code> class) and show it in a browser window. When the
jaroslav@166
    90
 * initialization is over, a <b>public static</b> method <em>initialized</em>
jaroslav@166
    91
 * in <code>YourMain</code> will be called with provided string parameters.
jaroslav@166
    92
 * <p>
jaroslav@166
    93
 * This module provides only API for building browsers. To use it properly one
jaroslav@166
    94
 * also needs an implementation on the classpath of one's application. For example
jaroslav@166
    95
 * use: <pre>
jaroslav@166
    96
 * &lt;dependency&gt;
jaroslav@361
    97
 *   &lt;groupId&gt;org.netbeans.html&lt;/groupId&gt;
jaroslav@361
    98
 *   &lt;artifactId&gt;net.java.html.boot.fx&lt;/artifactId&gt;
jaroslav@166
    99
 *   &lt;scope&gt;runtime&lt;/scope&gt;
jaroslav@166
   100
 * &lt;/dependency&gt;
jaroslav@166
   101
 * </pre>
jaroslav@123
   102
 *
jtulach@790
   103
 * @author Jaroslav Tulach
jaroslav@123
   104
 */
jaroslav@123
   105
public final class BrowserBuilder {
jaroslav@156
   106
    private static final Logger LOG = Logger.getLogger(BrowserBuilder.class.getName());
jaroslav@156
   107
    
jaroslav@127
   108
    private String resource;
jaroslav@127
   109
    private Class<?> clazz;
jaroslav@146
   110
    private Class[] browserClass;
jaroslav@146
   111
    private Runnable onLoad;
jaroslav@156
   112
    private String methodName;
jaroslav@156
   113
    private String[] methodArgs;
jaroslav@288
   114
    private final Object[] context;
jtulach@771
   115
    private ClassLoader loader;
jtulach@834
   116
    private Locale locale;
jaroslav@156
   117
    
jaroslav@288
   118
    private BrowserBuilder(Object[] context) {
jaroslav@288
   119
        this.context = context;
jaroslav@123
   120
    }
jaroslav@166
   121
jaroslav@166
   122
    /** Entry method to obtain a new browser builder. Follow by calling 
jaroslav@166
   123
     * its instance methods like {@link #loadClass(java.lang.Class)} and
jaroslav@166
   124
     * {@link #loadPage(java.lang.String)}.
jtulach@886
   125
     * Since introduction of {@link Id technology identifiers} the 
jtulach@886
   126
     * provided <code>context</code> objects are also passed to the 
jtulach@886
   127
     * {@link BrwsrCtx context} when it is being 
jtulach@886
   128
     * {@link Contexts#newBuilder(java.lang.Object...) created}
jtulach@886
   129
     * and can influence the selection
jtulach@886
   130
     * of available technologies 
jtulach@886
   131
     * (like {@link org.netbeans.html.json.spi.Technology},
jtulach@886
   132
     * {@link org.netbeans.html.json.spi.Transfer} or
jtulach@886
   133
     * {@link org.netbeans.html.json.spi.WSTransfer}) by name.
jaroslav@166
   134
     * 
jaroslav@288
   135
     * @param context any instances that should be available to the builder -
jaroslav@458
   136
     *   implementation dependant
jaroslav@166
   137
     * @return new browser builder
jaroslav@166
   138
     */
jaroslav@288
   139
    public static BrowserBuilder newBrowser(Object... context) {
jaroslav@288
   140
        return new BrowserBuilder(context);
jaroslav@123
   141
    }
jaroslav@123
   142
    
jaroslav@166
   143
    /** The class to load when the browser is initialized. This class
jaroslav@166
   144
     * is loaded by a special classloader (that supports {@link JavaScriptBody}
jaroslav@166
   145
     * and co.). 
jaroslav@166
   146
     * 
jaroslav@166
   147
     * @param mainClass the class to load and resolve when the browser is ready
jaroslav@166
   148
     * @return this builder
jaroslav@166
   149
     */
jaroslav@127
   150
    public BrowserBuilder loadClass(Class<?> mainClass) {
jaroslav@127
   151
        this.clazz = mainClass;
jaroslav@123
   152
        return this;
jaroslav@123
   153
    }
jtulach@656
   154
    
jtulach@656
   155
    /** Allows one to specify a runnable that should be invoked when a load
jtulach@656
   156
     * of a page is finished. This method may be used in addition or instead
jtulach@656
   157
     * of {@link #loadClass(java.lang.Class)} and 
jtulach@656
   158
     * {@link #invoke(java.lang.String, java.lang.String...)} methods.
jtulach@656
   159
     * 
jtulach@656
   160
     * @param r the code to run when the page is loaded
jtulach@656
   161
     * @return this builder
jtulach@656
   162
     * @since 0.8.1
jtulach@656
   163
     */
jtulach@656
   164
    public BrowserBuilder loadFinished(Runnable r) {
jtulach@656
   165
        this.onLoad = r;
jtulach@656
   166
        return this;
jtulach@656
   167
    }
jaroslav@156
   168
jaroslav@166
   169
    /** Page to load into the browser. If the <code>page</code> represents
jaroslav@166
   170
     * a {@link URL} known to the Java system, the URL is passed to the browser. 
jaroslav@202
   171
     * If system property <code>browser.rootdir</code> is specified, then a
jaroslav@202
   172
     * file <code>page</code> relative to this directory is used as the URL.
jaroslav@202
   173
     * If no such file exists, the system seeks for the 
jaroslav@202
   174
     * resource via {@link Class#getResource(java.lang.String)}
jaroslav@202
   175
     * method (relative to the {@link #loadClass(java.lang.Class) specified class}). 
jaroslav@202
   176
     * If such resource is not found, a file relative to the location JAR
jaroslav@202
   177
     * that contains the {@link #loadClass(java.lang.Class) main class} is 
jaroslav@202
   178
     * searched for.
jtulach@834
   179
     * <p>
jtulach@834
   180
     * The search honors provided {@link #locale}, if specified.
jtulach@834
   181
     * E.g. it will prefer <code>index_cs.html</code> over <code>index.html</code>
jtulach@834
   182
     * if the locale is set to <code>cs_CZ</code>.
jaroslav@166
   183
     * 
jaroslav@166
   184
     * @param page the location (relative, absolute, or URL) of a page to load
jtulach@834
   185
     * @return this builder
jaroslav@166
   186
     */
jaroslav@166
   187
    public BrowserBuilder loadPage(String page) {
jaroslav@166
   188
        this.resource = page;
jaroslav@166
   189
        return this;
jaroslav@166
   190
    }
jaroslav@166
   191
    
jtulach@834
   192
    /** Locale to use when searching for an initial {@link #loadPage(java.lang.String) page to load}.
jtulach@834
   193
     * Localization is best done by providing different versions of the 
jtulach@834
   194
     * initial page with appropriate suffixes (like <code>index_cs.html</code>).
jtulach@834
   195
     * Then one can call this method with value of {@link Locale#getDefault()}
jtulach@834
   196
     * to instruct the builder to use the user's current locale.
jtulach@834
   197
     * 
jtulach@834
   198
     * @param locale the locale to use or <code>null</code> if no suffix search should be performed
jtulach@834
   199
     * @return this builder
jtulach@834
   200
     * @since 1.0
jtulach@834
   201
     */
jtulach@834
   202
    public BrowserBuilder locale(Locale locale) {
jtulach@834
   203
        this.locale = locale;
jtulach@834
   204
        return this;
jtulach@834
   205
    }
jtulach@834
   206
    
jaroslav@166
   207
    /** Specifies callback method to notify the application that the browser is ready.
jaroslav@166
   208
     * There should be a <b>public static</b> method in the class specified
jaroslav@166
   209
     * by {@link #loadClass(java.lang.Class)} which takes an array of {@link String}
jaroslav@166
   210
     * argument. The method is called on the browser dispatch thread one
jaroslav@166
   211
     * the browser finishes loading of the {@link #loadPage(java.lang.String) HTML page}.
jaroslav@166
   212
     * 
jaroslav@166
   213
     * @param methodName name of a method to seek for
jaroslav@166
   214
     * @param args parameters to pass to the method
jaroslav@166
   215
     * @return this builder
jaroslav@166
   216
     */
jaroslav@156
   217
    public BrowserBuilder invoke(String methodName, String... args) {
jaroslav@156
   218
        this.methodName = methodName;
jaroslav@156
   219
        this.methodArgs = args;
jaroslav@156
   220
        return this;
jaroslav@156
   221
    }
jaroslav@166
   222
jtulach@771
   223
    /** Loader to use when searching for classes to initialize. 
jtulach@882
   224
     * If specified, this loader is going to be used to load {@link Presenter}
jtulach@838
   225
     * and {@link Contexts#fillInByProviders(java.lang.Class, org.netbeans.html.context.spi.Contexts.Builder) fill} {@link BrwsrCtx} in.
jtulach@771
   226
     * Specifying special classloader may be useful in modular systems, 
jtulach@771
   227
     * like OSGi, where one needs to load classes from many otherwise independent
jtulach@771
   228
     * modules.
jtulach@771
   229
     * 
jtulach@771
   230
     * @param l the loader to use (or <code>null</code>)
jtulach@771
   231
     * @return this builder
jtulach@771
   232
     * @since 0.9
jtulach@771
   233
     */
jtulach@771
   234
    public BrowserBuilder classloader(ClassLoader l) {
jtulach@771
   235
        this.loader = l;
jtulach@771
   236
        return this;
jtulach@771
   237
    }
jtulach@771
   238
jaroslav@166
   239
    /** Shows the browser, loads specified page in and executes the 
jaroslav@166
   240
     * {@link #invoke(java.lang.String, java.lang.String[]) initialization method}.
jaroslav@166
   241
     * The method returns when the browser is closed.
jaroslav@166
   242
     * 
jaroslav@166
   243
     * @throws NullPointerException if some of essential parameters (like {@link #loadPage(java.lang.String) page} or
jaroslav@166
   244
     *    {@link #loadClass(java.lang.Class) class} have not been specified
jaroslav@166
   245
     */
jaroslav@123
   246
    public void showAndWait() {
jaroslav@146
   247
        if (resource == null) {
jaroslav@166
   248
            throw new NullPointerException("Need to specify resource via loadPage method");
jaroslav@146
   249
        }
jaroslav@146
   250
        
jtulach@656
   251
        final Class<?> myCls;
jtulach@656
   252
        if (clazz != null) {
jtulach@656
   253
            myCls = clazz;
jtulach@656
   254
        } else if (onLoad != null) {
jtulach@656
   255
            myCls = onLoad.getClass();
jtulach@656
   256
        } else {
jtulach@656
   257
            throw new NullPointerException("loadClass, neither loadFinished was called!");
jtulach@656
   258
        }
jtulach@834
   259
        IOException mal[] = { null };
jtulach@834
   260
        URL url = findLocalizedResourceURL(resource, locale, mal, myCls);
jaroslav@288
   261
        
jaroslav@288
   262
        Fn.Presenter dfnr = null;
jaroslav@288
   263
        for (Object o : context) {
jaroslav@288
   264
            if (o instanceof Fn.Presenter) {
jaroslav@288
   265
                dfnr = (Fn.Presenter)o;
jaroslav@288
   266
                break;
jaroslav@288
   267
            }
jaroslav@288
   268
        }
jaroslav@127
   269
jtulach@771
   270
        if (dfnr == null && loader != null) for (Fn.Presenter o : ServiceLoader.load(Fn.Presenter.class, loader)) {
jtulach@771
   271
            dfnr = o;
jtulach@771
   272
            break;
jtulach@771
   273
        }
jtulach@771
   274
        
jaroslav@288
   275
        if (dfnr == null) for (Fn.Presenter o : ServiceLoader.load(Fn.Presenter.class)) {
jaroslav@288
   276
            dfnr = o;
jaroslav@288
   277
            break;
jaroslav@288
   278
        }
jaroslav@288
   279
        
jaroslav@288
   280
        if (dfnr == null) {
jaroslav@288
   281
            throw new IllegalStateException("Can't find any Fn.Presenter");
jaroslav@288
   282
        }
jaroslav@288
   283
        
jtulach@771
   284
        final ClassLoader activeLoader;
jtulach@771
   285
        if (loader != null) {
jtulach@884
   286
            if (!FnContext.isJavaScriptCapable(loader)) {
jtulach@771
   287
                throw new IllegalStateException("Loader cannot resolve @JavaScriptBody: " + loader);
jtulach@771
   288
            }
jtulach@771
   289
            activeLoader = loader;
jtulach@884
   290
        } else if (FnContext.isJavaScriptCapable(myCls.getClassLoader())) {
jtulach@771
   291
            activeLoader = myCls.getClassLoader();
jaroslav@509
   292
        } else {
jtulach@884
   293
            if (!FnContext.isAsmPresent()) {
jtulach@884
   294
                throw new IllegalStateException("Cannot find asm-5.0.jar classes!");
jtulach@884
   295
            }
jtulach@656
   296
            FImpl impl = new FImpl(myCls.getClassLoader());
jtulach@771
   297
            activeLoader = FnUtils.newLoader(impl, dfnr, myCls.getClassLoader().getParent());
jaroslav@509
   298
        }
jtulach@736
   299
        
jtulach@736
   300
        final Fn.Presenter dP = dfnr;
jaroslav@128
   301
jaroslav@288
   302
        class OnPageLoad implements Runnable {
jaroslav@288
   303
            @Override
jaroslav@288
   304
            public void run() {
jaroslav@288
   305
                try {
jtulach@736
   306
                    final Fn.Presenter aP = Fn.activePresenter();
jtulach@736
   307
                    final Fn.Presenter currentP = aP != null ? aP : dP;
jtulach@736
   308
                    
jtulach@771
   309
                    Thread.currentThread().setContextClassLoader(activeLoader);
jtulach@771
   310
                    final Class<?> newClazz = Class.forName(myCls.getName(), true, activeLoader);
jtulach@736
   311
                    if (browserClass != null) {
jtulach@736
   312
                        browserClass[0] = newClazz;
jtulach@736
   313
                    }
jtulach@886
   314
                    Contexts.Builder cb = Contexts.newBuilder(context);
jtulach@736
   315
                    if (!Contexts.fillInByProviders(newClazz, cb)) {
jtulach@736
   316
                        LOG.log(Level.WARNING, "Using empty technology for {0}", newClazz);
jtulach@736
   317
                    }
jtulach@736
   318
                    if (currentP instanceof Executor) {
jtulach@736
   319
                        cb.register(Executor.class, (Executor)currentP, 1000);
jtulach@736
   320
                    }
jtulach@736
   321
                    cb.register(Fn.Presenter.class, currentP, 1000);
jtulach@736
   322
                    BrwsrCtx c = cb.build();
jtulach@736
   323
jtulach@736
   324
                    class CallInitMethod implements Runnable {
jtulach@736
   325
                        @Override
jtulach@736
   326
                        public void run() {
jtulach@736
   327
                            Throwable firstError = null;
jtulach@736
   328
                            if (onLoad != null) {
jtulach@736
   329
                                try {
jtulach@736
   330
                                    FnContext.currentPresenter(currentP);
jtulach@736
   331
                                    onLoad.run();
jtulach@736
   332
                                } catch (Throwable ex) {
jtulach@736
   333
                                    firstError = ex;
jtulach@736
   334
                                } finally {
jtulach@736
   335
                                    FnContext.currentPresenter(null);
jtulach@736
   336
                                }
jtulach@736
   337
                            }
jtulach@736
   338
                            INIT: if (methodName != null) {
jtulach@736
   339
                                if (methodArgs.length == 0) {
jtulach@736
   340
                                    try {
jtulach@736
   341
                                        Method m = newClazz.getMethod(methodName);
jtulach@736
   342
                                        FnContext.currentPresenter(currentP);
jtulach@736
   343
                                        m.invoke(null);
jtulach@736
   344
                                        firstError = null;
jtulach@736
   345
                                        break INIT;
jtulach@736
   346
                                    } catch (Throwable ex) {
jtulach@736
   347
                                        firstError = ex;
jtulach@736
   348
                                    } finally {
jtulach@736
   349
                                        FnContext.currentPresenter(null);
jtulach@736
   350
                                    }
jtulach@736
   351
                                }
jtulach@736
   352
                                try {
jtulach@736
   353
                                    Method m = newClazz.getMethod(methodName, String[].class);
jtulach@736
   354
                                    FnContext.currentPresenter(currentP);
jtulach@736
   355
                                    m.invoke(m, (Object) methodArgs);
jtulach@736
   356
                                    firstError = null;
jtulach@736
   357
                                } catch (Throwable ex) {
jtulach@736
   358
                                    LOG.log(Level.SEVERE, "Can't call " + methodName + " with args " + Arrays.toString(methodArgs), ex);
jtulach@736
   359
                                } finally {
jtulach@736
   360
                                    FnContext.currentPresenter(null);
jtulach@736
   361
                                }
jtulach@736
   362
                            }
jtulach@736
   363
                            if (firstError != null) {
jtulach@736
   364
                                LOG.log(Level.SEVERE, "Can't initialize the view", firstError);
jtulach@736
   365
                            }
jtulach@569
   366
                        }
jaroslav@288
   367
                    }
jtulach@569
   368
                    
jtulach@736
   369
                    c.execute(new CallInitMethod());
jaroslav@288
   370
                } catch (ClassNotFoundException ex) {
jtulach@656
   371
                    LOG.log(Level.SEVERE, "Can't load " + myCls.getName(), ex);
jaroslav@128
   372
                }
jaroslav@127
   373
            }
jaroslav@127
   374
        }
jaroslav@288
   375
        dfnr.displayPage(url, new OnPageLoad());
jaroslav@127
   376
    }
jaroslav@146
   377
jtulach@834
   378
    private static URL findResourceURL(String resource, String suffix, IOException[] mal, Class<?> relativeTo) {
jtulach@834
   379
        if (suffix != null) {
jtulach@834
   380
            int lastDot = resource.lastIndexOf('.');
jtulach@834
   381
            if (lastDot != -1) {
jtulach@834
   382
                resource = resource.substring(0, lastDot) + suffix + resource.substring(lastDot);
jtulach@834
   383
            } else {
jtulach@834
   384
                resource = resource + suffix;
jtulach@834
   385
            }
jtulach@834
   386
        }
jtulach@834
   387
        
jtulach@834
   388
        URL url = null;
jtulach@834
   389
        try {
jtulach@834
   390
            String baseURL = System.getProperty("browser.rootdir"); // NOI18N
jtulach@834
   391
            if (baseURL != null) {
jtulach@834
   392
                URL u = new File(baseURL, resource).toURI().toURL();
jtulach@834
   393
                if (isReal(u)) {
jtulach@834
   394
                    url = u;
jtulach@834
   395
                }
jtulach@834
   396
            } 
jtulach@834
   397
            
jtulach@834
   398
            {
jtulach@834
   399
                URL u = new URL(resource);
jtulach@834
   400
                if (suffix == null || isReal(u)) {
jtulach@834
   401
                    url = u;
jtulach@834
   402
                }
jtulach@834
   403
                return url;
jtulach@834
   404
            }
jtulach@834
   405
        } catch (MalformedURLException ex) {
jtulach@834
   406
            mal[0] = ex;
jtulach@834
   407
        }
jtulach@834
   408
        
jtulach@834
   409
        if (url == null) {
jtulach@834
   410
            url = relativeTo.getResource(resource);
jtulach@834
   411
        }
jtulach@834
   412
        if (url == null) {
jtulach@834
   413
            final ProtectionDomain pd = relativeTo.getProtectionDomain();
jtulach@834
   414
            if (pd != null && pd.getCodeSource() != null) {
jtulach@834
   415
                URL jar = pd.getCodeSource().getLocation();
jtulach@834
   416
                try {
jtulach@834
   417
                    URL u = new URL(jar, resource);
jtulach@834
   418
                    if (isReal(u)) {
jtulach@834
   419
                        url = u;
jtulach@834
   420
                    }
jtulach@834
   421
                } catch (MalformedURLException ex) {
jtulach@834
   422
                    ex.initCause(mal[0]);
jtulach@834
   423
                    mal[0] = ex;
jtulach@834
   424
                }
jtulach@834
   425
            }
jtulach@834
   426
        }
jtulach@834
   427
        if (url == null) {
jtulach@834
   428
            URL res = BrowserBuilder.class.getResource("html4j.txt");
jtulach@834
   429
            LOG.log(Level.FINE, "Found html4j {0}", res);
jtulach@834
   430
            if (res != null) {
jtulach@834
   431
                try {
jtulach@834
   432
                    URLConnection c = res.openConnection();
jtulach@834
   433
                    LOG.log(Level.FINE, "testing : {0}", c);
jtulach@834
   434
                    if (c instanceof JarURLConnection) {
jtulach@834
   435
                        JarURLConnection jc = (JarURLConnection) c;
jtulach@834
   436
                        URL base = jc.getJarFileURL();
jtulach@834
   437
                        for (int i = 0; i < 50; i++) {
jtulach@834
   438
                            URL u = new URL(base, resource);
jtulach@834
   439
                            if (isReal(u)) {
jtulach@834
   440
                                url = u;
jtulach@834
   441
                                break;
jtulach@834
   442
                            }
jtulach@834
   443
                            base = new URL(base, "..");
jtulach@834
   444
                        }
jtulach@834
   445
                    }
jtulach@834
   446
                } catch (IOException ex) {
jtulach@834
   447
                    mal[0] = ex;
jtulach@834
   448
                }
jtulach@834
   449
            }
jtulach@834
   450
        }
jtulach@834
   451
        return url;
jtulach@834
   452
    }
jtulach@834
   453
jtulach@834
   454
    static URL findLocalizedResourceURL(String resource, Locale l, IOException[] mal, Class<?> relativeTo) {
jtulach@834
   455
        URL url = null;
jtulach@834
   456
        if (l != null) {
jtulach@834
   457
            url = findResourceURL(resource, "_" + l.getLanguage() + "_" + l.getCountry(), mal, relativeTo);
jtulach@834
   458
            if (url != null) {
jtulach@834
   459
                return url;
jtulach@834
   460
            }
jtulach@834
   461
            url = findResourceURL(resource, "_" + l.getLanguage(), mal, relativeTo);
jtulach@834
   462
        }
jtulach@834
   463
        if (url != null) {
jtulach@834
   464
            return url;
jtulach@834
   465
        }
jtulach@834
   466
        return findResourceURL(resource, null, mal, relativeTo);
jtulach@834
   467
    }
jtulach@834
   468
    
jtulach@834
   469
    private static boolean isReal(URL u) {
jtulach@834
   470
        try {
jtulach@834
   471
            URLConnection conn = u.openConnection();
jtulach@834
   472
            if (conn instanceof HttpURLConnection) {
jtulach@834
   473
                HttpURLConnection hc = (HttpURLConnection) conn;
jtulach@834
   474
                hc.setReadTimeout(5000);
jtulach@834
   475
                if (hc.getResponseCode() >= 300) {
jtulach@834
   476
                    throw new IOException("Wrong code: " + hc.getResponseCode());
jtulach@834
   477
                }
jtulach@834
   478
            }
jtulach@834
   479
            InputStream is = conn.getInputStream();
jtulach@834
   480
            is.close();
jtulach@834
   481
            LOG.log(Level.FINE, "found real url: {0}", u);
jtulach@834
   482
            return true;
jtulach@834
   483
        } catch (IOException ignore) {
jtulach@834
   484
            LOG.log(Level.FINE, "Cannot open " + u, ignore);
jtulach@834
   485
            return false;
jtulach@834
   486
        }
jtulach@834
   487
    }
jtulach@834
   488
jaroslav@128
   489
    private static final class FImpl implements FindResources {
jaroslav@128
   490
        final ClassLoader l;
jaroslav@127
   491
jaroslav@127
   492
        public FImpl(ClassLoader l) {
jaroslav@127
   493
            this.l = l;
jaroslav@127
   494
        }
jaroslav@127
   495
jaroslav@127
   496
        @Override
jaroslav@127
   497
        public void findResources(String path, Collection<? super URL> results, boolean oneIsEnough) {
jaroslav@127
   498
            if (oneIsEnough) {
jaroslav@127
   499
                URL u = l.getResource(path);
jaroslav@127
   500
                if (u != null) {
jaroslav@127
   501
                    results.add(u);
jaroslav@127
   502
                }
jaroslav@127
   503
            } else {
jaroslav@127
   504
                try {
jaroslav@127
   505
                    Enumeration<URL> en = l.getResources(path);
jaroslav@127
   506
                    while (en.hasMoreElements()) {
jaroslav@127
   507
                        results.add(en.nextElement());
jaroslav@127
   508
                    }
jaroslav@127
   509
                } catch (IOException ex) {
jaroslav@127
   510
                    // no results
jaroslav@127
   511
                }
jaroslav@127
   512
            }
jaroslav@127
   513
        }
jaroslav@127
   514
        
jaroslav@123
   515
    }
jaroslav@123
   516
}