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