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 final class JndiUtils {
31  
32    private static final Logger LOG = LoggerFactory.getLogger(JndiUtils.class);
33  
34    private JndiUtils() {
35    }
36  
37    public static Object getJndiProperty(Context ctx, String... path) throws NamingException {
38      return getJndiProperty(ctx, null, path);
39    }
40  
41    public static Object getJndiProperty(Context ctx, Object defaultValue, String... path) throws NamingException {
42      String name = "java:comp/env";
43      // avoid error messages from websphere
44      for (int i = 0; i < path.length; i++) {
45        Binding b = getBinding(ctx, name, path[i]);
46        if (b == null) {
47          break;
48        }
49        if (i == path.length - 1) {
50          Object obj = b.getObject();
51          if (LOG.isDebugEnabled()) {
52            LOG.debug("Value: " + obj);
53          }
54          return obj;
55        } else {
56          name = name + "/" + path[i];
57        }
58      }
59      return defaultValue;
60    }
61  
62    private static Binding getBinding(Context ctx, String name, String path)
63        throws NamingException {
64      NamingEnumeration<Binding> ne = ctx.listBindings(name);
65      while (ne.hasMore()) {
66        Binding b = ne.next();
67        if (LOG.isDebugEnabled()) {
68          LOG.debug("Property: " + b.getName());
69        }
70        if (path.equals(b.getName())) {
71          return b;
72        }
73      }
74      return null;
75    }
76  
77  }