alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.openide.execution;

import java.io.*;
import java.net.*;
import java.util.*;

import org.openide.ErrorManager;
import org.openide.util.NbBundle;

/** Stream handler for internal resource-based URLs.
 * @author Jesse Glick
 */
class NbResourceStreamHandler extends URLStreamHandler {

    public static final String PROTOCOL_BOOT_RESOURCE = "nbresboot"; // NOI18N
    public static final String PROTOCOL_CURRENT_RESOURCE = "nbrescurr"; // NOI18N
    public static final String PROTOCOL_LOCALIZED_BOOT_RESOURCE = "nbresbootloc"; // NOI18N
    public static final String PROTOCOL_LOCALIZED_CURRENT_RESOURCE = "nbrescurrloc"; // NOI18N

    public URLConnection openConnection (URL u) throws IOException {
        if (u.getProtocol ().equals (PROTOCOL_BOOT_RESOURCE)) {
            return new Connection (u, 0, false);
        } else if (u.getProtocol ().equals (PROTOCOL_CURRENT_RESOURCE)) {
            return new Connection (u, 2, false);
        } else if (u.getProtocol ().equals (PROTOCOL_LOCALIZED_BOOT_RESOURCE)) {
            return new Connection (u, 0, true);
        } else if (u.getProtocol ().equals (PROTOCOL_LOCALIZED_CURRENT_RESOURCE)) {
            return new Connection (u, 2, true);
        } else {
            throw new IOException (NbBundle.getMessage (NbResourceStreamHandler.class, "EXC_UnrecognizedProtocol"));
        }
    }

    private static class Connection extends URLConnection {

	private final boolean localized;
        private final int current; // 0 = boot, 1 = system, 2 = current

	// A real connection to delegate to. Non-null if successfully connected.
	private URLConnection real;
        
        private IOException exception = null;
        
        private static final Set warnedURLs = new HashSet(); // Set

	public Connection (URL u, int current, boolean localized) {
	    super (u);
	    this.current = current;
	    this.localized = localized;
            if (current == 0 && warnedURLs.add(u.toExternalForm())) {
                ErrorManager.getDefault().log(ErrorManager.WARNING, "Warning: in " + u.toExternalForm() + ", the " + u.getProtocol() + " URL protocol has been deprecated in favor of nbres/nbresloc which is less implementation-dependent.");
            } else if (current == 2 && warnedURLs.add(u.toExternalForm())) {
                ErrorManager.getDefault().log(ErrorManager.WARNING, "Warning: in " + u.toExternalForm() + ", the " + u.getProtocol() + " URL protocol has been deprecated as it assumes Filesystems == classpath.");
            }
	}

	/** Tries to get a URL from this resource from the proper classloader,
	 * localizing first if requested.
	 * Also opens the URL to make a connection; this connection, real,
	 * will be delegated to for all operations.
	 */
	public synchronized void connect () throws IOException {
            if (exception != null) {
                // See tryToConnect().
                IOException e = exception;
                exception = null;
                throw e;
            }
	    if (! connected) {
		String resource = url.getFile ();
		if (resource.startsWith ("/")) resource = resource.substring (1); //NOI18N
		ClassLoader loader;
                switch (current) {
                case 2:
                    throw new IOException("No longer works!"); // NOI18N
                    /*
                    loader = new NbClassLoader();
                    break;
                     */
                case 0:
                    loader = NbResourceStreamHandler.class.getClassLoader ();
                    break;
                default:
                    throw new InternalError ();
                }
		URL target;
		if (localized) {
                    String ext, basename;
		    int index = resource.lastIndexOf ('.');
		    if (index != -1) {
                        ext = resource.substring (index + 1);
                        basename = resource.substring (0, index).replace ('/', '.');
                    } else {
                        ext = null;
                        basename = resource.replace ('/', '.');
                    }
                    try {
                        target = NbBundle.getLocalizedFile (basename, ext, Locale.getDefault (), loader);
                    } catch (MissingResourceException mre) {
                        throw (IOException) ErrorManager.getDefault ().annotate
			    (new IOException (NbBundle.getMessage (NbResourceStreamHandler.class, "EXC_nbres_cannot_connect", url)), mre);
                    }
		} else {
		    target = loader.getResource (resource);
                    if (target == null) throw new IOException
                        (NbBundle.getMessage (NbResourceStreamHandler.class, "EXC_nbres_cannot_connect", url));
		}
		real = target.openConnection ();
                real.connect ();
		connected = true;
	    }
	}
        
        /** Try to connect; but if it does not work, oh well.
         * Ideally this would be quite unnecessary.
         * Unfortunately much code, inclduing the Swing editor kits,
         * gets header fields and so on without ever calling connect().
         * These methods cannot even throw exceptions so it is a mess.
         * E.g. if you display a nbres: URL in the ICE browser, it is fine:
         * it calls connect() according to the specification, then
         * getContentType() produces text/html as expected.
         * But using the SwingBrowser default implementation, it goes
         * ahead and calls getContentType() immediately. So we have
         * to try to connect and get the right content type then too.
         * This complicated the timing of error reporting.
         */
        private void tryToConnect () {
            if (connected || exception != null) return;
            try {
                connect ();
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

	public String getHeaderField (int n) {
            tryToConnect ();
	    if (connected)
		return real.getHeaderField (n);
	    else
		return null;
	}

	public String getHeaderFieldKey (int n) {
            tryToConnect ();
	    if (connected)
		return real.getHeaderFieldKey (n);
	    else
		return null;
	}

	public String getHeaderField (String key) {
            tryToConnect ();
	    if (connected)
		return real.getHeaderField (key);
	    else
		return null;
	}

	public InputStream getInputStream () throws IOException {
            connect ();
            return real.getInputStream ();
	}

	public OutputStream getOutputStream () throws IOException {
            connect ();
            return real.getOutputStream ();
	}
        
        // Should not be required, but they are:
        
        public String getContentType () {
            tryToConnect ();
            if (connected)
                return real.getContentType ();
            else
                return "application/octet-stream"; // NOI18N
        }
        
        public int getContentLength () {
            tryToConnect ();
            if (connected)
                return real.getContentLength ();
            else
                return 0;
        }

	// [PENDING] might be some more methods it would be useful to delegate, possibly

    }

}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.