1 package org.itracker.services.util;
2
3 import java.util.Hashtable;
4
5 import javax.naming.Context;
6 import javax.naming.InitialContext;
7 import javax.naming.NameNotFoundException;
8 import javax.naming.NamingException;
9
10 import org.apache.log4j.Logger;
11
12
13
14
15
16
17
18 public class NamingUtilites {
19
20 private static final Logger log = Logger.getLogger(NamingUtilites.class
21 .getName());
22
23
24
25
26
27
28
29
30
31
32
33
34 public static final String getStringValue(Context ctx, String lookupName,
35 String defaultValue) {
36 String value = null;
37 Object val;
38 if (log.isDebugEnabled()) {
39 log.debug("getStringValue: look up " + lookupName + " in context "
40 + ctx + ", default: " + defaultValue);
41
42 }
43
44
45
46 if (null == ctx) {
47 log.debug("getStringValue: creating new InitialContext");
48 try {
49 ctx = new InitialContext();
50 if (log.isDebugEnabled()) {
51 log.debug("created new InitialContext: " + ctx);
52 }
53 } catch (NamingException e) {
54 log.warn("getStringValue: failed to create InitialContext", e);
55 if (log.isDebugEnabled())
56 log.debug("getStringValue: context was null, exception from new initial context caught", e);
57 }
58 }
59
60
61 if (null != ctx) {
62
63
64 val = lookup(ctx, lookupName);
65 if (val instanceof String) {
66 value = (String) val;
67 } else {
68 value = (null == val) ? null : String.valueOf(val);
69 }
70
71 }
72 value = (null == value) ? defaultValue : value;
73 if (log.isDebugEnabled()) {
74 log.debug("getStringValue: returning '" + value + "' for " + lookupName);
75
76 }
77
78 return value;
79 }
80
81
82
83
84
85
86
87
88
89
90 public static final Object lookup(Context ctx, String lookupName) {
91 if (null == ctx) {
92 throw new IllegalArgumentException("context must not be null");
93 }
94 if (null == lookupName || lookupName.trim().length() == 0) {
95 throw new IllegalArgumentException(
96 "lookup name must not be empty, got: "
97 + ((null == lookupName) ? "<null>" : "'"
98 + lookupName + "'"));
99 }
100 try {
101 return ctx.lookup(lookupName);
102 } catch (NamingException e) {
103 if (e instanceof NameNotFoundException) {
104 if (log.isDebugEnabled()){
105 log.debug("lookup: failed to lookup " + lookupName
106 + ": name not found");
107 }
108 } else {
109 log.warn("lookup: failed to lookup " + lookupName
110 + " in context " + ctx, e);
111 }
112 return null;
113 }
114 }
115
116
117
118
119
120
121
122 public static final Context getDefaultInitialContext(Hashtable<?,?> environment) throws NamingException {
123 return new InitialContext(environment);
124 }
125
126
127
128
129
130
131 public static final Context getDefaultInitialContext() throws NamingException {
132 return new InitialContext();
133 }
134 }