Example usage for java.net URL setURLStreamHandlerFactory

List of usage examples for java.net URL setURLStreamHandlerFactory

Introduction

In this page you can find the example usage for java.net URL setURLStreamHandlerFactory.

Prototype

public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) 

Source Link

Document

Sets an application's URLStreamHandlerFactory .

Usage

From source file:com.t3.client.TabletopTool.java

public static void main(String[] args) {
    if (MAC_OS_X) {
        // On OSX the menu bar at the top of the screen can be enabled at any time, but the
        // title (ie. name of the application) has to be set before the GUI is initialized (by
        // creating a frame, loading a splash screen, etc).  So we do it here.
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        System.setProperty("com.apple.mrj.application.apple.menu.about.name", "About TabletopTool...");
        System.setProperty("apple.awt.brushMetalLook", "true");
    }//from  w  w  w  .  j av a 2  s  . c  om
    // Before anything else, create a place to store all the data
    try {
        AppUtil.getAppHome();
    } catch (Throwable t) {
        t.printStackTrace();

        // Create an empty frame so there's something to click on if the dialog goes in the background
        JFrame frame = new JFrame();
        SwingUtil.centerOnScreen(frame);
        frame.setVisible(true);

        String errorCreatingDir = "Error creating data directory";
        log.error(errorCreatingDir, t);
        JOptionPane.showMessageDialog(frame, t.getMessage(), errorCreatingDir, JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }
    verifyJavaVersion();

    configureLogging();

    // System properties
    System.setProperty("swing.aatext", "true");
    // System.setProperty("sun.java2d.opengl", "true");

    final SplashScreen splash = new SplashScreen(SPLASH_IMAGE, getVersion());
    splash.showSplashScreen();

    // Protocol handlers
    // cp:// is registered by the RPTURLStreamHandlerFactory constructor (why?)
    RPTURLStreamHandlerFactory factory = new RPTURLStreamHandlerFactory();
    factory.registerProtocol("asset", new AssetURLStreamHandler());
    URL.setURLStreamHandlerFactory(factory);

    MacroEngine.initialize();
    configureJide(); //TODO find out how to not call this twice without destroying error windows

    final Toolkit tk = Toolkit.getDefaultToolkit();
    tk.getSystemEventQueue().push(new T3EventQueue());

    // LAF
    try {

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        configureJide();
        if (WINDOWS)
            LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE);
        else
            LookAndFeelFactory.installJideExtension();
        if (MAC_OS_X) {
            macOSXicon();
        }
        menuBar = new AppMenuBar();
    } catch (Exception e) {
        TabletopTool.showError("msg.error.lafSetup", e);
        System.exit(1);
    }

    /**
     * This is a tweak that makes the Chinese version work better.
     * <p>
     * Consider reviewing <a
     * href="http://en.wikipedia.org/wiki/CJK_characters"
     * >http://en.wikipedia.org/wiki/CJK_characters</a> before making
     * changes. And http://www.scarfboy.com/coding/unicode-tool is also a
     * really cool site.
     */
    if (Locale.CHINA.equals(Locale.getDefault())) {
        // The following font name appears to be "Sim Sun".  It can be downloaded
        // from here:  http://fr.cooltext.com/Fonts-Unicode-Chinese
        Font f = new Font("\u65B0\u5B8B\u4F53", Font.PLAIN, 12);
        FontUIResource fontRes = new FontUIResource(f);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource)
                UIManager.put(key, fontRes);
        }
    }

    // Draw frame contents on resize
    tk.setDynamicLayout(true);

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            initialize();
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    clientFrame.setVisible(true);
                    splash.hideSplashScreen();
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            postInitialize();
                        }
                    });
                }
            });
        }
    });
    // new Thread(new HeapSpy()).start();
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Start this component, initializing our associated class loader.
 *
 * @exception LifecycleException if a lifecycle error occurs
 *///from   w w w.java2 s  .co  m
public void start() throws LifecycleException {
    // Validate and update our current component state
    if (!initialized)
        init();
    if (started)
        throw new LifecycleException(sm.getString("webappLoader.alreadyStarted"));
    if (log.isDebugEnabled())
        log.debug(sm.getString("webappLoader.starting"));
    lifecycle.fireLifecycleEvent(START_EVENT, null);
    started = true;

    if (container.getResources() == null) {
        log.info("No resources for " + container);
        return;
    }
    // Register a stream handler factory for the JNDI protocol
    URLStreamHandlerFactory streamHandlerFactory = new DirContextURLStreamHandlerFactory();
    if (first) {
        first = false;
        try {
            URL.setURLStreamHandlerFactory(streamHandlerFactory);
        } catch (Exception e) {
            // Log and continue anyway, this is not critical
            log.error("Error registering jndi stream handler", e);
        } catch (Throwable t) {
            // This is likely a dual registration
            log.info("Dual registration of jndi stream handler: " + t.getMessage());
        }
    }

    // Construct a class loader based on our current repositories list
    try {

        classLoader = createClassLoader();
        classLoader.setResources(container.getResources());
        classLoader.setDebug(this.debug);
        classLoader.setDelegate(this.delegate);

        for (int i = 0; i < repositories.length; i++) {
            classLoader.addRepository(repositories[i]);
        }

        // Configure our repositories
        setRepositories();
        setClassPath();

        setPermissions();

        if (classLoader instanceof Lifecycle)
            ((Lifecycle) classLoader).start();

        // Binding the Webapp class loader to the directory context
        DirContextURLStreamHandler.bind((ClassLoader) classLoader, this.container.getResources());

    } catch (Throwable t) {
        log.error("LifecycleException ", t);
        throw new LifecycleException("start: ", t);
    }

}

From source file:org.danann.cernunnos.runtime.Main.java

public static void main(String[] args) {

    Log log = LogFactory.getLog(ScriptRunner.class);

    // Put some whitespace between the command and the output...
    System.out.println("");

    // Register custom protocol handlers...
    try {//from w ww  .jav  a2 s .  co m
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactoryImpl());
    } catch (Throwable t) {
        log.warn("Cernunnos was unable to register a URLStreamHandlerFactory.  "
                + "Custom URL protocols may not work properly (e.g. classpath://, c:/).  "
                + "See stack trace below.", t);
    }

    // Establish CRN_HOME...
    String crnHome = System.getenv("CRN_HOME");
    if (crnHome == null) {
        if (log.isDebugEnabled()) {
            log.debug("The CRN_HOME environment variable is not defined;  "
                    + "this is completely normal for embedded applications " + "of Cernunnos.");
        }
    }

    // Look at the specified script:  might it be in the bin/ directory?
    String location = args[0];
    try {
        // This is how ScriptRunner will attempt to locate the script file...
        URL u = new URL(new File(".").toURI().toURL(), location);
        if (u.getProtocol().equals("file")) {
            // We know the specified resource is a local file;  is it either 
            // (1) absolute or (2) relative to the directory where Java is 
            // executing?
            if (!new File(u.toURI()).exists() && crnHome != null) {
                // No.  And what's more, 'CRN_HOME' is defined.  In this case 
                // let's see if the specified script *is* present in the bin/ 
                // directory.
                StringBuilder path = new StringBuilder();
                path.append(crnHome).append(File.separator).append("bin").append(File.separator)
                        .append(location);
                File f = new File(path.toString());
                if (f.exists()) {
                    // The user is specifying a Cernunnos script in the bin/ directory...
                    location = f.toURI().toURL().toExternalForm();
                    if (log.isInfoEnabled()) {
                        log.info("Resolving the specified Cernunnos document "
                                + "to a file in the CRN_HOME/bin directory:  " + location);
                    }
                }
            }
        }
    } catch (Throwable t) {
        // Just let this pass -- genuine issues will be caught & reported shortly...
    }

    // Analyze the command-line arguments...
    RuntimeRequestResponse req = new RuntimeRequestResponse();
    switch (args.length) {
    case 0:
        // No file provided, can't continue...
        System.out.println("Usage:\n\n\t>crn [script_name] [arguments]");
        System.exit(0);
        break;
    default:
        for (int i = 1; i < args.length; i++) {
            req.setAttribute("$" + i, args[i]);
        }
        break;
    }

    ScriptRunner runner = new ScriptRunner();
    runner.run(location, req);

}

From source file:org.fdroid.fdroid.FDroidApp.java

@TargetApi(9)
@Override/* w  w w .java 2s .  c  o m*/
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);
    curTheme = Preferences.get().getTheme();

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // make sure the current proxy stuff is configured
    Preferences.get().configureProxy();

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get().registerAppsRequiringRootChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            getContentResolver().notifyChange(AppProvider.getContentUri(), null);
        }
    });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
        }
    });

    final Context context = this;
    Preferences.get().registerUnstableUpdatesChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            AppProvider.Helper.calcDetailsFromIndex(context);
        }
    });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    if (!Preferences.get().shouldCacheApks()) {
        Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(new LimitedAgeDiskCache(
                    new File(StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"), null,
                    new FileNameGenerator() {
                        @Override
                        public String generate(String imageUri) {
                            return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                        }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4).threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get().registerLocalRepoHttpsListeners(new ChangeListener() {
        @Override
        public void onPreferenceChange() {
            startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
        }
    });

    configureTor(Preferences.get().isTorEnabled());
}

From source file:org.hadoop.tdg.TestPseudoHadoop.java

@Test
@Ignore("StackOverflowError with *-site.xml")
public void readWithURLHandler() throws IOException {
    URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
    printStream(new URL(fs.getUri() + DST_FILE).openStream());
}

From source file:org.mule.util.MuleUrlStreamHandlerFactory.java

/**
 * Install an instance of this class as UrlStreamHandlerFactory. This may be done exactly
 * once as {@link URL} will throw an {@link Error} on subsequent invocations. 
 * <p>/*ww  w  . j a  v a2  s.c o  m*/
 * This method takes care that multiple invocations are possible, but the 
 * UrlStreamHandlerFactory is installed only once.
 */
public static synchronized void installUrlStreamHandlerFactory() {
    /*
     * When running under surefire, this class will be loaded by different class loaders and
     * will be running in multiple "main" thread objects. Thus, there is no way for this class
     * to register a globally available variable to store the info whether our custom 
     * UrlStreamHandlerFactory was already registered.
     * 
     * The only way to accomplish this is to catch the Error that is thrown by URL when
     * trying to re-register the custom UrlStreamHandlerFactory.
     */
    try {
        URL.setURLStreamHandlerFactory(new MuleUrlStreamHandlerFactory());
    } catch (Error err) {
        if (log.isDebugEnabled()) {
            log.debug("Custom MuleUrlStreamHandlerFactory already registered", err);
        }
    }
}

From source file:org.onosproject.cluster.impl.ClusterMetadataManagerTest.java

/**
 * Tests fetching metadata from an HTTP source.
 *//*w w w. java 2  s. c  o  m*/
@Test
public void testUrlFetch() {
    URL.setURLStreamHandlerFactory(
            new HttpResourceUrlInterceptor.HttpResourceUrlInterceptorFactory("cluster-info.json"));
    System.setProperty("onos.cluster.metadata.uri", "http://opennetworking.org");

    fileProvider.activate();
    pause(400);

    ClusterMetadata metadata = fileProvider.getClusterMetadata().value();
    assertThat(metadata, notNullValue());

    assertThat(metadata.getName(), is(CLUSTER_NAME));
    assertThat(metadata.getNodes(), hasSize(1));
    assertThat(metadata.getPartitions(), hasSize(1));
}

From source file:org.opentestsystem.shared.common.logging.TestMonitoringAlertingAppender.java

@BeforeClass
public static void initStuff() {
    URL.setURLStreamHandlerFactory(urlStreamHandlerFactory);
}

From source file:org.ops4j.pax.runner.handler.internal.URLUtils.java

/**
 * Sets the URL stream handler factory even if the URLSStreamHandler factory is already set in the URL.
 * URL permits setting of the factory only once pe JVM. If the factory is already set it will set the field via
 * reflection and will keep the already set handler for delegation.
 *
 * @see java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)
 *///w  w  w  .j ava2 s  .  co  m
public static void setURLStreamHandlerFactory(final URLStreamHandlerFactory urlStreamHandlerFactory) {
    try {
        URL.setURLStreamHandlerFactory(urlStreamHandlerFactory);
    } catch (Error err) {
        // usually we get here because the URLStreamHandlerFactory was already set and is only permited onec pe JVM
        // so, we will try to "still" the static field inside URL via reflection and install our handler factory
        // that will delegate to the original factory
        LOGGER.debug("URLStreamHandlerFactory already set in the system. Replacing it with a composite");
        synchronized (URL.class) {
            final URLStreamHandlerFactory currentFactory = resetURLStreamHandlerFactory();
            // ususally it should not be null as otherwise we shouldn't be here but then we try again
            if (currentFactory == null) {
                URL.setURLStreamHandlerFactory(urlStreamHandlerFactory);
            } else if (currentFactory instanceof CompositeURLStreamHandlerFactory) {
                URL.setURLStreamHandlerFactory(currentFactory);
                ((CompositeURLStreamHandlerFactory) currentFactory).registerFactory(urlStreamHandlerFactory);
            } else {
                URL.setURLStreamHandlerFactory(new CompositeURLStreamHandlerFactory()
                        .registerFactory(urlStreamHandlerFactory).registerFactory(currentFactory));
            }
        }
    }
}

From source file:org.springframework.data.hadoop.configuration.ConfigurationFactoryBean.java

public void afterPropertiesSet() throws Exception {
    internalConfig = createConfiguration(configuration);

    internalConfig.setClassLoader(beanClassLoader);
    if (resources != null) {
        for (Resource resource : resources) {
            internalConfig.addResource(resource.getURL());
        }//from   w w  w  .jav  a  2s .com
    }

    ConfigurationUtils.addProperties(internalConfig, properties);

    // set hdfs / fs URI last to override all other properties
    if (StringUtils.hasText(fsUri)) {
        internalConfig.set("fs.default.name", fsUri.trim());
    }

    if (StringUtils.hasText(jtUri)) {
        internalConfig.set("mapred.job.tracker", jtUri.trim());
    }

    if (initialize) {
        internalConfig.size();
    }

    postProcessConfiguration(internalConfig);

    if (registerJvmUrl) {
        try {
            // force UGI init to prevent infinite loop - see SHDP-92
            UserGroupInformation.setConfiguration(internalConfig);
            URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(getObject()));
            log.info("Registered HDFS URL stream handler");
        } catch (Error err) {
            log.warn("Cannot register Hadoop URL stream handler - one is already registered");
        }
    }
}