001: /**
002: * $Id: PSBaseBean.java,v 1.13 2006/08/23 02:56:23 rt94277 Exp $
003: * Copyright 2005 Sun Microsystems, Inc. All
004: * rights reserved. Use of this product is subject
005: * to license terms. Federal Acquisitions:
006: * Commercial Software -- Government Users
007: * Subject to Standard License Terms and
008: * Conditions.
009: *
010: * Sun, Sun Microsystems, the Sun logo, and Sun ONE
011: * are trademarks or registered trademarks of Sun Microsystems,
012: * Inc. in the United States and other countries.
013: */package com.sun.portal.admin.console.common;
014:
015: import java.io.IOException;
016: import java.util.logging.Logger;
017: import java.util.logging.Level;
018: import java.util.Map;
019: import java.util.HashMap;
020: import java.util.Collections;
021: import java.util.Enumeration;
022: import java.util.Set;
023: import java.util.HashSet;
024: import java.util.LinkedList;
025: import java.util.Locale;
026: import java.util.ResourceBundle;
027:
028: import javax.servlet.ServletContext;
029: import javax.servlet.http.HttpServletRequest;
030: import javax.servlet.http.HttpServletResponse;
031: import javax.servlet.http.Cookie;
032: import javax.servlet.http.HttpSession;
033:
034: import javax.management.remote.JMXConnector;
035: import javax.management.MBeanServerConnection;
036: import javax.management.ObjectName;
037: import javax.management.QueryExp;
038: import javax.management.MBeanException;
039: import javax.management.ReflectionException;
040: import javax.management.MalformedObjectNameException;
041: import javax.management.InstanceNotFoundException;
042:
043: import javax.faces.context.FacesContext;
044:
045: import com.sun.portal.util.Encoder;
046: import com.sun.portal.admin.console.PSConsoleLogManager;
047: import com.sun.portal.admin.common.util.AdminClientUtil;
048:
049: public class PSBaseBean implements SessionAttributeNames {
050:
051: public static final String GLOBAL_LOCATION_DN = "_!global!_";
052: public static final String GLOBAL_LABEL = "TopLevel";
053:
054: private static String BOOKMARK_COOKIE_NAME = "psconsole.bookmarks";
055: private static final int BOOKMARK_MAX_AGE = 157680000;
056: private static Map dnTypeMap = Collections
057: .synchronizedMap(new HashMap());
058:
059: private boolean alert = false;
060: private String alertDetail = null;
061: private String alertType = null;
062: private String alertSummary = null;
063:
064: public PSBaseBean() {
065: }
066:
067: protected String getDomain() {
068: return AdminClientUtil.DEFAULT_DOMAIN;
069: }
070:
071: private static Object getLogger() {
072: // Log to servlet container for now
073: // TODO: use JDK or Portal logging framework
074: Object obj = null;
075: if (!PSConsoleLogManager.isStandAloneDeploy()) {
076: obj = PSConsoleLogManager.getLogger();
077: } else {
078: obj = PSConsoleLogManager.getContextLogger();
079: }
080: return obj;
081: }
082:
083: /**
084: * Logs a message to the debug log file.
085: * <p>
086: * This method logs the given message to the debug log file.
087: * <p>
088: * Note that this method now has the following limitations.
089: *
090: * No checking against the current configured log level.(Always log)
091: * Loading message from resource bundle based on locale
092: *
093: * @param level the level that this message should be logged against.
094: * @param msg the message to be logged.
095: */
096: public static void log(Level level, String msg) {
097: Object obj = getLogger();
098: if ((obj != null) && (obj instanceof Logger)) {
099: Logger logger = (Logger) obj;
100: logger.log(level, msg);
101: } else if ((obj != null) && (obj instanceof ServletContext)) {
102: ServletContext logger = (ServletContext) obj;
103: logger.log(level + ":" + msg);
104: }
105: }
106:
107: /**
108: * Logs a message and throwable object to the debug log file.
109: * <p>
110: * This method logs the given message and throwable object to the
111: * debug log file.
112: * <p>
113: * Note that this method now has the following limitations.
114: *
115: * No checking against the current configured log level.(Always log)
116: * Loading message from resource bundle based on locale
117: *
118: * @param level the level that this message should be logged against.
119: * @param msg the message to be logged.
120: */
121: public static void log(Level level, String msg, Throwable t) {
122: Object obj = getLogger();
123: if ((obj != null) && (obj instanceof Logger)) {
124: Logger logger = (Logger) obj;
125: logger.log(level, msg, t);
126: } else if ((obj != null) && (obj instanceof ServletContext)) {
127: ServletContext logger = (ServletContext) obj;
128: logger.log(level + ":" + msg, t);
129: }
130: }
131:
132: public static Object getSessionAttribute(String name) {
133: Map smap = FacesContext.getCurrentInstance()
134: .getExternalContext().getSessionMap();
135: if ((smap != null) && (!smap.isEmpty())) {
136: return smap.get(name);
137: }
138: return null;
139: }
140:
141: public static void setSessionAttribute(String name, Object value) {
142: Map smap = FacesContext.getCurrentInstance()
143: .getExternalContext().getSessionMap();
144: if (smap != null) {
145: smap.put(name, value);
146: }
147: }
148:
149: public static void removeFromSession(String name) {
150: Map smap = FacesContext.getCurrentInstance()
151: .getExternalContext().getSessionMap();
152: if ((smap != null) && (!smap.isEmpty())) {
153: smap.remove(name);
154: }
155: }
156:
157: public Object getCurrentDN() {
158: Object currentDN = getSessionAttribute(ATTR_CURRENT_LOCATION_DN);
159: if (currentDN == null) {
160: currentDN = GLOBAL_LOCATION_DN;
161: }
162: return currentDN;
163: }
164:
165: public void setCurrentDN(Object currentDN) {
166: log(Level.FINEST, "setting currentDN to" + currentDN);
167: setSessionAttribute(ATTR_CURRENT_LOCATION_DN, currentDN);
168: }
169:
170: public boolean isGlobalDN(String dn) {
171: if (dn.equals(GLOBAL_LOCATION_DN)) {
172: return true;
173: } else {
174: return false;
175: }
176: }
177:
178: public boolean isAlert() {
179: return alert;
180: }
181:
182: public String getAlertDetail() {
183: return alertDetail;
184: }
185:
186: public String getAlertSummary() {
187: return alertSummary;
188: }
189:
190: public String getAlertType() {
191: return alertType;
192: }
193:
194: protected void setAlertDetail(String alertDtls) {
195: alertDetail = alertDtls;
196: }
197:
198: protected void setAlertSummary(String alertSumm) {
199: alertSummary = alertSumm;
200: }
201:
202: protected void setAlertType(String type) {
203: alertType = type;
204: }
205:
206: public void setAlert(boolean value) {
207: alert = value;
208: }
209:
210: protected void showAlert() {
211: alert = true;
212: }
213:
214: protected void clearAlert() {
215: alert = false;
216: }
217:
218: protected void setSuccessAlert() {
219: String sm = getLocalizedString("common", "common.alert.save");
220: setAlert(true);
221: setAlertType("information");
222: setAlertSummary(sm);
223: }
224:
225: public boolean isRoleDN(String dn) {
226: if (isGlobalDN(dn)) {
227: return false;
228: }
229: Integer otype = null;
230: if (dnTypeMap.containsKey(dn)) {
231: otype = (Integer) dnTypeMap.get(dn);
232: } else {
233: otype = getAMObjectType(dn);
234: if (otype != null) {
235: dnTypeMap.put(dn, otype);
236: }
237: }
238: if (otype != null && otype.intValue() == 1) {
239: return true;
240: }
241: return false;
242: }
243:
244: public boolean isFilteredRoleDN(String dn) {
245: if (isGlobalDN(dn)) {
246: return false;
247: }
248: Integer otype = null;
249: if (dnTypeMap.containsKey(dn)) {
250: otype = (Integer) dnTypeMap.get(dn);
251: } else {
252: otype = getAMObjectType(dn);
253: if (otype != null) {
254: dnTypeMap.put(dn, otype);
255: }
256: }
257: if (otype != null && otype.intValue() == 3) {
258: return true;
259: }
260: return false;
261: }
262:
263: public boolean isOrgDN(String dn) {
264: if (isGlobalDN(dn)) {
265: return false;
266: }
267: Integer otype = null;
268: if (dnTypeMap.containsKey(dn)) {
269: otype = (Integer) dnTypeMap.get(dn);
270: } else {
271: otype = getAMObjectType(dn);
272: if (otype != null) {
273: dnTypeMap.put(dn, otype);
274: }
275: }
276: if (otype != null && otype.intValue() == 2) {
277: return true;
278: }
279: return false;
280: }
281:
282: public boolean isUserDN(String dn) {
283: if (isGlobalDN(dn)) {
284: return false;
285: }
286: Integer otype = null;
287: if (dnTypeMap.containsKey(dn)) {
288: otype = (Integer) dnTypeMap.get(dn);
289: } else {
290: otype = getAMObjectType(dn);
291: if (otype != null) {
292: dnTypeMap.put(dn, otype);
293: }
294: }
295: if (otype != null && otype.intValue() == 0) {
296: return true;
297: }
298: return false;
299: }
300:
301: public Integer getAMObjectType(String dn) {
302: Integer result = null;
303: try {
304: MBeanServerConnection msc = getMBeanServerConnection();
305: ObjectName objName = null;
306: LinkedList path = new LinkedList();
307: path.addFirst(AdminClientUtil.DEFAULT_DOMAIN);
308: path.addFirst("amobjsearch");
309: objName = AdminClientUtil.getResourceMBeanObjectName(
310: AdminClientUtil.AMOBJECTSEARCH_MBEAN_TYPE, path);
311: Object[] params = new Object[] { dn };
312: String[] signature = new String[] { "java.lang.String" };
313: result = (Integer) msc.invoke(objName, "queryObjectType",
314: params, signature);
315: } catch (InstanceNotFoundException infe) {
316: log(Level.SEVERE,
317: "Exception in PSBaseBean.getAMObjectType()", infe);
318: //throw infe
319: } catch (MBeanException me) {
320: log(Level.SEVERE,
321: "Exception in PSBaseBean.getAMObjectType()", me);
322: //throw me;
323: } catch (ReflectionException re) {
324: log(Level.SEVERE,
325: "Exception in PSBaseBean.getAMObjectType()", re);
326: //throw re;
327: } catch (IOException ioe) {
328: log(Level.SEVERE,
329: "Exception in PSBaseBean.getAMObjectType()", ioe);
330: //throw ioe
331: } catch (MalformedObjectNameException mone) {
332: //throw mone
333: log(Level.SEVERE,
334: "Exception in PSBaseBean.getAMObjectType()", mone);
335: } catch (Exception e) {
336: log(Level.SEVERE,
337: "Exception in PSBaseBean.getAMObjectType()", e);
338: //throw e;
339: }
340: return result;
341: }
342:
343: public static void saveBookmarks(String userDN, Map bookmarks) {
344: log(Level.FINEST, "Saving Bookmarks: " + bookmarks);
345: Map bookmarkMap = getBookmarkMap();
346: bookmarkMap.put(userDN, bookmarks);
347: String cookieValue = null;
348: try {
349: cookieValue = Encoder.encodeHttp64(Encoder.serialize(
350: (HashMap) bookmarkMap, true), 1024);
351: } catch (IOException ioe) {
352: log(Level.FINEST,
353: "Exception in PSBaseBean.saveBookmarks()", ioe);
354: }
355: if (cookieValue != null) {
356: String bookmarkCookieStr = getCookieStr(cookieValue);
357: HttpServletResponse res = (HttpServletResponse) FacesContext
358: .getCurrentInstance().getExternalContext()
359: .getResponse();
360: log(Level.FINEST, "Setting Bookmark Cookie: "
361: + bookmarkCookieStr);
362: res.addHeader("Set-Cookie", bookmarkCookieStr);
363: }
364: }
365:
366: public static Map getBookmarks(String userDN) {
367: Map bookmarks = new HashMap();
368: Map bookmarkMap = getBookmarkMap();
369: if (bookmarkMap != null && !bookmarkMap.isEmpty()
370: && bookmarkMap.containsKey(userDN)) {
371: bookmarks = (Map) bookmarkMap.get(userDN);
372: }
373: log(Level.FINEST, "Currently set bookmarks=" + bookmarks);
374: return bookmarks;
375: }
376:
377: private static Map getBookmarkMap() {
378: Map bookmarks = new HashMap();
379: Map cookieMap = FacesContext.getCurrentInstance()
380: .getExternalContext().getRequestCookieMap();
381: Cookie bookmarkCookie = (Cookie) cookieMap
382: .get(BOOKMARK_COOKIE_NAME);
383: String value = null;
384: if (bookmarkCookie != null) {
385: value = bookmarkCookie.getValue();
386: }
387: if (value != null) {
388: try {
389: bookmarks = (Map) Encoder.deserialize(Encoder
390: .decodeHttp64(value), true);
391: } catch (IOException ioe) {
392: log(Level.SEVERE,
393: "Exception in PSBaseBean.getBookmarkMap()", ioe);
394: } catch (ClassNotFoundException cnfe) {
395: log(Level.SEVERE,
396: "Exception in PSBaseBean.getBookmarkMap()",
397: cnfe);
398: }
399: }
400: return bookmarks;
401: }
402:
403: private static String getCookieStr(String cookieValue) {
404: String path = FacesContext.getCurrentInstance()
405: .getExternalContext().getRequestContextPath();
406: log(Level.FINEST, "Context Path for Bookmark Cookie=" + path);
407: StringBuffer cs = new StringBuffer();
408: cs.append(BOOKMARK_COOKIE_NAME).append("=").append(cookieValue)
409: .append(";").append("Max-Age=")
410: .append(BOOKMARK_MAX_AGE).append(";").append("Path=")
411: .append(path);
412: return cs.toString();
413:
414: }
415:
416: public void setAuthCredential(JMXConnector connector, String uid) {
417: AuthCredentialBean abean = AuthCredentialBean
418: .getCurrentInstance();
419: if (abean != null) {
420: abean.setAuthCredential(connector, uid);
421: }
422: }
423:
424: public void resetAuthCredential() {
425: AuthCredentialBean abean = AuthCredentialBean
426: .getCurrentInstance();
427: if (abean != null) {
428: abean.resetAuthCredential();
429: }
430: }
431:
432: public void closeConnection() throws IOException {
433: AuthCredentialBean abean = AuthCredentialBean
434: .getCurrentInstance();
435: if (abean != null) {
436: abean.closeConnection();
437: }
438: }
439:
440: public MBeanServerConnection getMBeanServerConnection() {
441: AuthCredentialBean abean = AuthCredentialBean
442: .getCurrentInstance();
443: if (abean != null) {
444: return abean.getMBeanServerConnection();
445: }
446: return null;
447: }
448:
449: public String getUID() {
450: AuthCredentialBean abean = AuthCredentialBean
451: .getCurrentInstance();
452: if (abean != null) {
453: return abean.getUID();
454: }
455: return null;
456: }
457:
458: public Object getAttribute(ObjectName obj, String attribute) {
459: try {
460: return getMBeanServerConnection().getAttribute(obj,
461: attribute);
462: } catch (Exception e) {
463: log(
464: Level.SEVERE,
465: "PSBaseBean.getAttribute(): Failed to get mbean server attribute.",
466: e);
467: return null;
468: }
469: }
470:
471: public Set JMXQueryNames(ObjectName obj, QueryExp queryex) {
472: try {
473: return getMBeanServerConnection().queryNames(obj, queryex);
474: } catch (Exception e) {
475: log(
476: Level.SEVERE,
477: "PSBaseBean.JMXQueryNames(): Failed to query mbean names.",
478: e);
479: return null;
480: }
481: }
482:
483: public static String getLocalizedString(String rbName, String key) {
484: String i18NStr = null;
485: ResourceBundle bundle = getRBundle(rbName);
486: try {
487: if (bundle != null) {
488: i18NStr = bundle.getString(key);
489: }
490: } catch (Exception e) {
491: log(
492: Level.WARNING,
493: "PSBaseBean.getLocalizedString(): Failed to localize content",
494: e);
495: }
496:
497: if (i18NStr == null) {
498: i18NStr = "???" + key + "???";
499: }
500: return i18NStr;
501: }
502:
503: protected Map getResourceStringMap(String rbName) {
504: Map resMap = new HashMap();
505: ResourceBundle bundle = getRBundle(rbName);
506: if (bundle != null) {
507: Enumeration en = bundle.getKeys();
508: while (en.hasMoreElements()) {
509: String key = (String) en.nextElement();
510: try {
511:
512: resMap.put(key, bundle.getString(key));
513: } catch (Exception e) {
514: log(
515: Level.WARNING,
516: "PSBaseBean.getResourceStringMap(): Failed to localize content",
517: e);
518: }
519: }
520: }
521: return resMap;
522: }
523:
524: public static ResourceBundle getRBundle(String rbName) {
525: ResourceBundle rb = null;
526: try {
527: FacesContext fc = FacesContext.getCurrentInstance();
528: Locale locale = fc.getViewRoot().getLocale();
529: rb = ResourceBundle.getBundle(rbName, locale);
530: } catch (Exception e) {
531: log(
532: Level.WARNING,
533: "PSBaseBean.getRBundle(): Failed to localize content",
534: e);
535: }
536: return rb;
537: }
538:
539: /**
540: * Returns a string representation of the stack trace.
541: * Puts the exception message in the first line and the rest of the
542: * stack trace below it, each terminated by a newline char.
543: */
544: public String getStackTrace(Throwable t) {
545: StringBuffer strace = new StringBuffer();
546: StackTraceElement[] ste = t.getStackTrace();
547: strace.append(t.getMessage());
548: strace.append('\n');
549: for (int i = 0; i < ste.length; i++) {
550: strace.append(ste[i].toString());
551: strace.append('\n');
552: }
553: return strace.toString();
554: }
555: }
|