1160 lines · 42.9 KB · Java
RawDownload
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.jndi.cosnaming; import javax.naming.*;import javax.naming.spi.NamingManager;import javax.naming.spi.ResolveResult; import java.util.Hashtable;import java.util.Vector;import java.net.MalformedURLException;import java.net.URL;import java.io.InputStream;import java.io.InputStreamReader;import java.io.BufferedReader;import java.io.IOException; import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*; import com.sun.jndi.toolkit.corba.CorbaUtils; // Needed for creating default ORBimport java.applet.Applet; /**  * Provides a bridge to the CosNaming server provided by  * JavaIDL. This class provides the InitialContext from CosNaming.  *  * @author Raj Krishnamurthy  * @author Rosanna Lee  */ public class CNCtx implements javax.naming.Context {     private final static boolean debug = false;     ORB _orb;                   // used by ExceptionMapper and RMI/IIOP factory    public NamingContext _nc;   // public for accessing underlying NamingContext    private NameComponent[] _name = null;     Hashtable _env; // used by ExceptionMapper    static final CNNameParser parser = new CNNameParser();     private static final String FED_PROP = "com.sun.jndi.cosnaming.federation";    boolean federation = false;     // Reference counter for tracking _orb references    OrbReuseTracker orbTracker = null;    int enumCount;    boolean isCloseCalled = false;     /**      * Create a CNCtx object. Gets the initial naming      * reference for the COS Naming Service from the ORB.      * The ORB can be passed in via the java.naming.corba.orb property      * or be created using properties in the environment properties.      * @param env Environment properties for initializing name service.      * @exception NamingException Cannot initialize ORB or naming context.      */    CNCtx(Hashtable env) throws NamingException {        if (env != null) {            env = (Hashtable) env.clone();        }        _env = env;        federation = "true".equals(env != null ? env.get(FED_PROP) : null);        initOrbAndRootContext(env);    }     private CNCtx() {    }     /**     * This method is used by the iiop and iiopname URL Context factories.     */    public static ResolveResult createUsingURL(String url, Hashtable env)    throws NamingException {        CNCtx ctx = new CNCtx();        if (env != null) {            env = (Hashtable) env.clone();        }        ctx._env = env;        String rest = ctx.initUsingUrl(            env != null ?                (org.omg.CORBA.ORB) env.get("java.naming.corba.orb")                : null,            url, env);         // rest is the INS name        // Return the parsed form to prevent subsequent lookup        // from parsing the string as a composite name        // The caller should be aware that a toString() of the name        // will yield its INS syntax, rather than a composite syntax        return new ResolveResult(ctx, parser.parse(rest));    }     /**      * Creates a CNCtx object which supports the javax.naming      * apis given a COS Naming Context object.      * @param orb The ORB used by this context      * @param tracker The ORB reuse tracker for tracking references to the      *  orb object      * @param nctx The COS NamingContext object associated with this context      * @param name The name of this context relative to the root      */     CNCtx(ORB orb, OrbReuseTracker tracker, NamingContext nctx, Hashtable env,                        NameComponent[]name)        throws NamingException {            if (orb == null || nctx == null)                throw new ConfigurationException(                    "Must supply ORB or NamingContext");            _orb = orb;            orbTracker = tracker;            if (orbTracker != null) {                orbTracker.incRefCount();            }            _nc = nctx;            _env = env;            _name = name;            federation = "true".equals(env != null ? env.get(FED_PROP) : null);    }     NameComponent[] makeFullName(NameComponent[] child) {        if (_name == null || _name.length == 0) {            return child;        }        NameComponent[] answer = new NameComponent[_name.length+child.length];         // parent        System.arraycopy(_name, 0, answer, 0, _name.length);         // child        System.arraycopy(child, 0, answer, _name.length, child.length);        return answer;    }      public String getNameInNamespace() throws NamingException {        if (_name == null || _name.length == 0) {            return "";        }        return CNNameParser.cosNameToInsString(_name);    }     /**     * These are the URL schemes that need to be processed.     * IOR and corbaloc URLs can be passed directly to ORB.string_to_object()     */    private static boolean isCorbaUrl(String url) {        return url.startsWith("iiop://")            || url.startsWith("iiopname://")            || url.startsWith("corbaname:")            ;    }     /**      * Initializes the COS Naming Service.      * This method initializes the three instance fields:      * _nc : The root naming context.      * _orb: The ORB to use for connecting RMI/IIOP stubs and for      *       getting the naming context (_nc) if one was not specified      *       explicitly via PROVIDER_URL.      * _name: The name of the root naming context.      *<p>      * _orb is obtained from java.naming.corba.orb if it has been set.      * Otherwise, _orb is created using the host/port from PROVIDER_URL      * (if it contains an "iiop" or "iiopname" URL), or from initialization      * properties specified in env.      *<p>      * _nc is obtained from the IOR stored in PROVIDER_URL if it has been      * set and does not contain an "iiop" or "iiopname" URL. It can be      * a stringified IOR, "corbaloc" URL, "corbaname" URL,      * or a URL (such as file/http/ftp) to a location      * containing a stringified IOR. If PROVIDER_URL has not been      * set in this way, it is obtained from the result of      *     ORB.resolve_initial_reference("NameService");      *<p>      * _name is obtained from the "iiop", "iiopname", or "corbaname" URL.      * It is the empty name by default.      *      * @param env Environment The possibly null environment.      * @exception NamingException When an error occurs while initializing the      * ORB or the naming context.      */    private void initOrbAndRootContext(Hashtable env) throws NamingException {        org.omg.CORBA.ORB inOrb = null;        String ncIor = null;         if (env != null) {            inOrb = (org.omg.CORBA.ORB) env.get("java.naming.corba.orb");        }         // Extract PROVIDER_URL from environment        String provUrl = null;        if (env != null) {            provUrl = (String)env.get(javax.naming.Context.PROVIDER_URL);        }         if (provUrl != null && !isCorbaUrl(provUrl)) {            // Initialize the root naming context by using the IOR supplied            // in the PROVIDER_URL            ncIor = getStringifiedIor(provUrl);             if (inOrb == null) {                 // no ORB instance specified; create one using env and defaults                inOrb = CorbaUtils.getOrb(null, -1, env);                orbTracker = new OrbReuseTracker(inOrb);            }            setOrbAndRootContext(inOrb, ncIor);        } else if (provUrl != null) {            // Initialize the root naming context by using the URL supplied            // in the PROVIDER_URL            String insName = initUsingUrl(inOrb, provUrl, env);             // If name supplied in URL, resolve it to a NamingContext            if (insName.length() > 0) {                _name = parser.nameToCosName(parser.parse(insName));                try {                    org.omg.CORBA.Object obj = _nc.resolve(_name);                    _nc = NamingContextHelper.narrow(obj);                    if (_nc == null) {                        throw new ConfigurationException(insName +                            " does not name a NamingContext");                    }                } catch (org.omg.CORBA.BAD_PARAM e) {                    throw new ConfigurationException(insName +                        " does not name a NamingContext");                } catch (Exception e) {                    throw ExceptionMapper.mapException(e, this, _name);                }            }        } else {            // No PROVIDER_URL supplied; initialize using defaults            if (inOrb == null) {                 // No ORB instance specified; create one using env and defaults                inOrb = CorbaUtils.getOrb(null, -1, env);                orbTracker = new OrbReuseTracker(inOrb);                if (debug) {                    System.err.println("Getting default ORB: " + inOrb + env);                }            }            setOrbAndRootContext(inOrb, (String)null);        }    }      private String initUsingUrl(ORB orb, String url, Hashtable env)        throws NamingException {        if (url.startsWith("iiop://") || url.startsWith("iiopname://")) {            return initUsingIiopUrl(orb, url, env);        } else {            return initUsingCorbanameUrl(orb, url, env);        }    }     /**     * Handles "iiop" and "iiopname" URLs (INS 98-10-11)     */    private String initUsingIiopUrl(ORB defOrb, String url, Hashtable env)        throws NamingException {        try {            IiopUrl parsedUrl = new IiopUrl(url);             Vector addrs = parsedUrl.getAddresses();            IiopUrl.Address addr;            NamingException savedException = null;             for (int i = 0; i < addrs.size(); i++) {                addr = (IiopUrl.Address)addrs.elementAt(i);                 try {                    if (defOrb != null) {                        try {                            String tmpUrl = "corbaloc:iiop:" + addr.host                                + ":" + addr.port + "/NameService";                            if (debug) {                                System.err.println("Using url: " + tmpUrl);                            }                            org.omg.CORBA.Object rootCtx =                                defOrb.string_to_object(tmpUrl);                            setOrbAndRootContext(defOrb, rootCtx);                            return parsedUrl.getStringName();                        } catch (Exception e) {} // keep going                    }                     // Get ORB                    if (debug) {                        System.err.println("Getting ORB for " + addr.host                            + " and port " + addr.port);                    }                     // Get ORB                    ORB orb = CorbaUtils.getOrb(addr.host, addr.port, env);                    orbTracker = new OrbReuseTracker(orb);                     // Assign to fields                    setOrbAndRootContext(orb, (String)null);                    return parsedUrl.getStringName();                 } catch (NamingException ne) {                    savedException = ne;                }            }            if (savedException != null) {                throw savedException;            } else {                throw new ConfigurationException("Problem with URL: " + url);            }        } catch (MalformedURLException e) {            throw new ConfigurationException(e.getMessage());        }    }     /**     * Initializes using "corbaname" URL (INS 99-12-03)     */    private String initUsingCorbanameUrl(ORB orb, String url, Hashtable env)        throws NamingException {        try {            CorbanameUrl parsedUrl = new CorbanameUrl(url);             String corbaloc = parsedUrl.getLocation();            String cosName = parsedUrl.getStringName();             if (orb == null) {                 // No ORB instance specified; create one using env and defaults                orb = CorbaUtils.getOrb(null, -1, env);                orbTracker = new OrbReuseTracker(orb);            }            setOrbAndRootContext(orb, corbaloc);             return parsedUrl.getStringName();        } catch (MalformedURLException e) {            throw new ConfigurationException(e.getMessage());        }    }     private void setOrbAndRootContext(ORB orb, String ncIor)        throws NamingException {        _orb = orb;        try {            org.omg.CORBA.Object ncRef;            if (ncIor != null) {                if (debug) {                    System.err.println("Passing to string_to_object: " + ncIor);                }                ncRef = _orb.string_to_object(ncIor);            } else {                ncRef = _orb.resolve_initial_references("NameService");            }            if (debug) {                System.err.println("Naming Context Ref: " + ncRef);            }            _nc = NamingContextHelper.narrow(ncRef);            if (_nc == null) {                if (ncIor != null) {                    throw new ConfigurationException(                        "Cannot convert IOR to a NamingContext: " + ncIor);                } else {                    throw new ConfigurationException("ORB.resolve_initial_references(\"NameService\") does not return a NamingContext");                }            }        } catch (org.omg.CORBA.ORBPackage.InvalidName in) {            NamingException ne =                new ConfigurationException("COS Name Service not registered with ORB under the name 'NameService'");            ne.setRootCause(in);            throw ne;        } catch (org.omg.CORBA.COMM_FAILURE e) {            NamingException ne =                new CommunicationException("Cannot connect to ORB");            ne.setRootCause(e);            throw ne;        } catch (org.omg.CORBA.BAD_PARAM e) {            NamingException ne = new ConfigurationException(                "Invalid URL or IOR: " + ncIor);            ne.setRootCause(e);            throw ne;        } catch (org.omg.CORBA.INV_OBJREF e) {            NamingException ne = new ConfigurationException(                "Invalid object reference: " + ncIor);            ne.setRootCause(e);            throw ne;        }    }     private void setOrbAndRootContext(ORB orb, org.omg.CORBA.Object ncRef)        throws NamingException {        _orb = orb;        try {            _nc = NamingContextHelper.narrow(ncRef);            if (_nc == null) {                throw new ConfigurationException(                    "Cannot convert object reference to NamingContext: " + ncRef);            }        } catch (org.omg.CORBA.COMM_FAILURE e) {            NamingException ne =                new CommunicationException("Cannot connect to ORB");            ne.setRootCause(e);            throw ne;        }    }     private String getStringifiedIor(String url) throws NamingException {        if (url.startsWith("IOR:") || url.startsWith("corbaloc:")) {            return url;        } else {            InputStream in = null;            try {                URL u = new URL(url);                in = u.openStream();                if (in != null) {                    BufferedReader bufin =                        new BufferedReader(new InputStreamReader(in, "8859_1"));                    String str;                    while ((str = bufin.readLine()) != null) {                        if (str.startsWith("IOR:")) {                            return str;                        }                    }                }            } catch (IOException e) {                NamingException ne =                    new ConfigurationException("Invalid URL: " + url);                ne.setRootCause(e);                throw ne;            } finally {                try {                    if (in != null) {                        in.close();                    }                } catch (IOException e) {                    NamingException ne =                        new ConfigurationException("Invalid URL: " + url);                    ne.setRootCause(e);                    throw ne;                }            }            throw new ConfigurationException(url + " does not contain an IOR");        }    }      /**      * Does the job of calling the COS Naming API,      * resolve, and performs the exception mapping. If the resolved      * object is a COS Naming Context (sub-context), then this function      * returns a new JNDI naming context object.      * @param path the NameComponent[] object.      * @exception NotFound No objects under the name.      * @exception CannotProceed Unable to obtain a continuation context      * @exception InvalidName Name not understood.      * @return Resolved object returned by the COS Name Server.      */    java.lang.Object callResolve(NameComponent[] path)        throws NamingException {            try {                org.omg.CORBA.Object obj = _nc.resolve(path);                try {                    NamingContext nc =                        NamingContextHelper.narrow(obj);                    if (nc != null) {                        return new CNCtx(_orb, orbTracker, nc, _env,                                        makeFullName(path));                    } else {                        return obj;                    }                } catch (org.omg.CORBA.SystemException e) {                    return obj;                }            } catch (Exception e) {

Lines 1–500 of 1160.