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