NamingContext.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.naming;

  18. import java.util.Enumeration;
  19. import java.util.HashMap;
  20. import java.util.Hashtable;

  21. import javax.naming.Binding;
  22. import javax.naming.CompositeName;
  23. import javax.naming.Context;
  24. import javax.naming.InitialContext;
  25. import javax.naming.LinkRef;
  26. import javax.naming.Name;
  27. import javax.naming.NameAlreadyBoundException;
  28. import javax.naming.NameClassPair;
  29. import javax.naming.NameNotFoundException;
  30. import javax.naming.NameParser;
  31. import javax.naming.NamingEnumeration;
  32. import javax.naming.NamingException;
  33. import javax.naming.NotContextException;
  34. import javax.naming.OperationNotSupportedException;
  35. import javax.naming.Reference;
  36. import javax.naming.Referenceable;
  37. import javax.naming.spi.NamingManager;
  38. import javax.naming.spi.ObjectFactory;

  39. import org.apache.juli.logging.Log;
  40. import org.apache.juli.logging.LogFactory;

  41. /**
  42.  * Catalina JNDI Context implementation.
  43.  *
  44.  * @author Remy Maucherat
  45.  */
  46. public class NamingContext implements Context {


  47.     // -------------------------------------------------------------- Constants


  48.     /**
  49.      * Name parser for this context.
  50.      */
  51.     protected static final NameParser nameParser = new NameParserImpl();


  52.     private static final Log log = LogFactory.getLog(NamingContext.class);


  53.     // ----------------------------------------------------------- Constructors


  54.     /**
  55.      * Builds a naming context.
  56.      *
  57.      * @param env The environment to use to construct the naming context
  58.      * @param name The name of the associated Catalina Context
  59.      */
  60.     public NamingContext(Hashtable<String,Object> env, String name) {
  61.         this(env, name, new HashMap<>());
  62.     }


  63.     /**
  64.      * Builds a naming context.
  65.      *
  66.      * @param env The environment to use to construct the naming context
  67.      * @param name The name of the associated Catalina Context
  68.      * @param bindings The initial bindings for the naming context
  69.      */
  70.     public NamingContext(Hashtable<String,Object> env, String name,
  71.             HashMap<String,NamingEntry> bindings) {

  72.         this.env = new Hashtable<>();
  73.         this.name = name;
  74.         // Populating the environment hashtable
  75.         if (env != null ) {
  76.             Enumeration<String> envEntries = env.keys();
  77.             while (envEntries.hasMoreElements()) {
  78.                 String entryName = envEntries.nextElement();
  79.                 addToEnvironment(entryName, env.get(entryName));
  80.             }
  81.         }
  82.         this.bindings = bindings;
  83.     }


  84.     // ----------------------------------------------------- Instance Variables


  85.     /**
  86.      * Environment.
  87.      */
  88.     protected final Hashtable<String,Object> env;


  89.     /**
  90.      * The string manager for this package.
  91.      */
  92.     protected static final StringManager sm = StringManager.getManager(NamingContext.class);


  93.     /**
  94.      * Bindings in this Context.
  95.      */
  96.     protected final HashMap<String,NamingEntry> bindings;


  97.     /**
  98.      * Name of the associated Catalina Context.
  99.      */
  100.     protected final String name;


  101.     /**
  102.      * Determines if an attempt to write to a read-only context results in an
  103.      * exception or if the request is ignored.
  104.      */
  105.     private boolean exceptionOnFailedWrite = true;
  106.     public boolean getExceptionOnFailedWrite() {
  107.         return exceptionOnFailedWrite;
  108.     }
  109.     public void setExceptionOnFailedWrite(boolean exceptionOnFailedWrite) {
  110.         this.exceptionOnFailedWrite = exceptionOnFailedWrite;
  111.     }


  112.     // -------------------------------------------------------- Context Methods

  113.     @Override
  114.     public Object lookup(Name name)
  115.         throws NamingException {
  116.         return lookup(name, true);
  117.     }


  118.     @Override
  119.     public Object lookup(String name)
  120.         throws NamingException {
  121.         return lookup(new CompositeName(name), true);
  122.     }


  123.     @Override
  124.     public void bind(Name name, Object obj)
  125.         throws NamingException {
  126.         bind(name, obj, false);
  127.     }


  128.     @Override
  129.     public void bind(String name, Object obj)
  130.         throws NamingException {
  131.         bind(new CompositeName(name), obj);
  132.     }


  133.     @Override
  134.     public void rebind(Name name, Object obj)
  135.         throws NamingException {
  136.         bind(name, obj, true);
  137.     }


  138.     @Override
  139.     public void rebind(String name, Object obj)
  140.         throws NamingException {
  141.         rebind(new CompositeName(name), obj);
  142.     }


  143.     @Override
  144.     public void unbind(Name name) throws NamingException {

  145.         if (!checkWritable()) {
  146.             return;
  147.         }

  148.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  149.             name = name.getSuffix(1);
  150.         }
  151.         if (name.isEmpty()) {
  152.             throw new NamingException
  153.                 (sm.getString("namingContext.invalidName"));
  154.         }

  155.         NamingEntry entry = bindings.get(name.get(0));

  156.         if (entry == null) {
  157.             throw new NameNotFoundException
  158.                 (sm.getString("namingContext.nameNotBound", name, name.get(0)));
  159.         }

  160.         if (name.size() > 1) {
  161.             if (entry.type == NamingEntry.CONTEXT) {
  162.                 ((Context) entry.value).unbind(name.getSuffix(1));
  163.             } else {
  164.                 throw new NamingException
  165.                     (sm.getString("namingContext.contextExpected"));
  166.             }
  167.         } else {
  168.             bindings.remove(name.get(0));
  169.         }

  170.     }


  171.     @Override
  172.     public void unbind(String name)
  173.         throws NamingException {
  174.         unbind(new CompositeName(name));
  175.     }


  176.     @Override
  177.     public void rename(Name oldName, Name newName)
  178.         throws NamingException {
  179.         Object value = lookup(oldName);
  180.         bind(newName, value);
  181.         unbind(oldName);
  182.     }


  183.     @Override
  184.     public void rename(String oldName, String newName)
  185.         throws NamingException {
  186.         rename(new CompositeName(oldName), new CompositeName(newName));
  187.     }


  188.     @Override
  189.     public NamingEnumeration<NameClassPair> list(Name name)
  190.         throws NamingException {
  191.         // Removing empty parts
  192.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  193.             name = name.getSuffix(1);
  194.         }
  195.         if (name.isEmpty()) {
  196.             return new NamingContextEnumeration(bindings.values().iterator());
  197.         }

  198.         NamingEntry entry = bindings.get(name.get(0));

  199.         if (entry == null) {
  200.             throw new NameNotFoundException
  201.                 (sm.getString("namingContext.nameNotBound", name, name.get(0)));
  202.         }

  203.         if (entry.type != NamingEntry.CONTEXT) {
  204.             throw new NamingException
  205.                 (sm.getString("namingContext.contextExpected"));
  206.         }
  207.         return ((Context) entry.value).list(name.getSuffix(1));
  208.     }


  209.     @Override
  210.     public NamingEnumeration<NameClassPair> list(String name)
  211.         throws NamingException {
  212.         return list(new CompositeName(name));
  213.     }


  214.     @Override
  215.     public NamingEnumeration<Binding> listBindings(Name name)
  216.         throws NamingException {
  217.         // Removing empty parts
  218.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  219.             name = name.getSuffix(1);
  220.         }
  221.         if (name.isEmpty()) {
  222.             return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
  223.         }

  224.         NamingEntry entry = bindings.get(name.get(0));

  225.         if (entry == null) {
  226.             throw new NameNotFoundException
  227.                 (sm.getString("namingContext.nameNotBound", name, name.get(0)));
  228.         }

  229.         if (entry.type != NamingEntry.CONTEXT) {
  230.             throw new NamingException
  231.                 (sm.getString("namingContext.contextExpected"));
  232.         }
  233.         return ((Context) entry.value).listBindings(name.getSuffix(1));
  234.     }


  235.     @Override
  236.     public NamingEnumeration<Binding> listBindings(String name)
  237.         throws NamingException {
  238.         return listBindings(new CompositeName(name));
  239.     }


  240.     @Override
  241.     public void destroySubcontext(Name name) throws NamingException {

  242.         if (!checkWritable()) {
  243.             return;
  244.         }

  245.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  246.             name = name.getSuffix(1);
  247.         }
  248.         if (name.isEmpty()) {
  249.             throw new NamingException
  250.                 (sm.getString("namingContext.invalidName"));
  251.         }

  252.         NamingEntry entry = bindings.get(name.get(0));

  253.         if (entry == null) {
  254.             throw new NameNotFoundException
  255.                 (sm.getString("namingContext.nameNotBound", name, name.get(0)));
  256.         }

  257.         if (name.size() > 1) {
  258.             if (entry.type == NamingEntry.CONTEXT) {
  259.                 ((Context) entry.value).destroySubcontext(name.getSuffix(1));
  260.             } else {
  261.                 throw new NamingException
  262.                     (sm.getString("namingContext.contextExpected"));
  263.             }
  264.         } else {
  265.             if (entry.type == NamingEntry.CONTEXT) {
  266.                 ((Context) entry.value).close();
  267.                 bindings.remove(name.get(0));
  268.             } else {
  269.                 throw new NotContextException
  270.                     (sm.getString("namingContext.contextExpected"));
  271.             }
  272.         }

  273.     }


  274.     @Override
  275.     public void destroySubcontext(String name)
  276.         throws NamingException {
  277.         destroySubcontext(new CompositeName(name));
  278.     }


  279.     @Override
  280.     public Context createSubcontext(Name name) throws NamingException {
  281.         if (!checkWritable()) {
  282.             return null;
  283.         }

  284.         NamingContext newContext = new NamingContext(env, this.name);
  285.         bind(name, newContext);

  286.         newContext.setExceptionOnFailedWrite(getExceptionOnFailedWrite());

  287.         return newContext;
  288.     }


  289.     @Override
  290.     public Context createSubcontext(String name)
  291.         throws NamingException {
  292.         return createSubcontext(new CompositeName(name));
  293.     }


  294.     @Override
  295.     public Object lookupLink(Name name)
  296.         throws NamingException {
  297.         return lookup(name, false);
  298.     }


  299.     @Override
  300.     public Object lookupLink(String name)
  301.         throws NamingException {
  302.         return lookup(new CompositeName(name), false);
  303.     }


  304.     @Override
  305.     public NameParser getNameParser(Name name)
  306.         throws NamingException {

  307.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  308.             name = name.getSuffix(1);
  309.         }
  310.         if (name.isEmpty()) {
  311.             return nameParser;
  312.         }

  313.         if (name.size() > 1) {
  314.             Object obj = bindings.get(name.get(0));
  315.             if (obj instanceof Context) {
  316.                 return ((Context) obj).getNameParser(name.getSuffix(1));
  317.             } else {
  318.                 throw new NotContextException
  319.                     (sm.getString("namingContext.contextExpected"));
  320.             }
  321.         }

  322.         return nameParser;

  323.     }


  324.     @Override
  325.     public NameParser getNameParser(String name)
  326.         throws NamingException {
  327.         return getNameParser(new CompositeName(name));
  328.     }


  329.     @Override
  330.     public Name composeName(Name name, Name prefix) throws NamingException {
  331.         prefix = (Name) prefix.clone();
  332.         return prefix.addAll(name);
  333.     }


  334.     @Override
  335.     public String composeName(String name, String prefix) {
  336.         return prefix + "/" + name;
  337.     }


  338.     @Override
  339.     public Object addToEnvironment(String propName, Object propVal) {
  340.         return env.put(propName, propVal);
  341.     }


  342.     @Override
  343.     public Object removeFromEnvironment(String propName){
  344.         return env.remove(propName);
  345.     }


  346.     @Override
  347.     public Hashtable<?,?> getEnvironment() {
  348.         return env;
  349.     }


  350.     @Override
  351.     public void close() throws NamingException {
  352.         if (!checkWritable()) {
  353.             return;
  354.         }
  355.         env.clear();
  356.     }


  357.     @Override
  358.     public String getNameInNamespace()
  359.         throws NamingException {
  360.         throw  new OperationNotSupportedException
  361.             (sm.getString("namingContext.noAbsoluteName"));
  362.     }


  363.     // ------------------------------------------------------ Protected Methods


  364.     private static final boolean GRAAL;

  365.     static {
  366.         boolean result = false;
  367.         try {
  368.             Class<?> nativeImageClazz = Class.forName("org.graalvm.nativeimage.ImageInfo");
  369.             result = Boolean.TRUE.equals(nativeImageClazz.getMethod("inImageCode").invoke(null));
  370.         } catch (ClassNotFoundException e) {
  371.             // Must be Graal
  372.         } catch (ReflectiveOperationException | IllegalArgumentException e) {
  373.             // Should never happen
  374.         }
  375.         GRAAL = result || System.getProperty("org.graalvm.nativeimage.imagecode") != null;
  376.     }

  377.     /**
  378.      * Retrieves the named object.
  379.      *
  380.      * @param name the name of the object to look up
  381.      * @param resolveLinks If true, the links will be resolved
  382.      * @return the object bound to name
  383.      * @exception NamingException if a naming exception is encountered
  384.      */
  385.     protected Object lookup(Name name, boolean resolveLinks)
  386.         throws NamingException {

  387.         // Removing empty parts
  388.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  389.             name = name.getSuffix(1);
  390.         }
  391.         if (name.isEmpty()) {
  392.             // If name is empty, a newly allocated naming context is returned
  393.             return new NamingContext(env, this.name, bindings);
  394.         }

  395.         NamingEntry entry = bindings.get(name.get(0));

  396.         if (entry == null) {
  397.             throw new NameNotFoundException
  398.                 (sm.getString("namingContext.nameNotBound", name, name.get(0)));
  399.         }

  400.         if (name.size() > 1) {
  401.             // If the size of the name is greater that 1, then we go through a
  402.             // number of subcontexts.
  403.             if (entry.type != NamingEntry.CONTEXT) {
  404.                 throw new NamingException
  405.                     (sm.getString("namingContext.contextExpected"));
  406.             }
  407.             return ((Context) entry.value).lookup(name.getSuffix(1));
  408.         } else {
  409.             if ((resolveLinks) && (entry.type == NamingEntry.LINK_REF)) {
  410.                 String link = ((LinkRef) entry.value).getLinkName();
  411.                 if (link.startsWith(".")) {
  412.                     // Link relative to this context
  413.                     return lookup(link.substring(1));
  414.                 } else {
  415.                     return new InitialContext(env).lookup(link);
  416.                 }
  417.             } else if (entry.type == NamingEntry.REFERENCE) {
  418.                 try {
  419.                     Object obj = null;
  420.                     if (!GRAAL) {
  421.                         obj = NamingManager.getObjectInstance(entry.value, name, this, env);
  422.                     } else {
  423.                         // NamingManager.getObjectInstance would simply return the reference here
  424.                         // Use the configured object factory to resolve it directly if possible
  425.                         // Note: This may need manual constructor reflection configuration
  426.                         Reference reference = (Reference) entry.value;
  427.                         String factoryClassName = reference.getFactoryClassName();
  428.                         if (factoryClassName != null) {
  429.                             Class<?> factoryClass = getClass().getClassLoader().loadClass(factoryClassName);
  430.                             ObjectFactory factory = (ObjectFactory) factoryClass.getDeclaredConstructor().newInstance();
  431.                             obj = factory.getObjectInstance(entry.value, name, this, env);
  432.                         }
  433.                     }
  434.                     if (entry.value instanceof ResourceRef) {
  435.                         boolean singleton = Boolean.parseBoolean(
  436.                                     (String) ((ResourceRef) entry.value).get(
  437.                                             ResourceRef.SINGLETON).getContent());
  438.                         if (singleton) {
  439.                             entry.type = NamingEntry.ENTRY;
  440.                             entry.value = obj;
  441.                         }
  442.                     }
  443.                     if (obj == null) {
  444.                         throw new NamingException(sm.getString("namingContext.failResolvingReference"));
  445.                     }
  446.                     return obj;
  447.                 } catch (NamingException e) {
  448.                     throw e;
  449.                 } catch (Exception e) {
  450.                     String msg = sm.getString("namingContext.failResolvingReference");
  451.                     log.warn(msg, e);
  452.                     NamingException ne = new NamingException(msg);
  453.                     ne.initCause(e);
  454.                     throw ne;
  455.                 }
  456.             } else {
  457.                 return entry.value;
  458.             }
  459.         }

  460.     }


  461.     /**
  462.      * Binds a name to an object. All intermediate contexts and the target
  463.      * context (that named by all but terminal atomic component of the name)
  464.      * must already exist.
  465.      *
  466.      * @param name the name to bind; may not be empty
  467.      * @param obj the object to bind; possibly null
  468.      * @param rebind if true, then perform a rebind (ie, overwrite)
  469.      * @exception NameAlreadyBoundException if name is already bound
  470.      * @exception javax.naming.directory.InvalidAttributesException if object
  471.      * did not supply all mandatory attributes
  472.      * @exception NamingException if a naming exception is encountered
  473.      */
  474.     protected void bind(Name name, Object obj, boolean rebind)
  475.         throws NamingException {

  476.         if (!checkWritable()) {
  477.             return;
  478.         }

  479.         while ((!name.isEmpty()) && (name.get(0).length() == 0)) {
  480.             name = name.getSuffix(1);
  481.         }
  482.         if (name.isEmpty()) {
  483.             throw new NamingException
  484.                 (sm.getString("namingContext.invalidName"));
  485.         }

  486.         NamingEntry entry = bindings.get(name.get(0));

  487.         if (name.size() > 1) {
  488.             if (entry == null) {
  489.                 throw new NameNotFoundException(sm.getString(
  490.                         "namingContext.nameNotBound", name, name.get(0)));
  491.             }
  492.             if (entry.type == NamingEntry.CONTEXT) {
  493.                 if (rebind) {
  494.                     ((Context) entry.value).rebind(name.getSuffix(1), obj);
  495.                 } else {
  496.                     ((Context) entry.value).bind(name.getSuffix(1), obj);
  497.                 }
  498.             } else {
  499.                 throw new NamingException
  500.                     (sm.getString("namingContext.contextExpected"));
  501.             }
  502.         } else {
  503.             if ((!rebind) && (entry != null)) {
  504.                 throw new NameAlreadyBoundException
  505.                     (sm.getString("namingContext.alreadyBound", name.get(0)));
  506.             } else {
  507.                 // Getting the type of the object and wrapping it within a new
  508.                 // NamingEntry
  509.                 Object toBind =
  510.                     NamingManager.getStateToBind(obj, name, this, env);
  511.                 if (toBind instanceof Context) {
  512.                     entry = new NamingEntry(name.get(0), toBind,
  513.                                             NamingEntry.CONTEXT);
  514.                 } else if (toBind instanceof LinkRef) {
  515.                     entry = new NamingEntry(name.get(0), toBind,
  516.                                             NamingEntry.LINK_REF);
  517.                 } else if (toBind instanceof Reference) {
  518.                     entry = new NamingEntry(name.get(0), toBind,
  519.                                             NamingEntry.REFERENCE);
  520.                 } else if (toBind instanceof Referenceable) {
  521.                     toBind = ((Referenceable) toBind).getReference();
  522.                     entry = new NamingEntry(name.get(0), toBind,
  523.                                             NamingEntry.REFERENCE);
  524.                 } else {
  525.                     entry = new NamingEntry(name.get(0), toBind,
  526.                                             NamingEntry.ENTRY);
  527.                 }
  528.                 bindings.put(name.get(0), entry);
  529.             }
  530.         }

  531.     }


  532.     /**
  533.      * @return <code>true</code> if writing is allowed on this context.
  534.      */
  535.     protected boolean isWritable() {
  536.         return ContextAccessController.isWritable(name);
  537.     }


  538.     /**
  539.      * Throws a naming exception is Context is not writable.
  540.      * @return <code>true</code> if the Context is writable
  541.      * @throws NamingException if the Context is not writable and
  542.      *  <code>exceptionOnFailedWrite</code> is <code>true</code>
  543.      */
  544.     protected boolean checkWritable() throws NamingException {
  545.         if (isWritable()) {
  546.             return true;
  547.         } else {
  548.             if (exceptionOnFailedWrite) {
  549.                 throw new OperationNotSupportedException(sm.getString("namingContext.readOnly"));
  550.             }
  551.         }
  552.         return false;
  553.     }
  554. }