View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.internal.util;
21  
22  import org.slf4j.Logger;
23  import org.slf4j.LoggerFactory;
24  
25  import javax.naming.Binding;
26  import javax.naming.Context;
27  import javax.naming.NamingEnumeration;
28  import javax.naming.NamingException;
29  
30  public class JndiUtils {
31  
32    private static final Logger LOG = LoggerFactory.getLogger(JndiUtils.class);
33  
34    public static Object getJndiProperty(Context ctx, String... path) throws NamingException {
35      return getJndiProperty(ctx, null, path);
36    }
37  
38    public static Object getJndiProperty(Context ctx, Object defaultValue, String... path) throws NamingException {
39      String name = "java:comp/env";
40      // avoid error messages from websphere
41      for (int i = 0; i < path.length; i++) {
42        Binding b = getBinding(ctx, name, path[i]);
43        if (b == null) {
44          break;
45        }
46        if (i == path.length - 1) {
47          Object obj = b.getObject();
48          if (LOG.isDebugEnabled()) {
49            LOG.debug("Value: " + obj);
50          }
51          return obj;
52        } else {
53          name = name + "/" + path[i];
54        }
55      }
56      return defaultValue;
57    }
58  
59    private static Binding getBinding(Context ctx, String name, String path)
60        throws NamingException {
61      NamingEnumeration<Binding> ne = ctx.listBindings(name);
62      while (ne.hasMore()) {
63        Binding b = ne.next();
64        if (LOG.isDebugEnabled()) {
65          LOG.debug("Property: " + b.getName());
66        }
67        if (path.equals(b.getName())) {
68          return b;
69        }
70      }
71      return null;
72    }
73  
74  }