Source Code Cross Referenced for NetletConfig.java in  » Portal » Open-Portal » com » sun » portal » netlet » servlet » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Portal » Open Portal » com.sun.portal.netlet.servlet 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        package com.sun.portal.netlet.servlet;
0002:
0003:        import java.io.*;
0004:        import java.net.InetAddress;
0005:        import java.net.URLDecoder;
0006:        import java.net.URLEncoder;
0007:        import java.net.UnknownHostException;
0008:        import java.security.NoSuchAlgorithmException;
0009:        import java.security.SecureRandom;
0010:        import java.text.MessageFormat;
0011:        import java.util.ArrayList;
0012:        import java.util.Enumeration;
0013:        import java.util.HashMap;
0014:        import java.util.Hashtable;
0015:        import java.util.Iterator;
0016:        import java.util.List;
0017:        import java.util.Map;
0018:        import java.util.MissingResourceException;
0019:        import java.util.NoSuchElementException;
0020:        import java.util.ResourceBundle;
0021:        import java.util.Set;
0022:        import java.util.StringTokenizer;
0023:        import java.util.Vector;
0024:        import java.util.logging.Level;
0025:        import java.util.logging.Logger;
0026:
0027:        import javax.servlet.ServletException;
0028:        import javax.servlet.http.Cookie;
0029:        import javax.servlet.http.HttpServlet;
0030:        import javax.servlet.http.HttpServletRequest;
0031:        import javax.servlet.http.HttpServletResponse;
0032:        import javax.servlet.http.HttpUtils;
0033:
0034:        import com.iplanet.am.util.AMClientDetector;
0035:        import com.iplanet.am.util.SystemProperties;
0036:        import com.iplanet.services.cdm.Client;
0037:        import com.iplanet.services.cdm.ClientException;
0038:        import com.iplanet.sso.SSOException;
0039:        import com.iplanet.sso.SSOToken;
0040:        import com.iplanet.sso.SSOTokenEvent;
0041:        import com.iplanet.sso.SSOTokenID;
0042:        import com.iplanet.sso.SSOTokenListener;
0043:        import com.iplanet.sso.SSOTokenManager;
0044:        import com.sun.portal.log.common.PortalLogger;
0045:        import com.sun.portal.netlet.econnection.KeyConstants;
0046:        import com.sun.portal.netlet.util.NetletConstants;
0047:        import com.sun.portal.netlet.util.UrlDecoder;
0048:        import com.sun.portal.netlet.util.UserAttributes;
0049:        import com.sun.portal.util.ResourceLoader;
0050:
0051:        public class NetletConfig extends HttpServlet implements 
0052:                SSOTokenListener, NetletConstants {
0053:
0054:            private static final String HTTP_PROTOCOL = "http";
0055:
0056:            private static final String sccsID = "@(#)NetletConfig.java	1.37 01/07/16 Sun Microsystems, Inc.";
0057:
0058:            private static Logger logger = PortalLogger
0059:                    .getLogger(NetletConfig.class);
0060:
0061:            private String serverName = null;
0062:
0063:            private String serverPort = null;
0064:
0065:            private String serverProtocol = null;
0066:
0067:            private String serverDomain = null;
0068:
0069:            private String serverUrl = null;
0070:
0071:            private String JS_DOCUMENT_DOMAIN = "document.domain";
0072:
0073:            private boolean autoCloseWindow = false;
0074:
0075:            private Hashtable sessionHash = new Hashtable();
0076:
0077:            private Hashtable clientPorts = new Hashtable(); // SessID mapping to
0078:
0079:            // clientPorts
0080:
0081:            private final int STATUS_LOADING = 1;
0082:
0083:            private final int STATUS_LOADED = 2;
0084:
0085:            private final int STATUS_NOT_LOADED = 3;
0086:
0087:            private final int STATUS_UNLOADED = 4;
0088:
0089:            private final int STATUS_NOT_STARTED = 5;
0090:
0091:            // Added for bug 4432831
0092:            private SecureRandom sRandom = null;
0093:
0094:            class NetletUser {
0095:                private Hashtable netletRules = new Hashtable();
0096:
0097:                private HttpServletRequest req = null;
0098:
0099:                private HttpServletResponse res = null;
0100:
0101:                private boolean portWarn = false;
0102:
0103:                private String clientBindIP = NetletConstants.NETLET_DEFAULT_CLIENT_BIND_IP;
0104:
0105:                private boolean portwarnCheckbox = true;
0106:
0107:                private boolean keepWinMin = false;
0108:
0109:                private boolean doReauth = false;
0110:
0111:                private int defaultLoopbackPort = 8000;
0112:
0113:                private String enc = null;
0114:
0115:                private ResourceBundle bundle = null;
0116:
0117:                private ResourceBundle appletBundle = null;
0118:
0119:                private String HTMLcharsetname = null;
0120:
0121:                private SSOToken ssoToken = null;
0122:
0123:                private UserAttributes userAttrs = null;
0124:
0125:                // Pluggable Cipher Support
0126:                private Hashtable userCipherPreference = new Hashtable();
0127:
0128:                private String defaultCipher = null;
0129:
0130:                private boolean terminateAtLogout = true;
0131:
0132:                private String jsDocumentDomain = null;
0133:
0134:                // private List pluggedInAlgorithms = new ArrayList();
0135:
0136:                /**
0137:                 * FIX for 4767153 (BEA specific bug). Just a work around. Please remove
0138:                 * this method after DSAME fixes this problem.
0139:                 */
0140:                public NetletUser(HttpServletRequest httpreq)
0141:                        throws SSOException {
0142:                    req = httpreq;
0143:                    /**
0144:                     * FIX for 4767153 (BEA specific bug). Just a work around.
0145:                     */
0146:                    ssoToken = createSSOToken(req);
0147:                    if (ssoToken == null) {
0148:                        throw new SSOException(
0149:                                "NetletUser.java Can't get ssoToken");
0150:                    }
0151:                    // End - FIX for 4767153 (BEA specific bug)
0152:                    // Commented to FIX 4767153 (BEA specific bug)
0153:                    /*
0154:                     * try { ssoToken =
0155:                     * SSOTokenManager.getInstance().createSSOToken(httpreq); }
0156:                     * catch(SSOException ssoe){ throw new SSOException("NetletUser.java
0157:                     * Can't get ssoToken"); }
0158:                     */
0159:                    // End - Commented to FIX 4767153 (BEA specific bug)
0160:                    userAttrs = new UserAttributes(ssoToken);
0161:
0162:                    terminateAtLogout = userAttrs.getBoolean(
0163:                            NetletConstants.NETLET_TERMINATE_AT_LOGOUT, true);
0164:
0165:                    enc = userAttrs.getUserAttribute(
0166:                            NetletConstants.USER_PREFERRED_LOCALE,
0167:                            com.iplanet.am.util.Locale.getDefaultLocale()
0168:                                    .toString());
0169:
0170:                    HTMLcharsetname = findHTMLCharset(req);
0171:
0172:                    // logger.info("Netlet using encoding : " + enc + " charset : " +
0173:                    // HTMLcharsetname);
0174:                    Object[] params0 = { enc, "  charset : ", HTMLcharsetname };
0175:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS000", params0);
0176:
0177:                    // retrieve the javascript document.domain
0178:                    jsDocumentDomain = req.getParameter(JS_DOCUMENT_DOMAIN);
0179:
0180:                    bundle = ResourceBundle.getBundle(
0181:                            NetletConstants.NETLET_SERVLET_RES_BUNDLE,
0182:                            com.iplanet.am.util.Locale.getLocale(enc));
0183:
0184:                    appletBundle = ResourceBundle.getBundle(
0185:                            NetletConstants.NETLET_APPLET_RES_BUNDLE,
0186:                            com.iplanet.am.util.Locale.getLocale(enc));
0187:
0188:                    defaultCipher = userAttrs.getString(
0189:                            NetletConstants.NETLET_KSSL_DEFAULT_CIPHER,
0190:                            NetletConstants.NETLET_KSSL_DEFAULT_CIPHER_VALUE)
0191:                            + "|"
0192:                            + userAttrs
0193:                                    .getString(
0194:                                            NetletConstants.NETLET_JSSE_DEFAULT_CIPHER,
0195:                                            NetletConstants.NETLET_JSSE_DEFAULT_CIPHER_VALUE);
0196:
0197:                    List userCipherList = userAttrs
0198:                            .getStringList(NetletConstants.NETLET_USER_CIPHER);
0199:                    for (int x = 0; x < userCipherList.size(); x++) {
0200:                        String userCipher = (String) userCipherList.get(x);
0201:                        int index = userCipher.indexOf("|");
0202:                        if (index != -1) {
0203:                            userCipherPreference.put(userCipher.substring(0,
0204:                                    index), userCipher.substring(index + 1));
0205:                        }
0206:                    }
0207:                }
0208:
0209:                public void getUserAttributes() throws SSOException {
0210:
0211:                    portWarn = userAttrs.getBoolean(
0212:                            NetletConstants.NETLET_PORT_WARN, true);
0213:
0214:                    doReauth = userAttrs.getBoolean(
0215:                            NetletConstants.NETLET_DO_REAUTH, false);
0216:
0217:                    portwarnCheckbox = userAttrs.getBoolean(
0218:                            NetletConstants.NETLET_PORT_WARN_CB, true);
0219:
0220:                    defaultLoopbackPort = userAttrs.getInt(
0221:                            NetletConstants.NETLET_CLIENT_LOOPBACK, 8000);
0222:
0223:                    clientBindIP = userAttrs.getString(
0224:                            NetletConstants.NETLET_CLIENT_BIND_IP,
0225:                            NetletConstants.NETLET_DEFAULT_CLIENT_BIND_IP);
0226:
0227:                    parseRules(new ArrayList(userAttrs
0228:                            .getStringList(NetletConstants.NETLET_RULES)));
0229:                }
0230:
0231:                private void parseRules(ArrayList cmds) {
0232:                    StringTokenizer algoTokens = null;
0233:                    String tmpStr = null;
0234:
0235:                    for (int x = 0; x < cmds.size(); x++) {
0236:                        String rule = (String) cmds.get(x);
0237:                        boolean isExtend = rule
0238:                                .endsWith(NetletConstants.NETLET_EXTEND_SESSION);
0239:                        if (isExtend) {
0240:                            rule = rule.substring(0, rule.lastIndexOf("|"));
0241:                        }
0242:
0243:                        Rules r = new Rules();
0244:                        StringTokenizer st = new StringTokenizer(rule, "|");
0245:                        try {
0246:                            while (st.hasMoreElements()) {
0247:                                tmpStr = (String) st.nextElement();
0248:                                algoTokens = new StringTokenizer(tmpStr, "^");
0249:                                try {
0250:                                    r.name = algoTokens.nextElement()
0251:                                            .toString();
0252:                                    tmpStr = algoTokens.nextElement()
0253:                                            .toString();
0254:                                    if (tmpStr.startsWith("ALGO")) {
0255:                                        r.isAlgoUserConfigurable = true;
0256:                                        try {
0257:                                            tmpStr = algoTokens.nextElement()
0258:                                                    .toString();
0259:                                        } catch (NoSuchElementException ne) {
0260:                                            tmpStr = defaultCipher;
0261:                                        }
0262:                                    }
0263:                                    algoTokens = new StringTokenizer(tmpStr,
0264:                                            "+");
0265:                                    while (algoTokens.hasMoreElements())
0266:                                        r.algorithms.add(algoTokens
0267:                                                .nextElement());
0268:                                } catch (NoSuchElementException ne) {
0269:                                    r.name = tmpStr;
0270:                                    r.algorithms.add(defaultCipher);
0271:                                }
0272:
0273:                                r.url = (String) st.nextElement();
0274:
0275:                                if (r.url.equalsIgnoreCase("null")) {
0276:                                    r.url = "";
0277:                                }
0278:                                String tmp = (String) st.nextElement();
0279:                                if (tmp.equalsIgnoreCase("false")) {
0280:                                    r.loopback = false;
0281:                                } else if (tmp.equalsIgnoreCase("true")) {
0282:                                    r.loopback = true;
0283:                                    r.clientLoopbackPort = new String(""
0284:                                            + defaultLoopbackPort + "");
0285:                                    r.loopbackServer = serverName;
0286:                                    r.serverLoopbackPort = serverPort;
0287:                                } else {
0288:                                    StringTokenizer st1 = new StringTokenizer(
0289:                                            tmp, ":");
0290:                                    // add new loopback in as new rule too so it gets
0291:                                    // made as a rule, otherwise
0292:                                    // it won't get built (this is the simplest way to
0293:                                    // do this)
0294:
0295:                                    // Added for Bug - 4616461
0296:                                    r.loopback = true;
0297:
0298:                                    r.clientLoopbackPort = (String) st1
0299:                                            .nextElement();
0300:                                    r.loopbackServer = (String) st1
0301:                                            .nextElement();
0302:                                    r.serverLoopbackPort = (String) st1
0303:                                            .nextElement();
0304:                                    r.lport.add(r.clientLoopbackPort);
0305:                                    r.dhost.add(r.loopbackServer);
0306:                                    r.dport.add(r.serverLoopbackPort);
0307:                                    r.ruleCount++;
0308:                                }
0309:                                while (st.hasMoreElements()) {
0310:                                    r.ruleCount++;
0311:                                    r.lport.add(expandAttributes((String) st
0312:                                            .nextElement()));
0313:                                    r.dhost.add(expandAttributes((String) st
0314:                                            .nextElement()));
0315:                                    r.dport.add(expandAttributes((String) st
0316:                                            .nextElement()));
0317:                                }
0318:                                r.isExtend = isExtend;
0319:                            }
0320:                        } catch (NoSuchElementException ex) {
0321:                            // logger.severe("Error parsing entry continuing " +ex );
0322:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS001", ex);
0323:                            continue;
0324:                        } catch (NumberFormatException nfe) {
0325:                            // logger.severe("Invalid port number in the rule " + nfe);
0326:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS002", nfe);
0327:                        }
0328:                        // logger.info("parseRules(): r=" + r.toString());
0329:                        Object[] params3 = { r.toString() };
0330:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS003", params3);
0331:                        addRule(r);
0332:                    }
0333:                }
0334:
0335:                public String findHTMLCharset(HttpServletRequest req) {
0336:                    String HTMLcharset = null;
0337:                    AMClientDetector amCD = new AMClientDetector();
0338:                    String clientType = amCD.getClientType(req);
0339:                    try {
0340:                        Client clientObj = Client.getInstance(clientType);
0341:                        HTMLcharset = clientObj
0342:                                .getCharset(com.iplanet.am.util.Locale
0343:                                        .getLocale(getLocale()));
0344:                    } catch (ClientException ce) {
0345:                        // logger.severe("NetletConfig: ClientException in determining
0346:                        // charset, reading charset from properties file.");
0347:                        logger.severe("PSSRNTLT_CSPNS004");
0348:                        try {
0349:                            HTMLcharset = getBundle().getString("HTMLcharset");
0350:                        } catch (Exception mre) {
0351:                            // logger.severe("NetletConfig: Exception in reading
0352:                            // HTMLcharset from properties file, using ISO-8859-1.");
0353:                            logger.severe("PSSRNTLT_CSPNS005");
0354:                            HTMLcharset = "ISO-8859-1";
0355:                        }
0356:                    }
0357:                    return HTMLcharset;
0358:                }
0359:
0360:                // Pluggable Cipher Support
0361:                /*
0362:                 * Added for Lihue Pluggable Cipher's @ date 2/01/2002 @ added Rajesh T
0363:                 *
0364:                 * returns the algorithm as specified in the rule, @ returns default
0365:                 * cipher for backward compactability @ modified by bshankar@sun.com to
0366:                 * fix - 4729138.
0367:                 */
0368:
0369:                public String getAlgorithm(Rules r) {
0370:                    String ruleName = r.name;
0371:                    if (ruleName == null || ruleName.trim().length() == 0)
0372:                        return KeyConstants.DEFAULT_CIPHER;
0373:                    /*
0374:                     * If there is no cipher defined for a rule, use default cipher
0375:                     */
0376:                    if (r.algorithms == null || r.algorithms.size() == 0)
0377:                        return defaultCipher;
0378:                    /*
0379:                     * If the rule has only one algorithm, user has no choice.
0380:                     */
0381:                    if (r.algorithms.size() == 1)
0382:                        return (String) r.algorithms.get(0);
0383:                    Object algo = userCipherPreference.get(ruleName);
0384:                    /*
0385:                     * If the latest modification to the rule doesnot contain the cipher
0386:                     * selected by the user, return the first cipher in the list
0387:                     */
0388:                    if (algo == null || algo.equals("null")
0389:                            || !r.algorithms.contains(algo))
0390:                        return (String) r.algorithms.get(0);
0391:                    return algo.toString();
0392:                }
0393:
0394:                public String getDefaultCipher() {
0395:                    return defaultCipher;
0396:                }
0397:
0398:                public boolean isAllowed() {
0399:                    return userAttrs == null ? false : userAttrs.isAllowed();
0400:                }
0401:
0402:                public String getDefaultRedirectURL() {
0403:                    String defaultRedirectURL = userAttrs
0404:                            .getUserAttribute(NetletConstants.USER_DEFAULT_URL);
0405:                    return defaultRedirectURL;
0406:                }
0407:
0408:                public int getDefaultLBPort() {
0409:                    return defaultLoopbackPort;
0410:                }
0411:
0412:                /*
0413:                 * End return type changed
0414:                 */
0415:
0416:                public boolean keepWindowMinimized() {
0417:                    return keepWinMin;
0418:                }
0419:
0420:                public boolean getPortWarn() {
0421:                    return portWarn;
0422:                }
0423:
0424:                public boolean terminateAtLogout() {
0425:                    return terminateAtLogout;
0426:                }
0427:
0428:                public String getClientBindIP() {
0429:                    return clientBindIP;
0430:                }
0431:
0432:                public boolean getPortWarnCheckbox() {
0433:                    return portwarnCheckbox;
0434:                }
0435:
0436:                public boolean getReauth() {
0437:                    return doReauth;
0438:                }
0439:
0440:                public void addRule(Rules r) {
0441:                    if (r == null) {
0442:                        return;
0443:                    }
0444:                    netletRules.put(r.name, r);
0445:                }
0446:
0447:                public Enumeration getRules() {
0448:                    return netletRules.elements();
0449:                }
0450:
0451:                public Rules getRule(String cmd) {
0452:                    return (Rules) netletRules.get(cmd);
0453:                }
0454:
0455:                /*
0456:                 * expandAttributes looks for attribute expansion expressions in val and
0457:                 * replaces them by reading the values for that attributes from the
0458:                 * profile. Each attribute that is replaced must be a single valued
0459:                 * String attribute, i.e., it cannot be a list. If the attribute value
0460:                 * is invalid, the expandsion expression is replaced with the empty
0461:                 * string. The following types of attribute expansion expressions are
0462:                 * recognized:
0463:                 *
0464:                 * $attrname (attrname is deliminated by any non-attribute name
0465:                 * character or the end of the value) ${attrname}
0466:                 */
0467:
0468:                private String expandAttributes(String val) {
0469:                    int i = val.indexOf('$');
0470:                    if (i == -1) {
0471:                        return val;
0472:                    }
0473:
0474:                    /*
0475:                     * state values are: 0 - initial state, gathering regular characters
0476:                     * into buffer 1 - just received $, getting ready for attribute name
0477:                     * 2 - gathering non-braced attribute name 3 - gathering braced
0478:                     * attribute name
0479:                     */
0480:                    int state = 0;
0481:                    StringBuffer buf = new StringBuffer();
0482:                    StringBuffer attr = null;
0483:                    char cval[] = val.toCharArray();
0484:
0485:                    while (i < cval.length) {
0486:                        char c = cval[i++];
0487:                        switch (state) {
0488:
0489:                        case 0:
0490:                            if (c == '$') {
0491:                                state = 1;
0492:                            } else {
0493:                                buf.append(c);
0494:                            }
0495:                            break;
0496:
0497:                        case 1:
0498:                            if ((c >= 'a' && c <= 'z')
0499:                                    || (c >= 'A' && c <= 'Z')) {
0500:                                attr = new StringBuffer();
0501:                                attr.append(c);
0502:                                state = 2;
0503:                            } else if (c == '{') {
0504:                                attr = new StringBuffer();
0505:                                state = 3;
0506:                            } else {
0507:                                // print error (missing attribute name after $),
0508:                                // discard $
0509:                                // logger.info("NetletConfig: missing attribute name
0510:                                // after $:" + val);
0511:                                Object[] params6 = { val };
0512:                                logger.log(Level.INFO, "PSSRNTLT_CSPNS006",
0513:                                        params6);
0514:                                state = 0;
0515:                            }
0516:                            break;
0517:
0518:                        case 2:
0519:                            if ((c >= 'a' && c <= 'z')
0520:                                    || (c >= 'A' && c <= 'Z')
0521:                                    || (c >= '0' && c <= '9') || (c == '-')) {
0522:                                attr.append(c);
0523:                            } else {
0524:                                buf.append(getAttr(attr.toString()));
0525:                                buf.append(c);
0526:                                state = 0;
0527:                            }
0528:                            break;
0529:
0530:                        case 3:
0531:                            if ((c >= 'a' && c <= 'z')
0532:                                    || (c >= 'A' && c <= 'Z')
0533:                                    || (c >= '0' && c <= '9') || (c == '-')) {
0534:                                attr.append(c);
0535:                            } else if (c == '}') {
0536:                                buf.append(getAttr(attr.toString()));
0537:                                state = 0;
0538:                            } else {
0539:                                // print error (missing close brace), discard
0540:                                // partial attribute name
0541:                                // logger.info("NetletConfig: missing close brace:"
0542:                                // + val);
0543:                                Object[] params7 = { val };
0544:                                logger.log(Level.INFO, "PSSRNTLT_CSPNS007",
0545:                                        params7);
0546:                                state = 0;
0547:                            }
0548:                            break;
0549:                        }
0550:                    }
0551:
0552:                    switch (state) {
0553:                    case 1:
0554:                        // print error (missing attribute name after $)
0555:                        // logger.info("NetletConfig: missing attribute name after
0556:                        // $:" + val);
0557:                        Object[] params8 = { val };
0558:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS008", params8);
0559:                        break;
0560:
0561:                    case 2:
0562:                        buf.append(getAttr(attr.toString()));
0563:                        break;
0564:
0565:                    case 3:
0566:                        // print error (missing close brace)
0567:                        // logger.info("NetletConfig: missing close brace:" + val);
0568:                        Object[] params9 = { val };
0569:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS009", params9);
0570:                        break;
0571:                    }
0572:
0573:                    String rval = buf.toString();
0574:                    // logger.info("expanded value from '" + val + "' to '" + rval +
0575:                    // "'");
0576:                    Object[] params10 = { val, "' to '", rval, "'" };
0577:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS010", params10);
0578:                    return rval;
0579:                }
0580:
0581:                private String getAttr(String aname) {
0582:                    return userAttrs.getUserAttribute(aname);
0583:                }
0584:
0585:                public void setReq(HttpServletRequest r) {
0586:                    req = r;
0587:                }
0588:
0589:                public HttpServletRequest getReq() {
0590:                    return req;
0591:                }
0592:
0593:                public void setRes(HttpServletResponse r) {
0594:                    res = r;
0595:                }
0596:
0597:                public HttpServletResponse getRes() {
0598:                    return res;
0599:                }
0600:
0601:                public String getLocale() {
0602:                    return enc;
0603:                }
0604:
0605:                public ResourceBundle getBundle() {
0606:                    return bundle;
0607:                }
0608:
0609:                public ResourceBundle getAppletBundle() {
0610:                    return appletBundle;
0611:                }
0612:
0613:                public String getHTMLcharsetname() {
0614:                    return HTMLcharsetname;
0615:                }
0616:
0617:                public SSOToken getSSOToken() {
0618:                    return ssoToken;
0619:                }
0620:
0621:                public SSOTokenID getSSOTokenID() {
0622:                    return ssoToken.getTokenID();
0623:                }
0624:
0625:                public UserAttributes getNetletUserAttributes() {
0626:                    return userAttrs;
0627:                }
0628:
0629:                public void setNetletUserAttributes(UserAttributes attrs) {
0630:                    userAttrs = attrs;
0631:                }
0632:
0633:                public String getClientHostName() throws SSOException {
0634:                    return ssoToken.getHostName();
0635:                }
0636:
0637:                public String getJsDocumentDomain() {
0638:                    return jsDocumentDomain;
0639:                }
0640:
0641:                public String getJsDocumentDomainInPage() {
0642:                    String rval = "";
0643:
0644:                    if (jsDocumentDomain != null) {
0645:                        rval = JS_DOCUMENT_DOMAIN + "=\"" + jsDocumentDomain
0646:                                + "\";";
0647:                    } else {
0648:                        rval = JS_DOCUMENT_DOMAIN + "=document.domain;";
0649:                    }
0650:
0651:                    return rval;
0652:                }
0653:
0654:                public String getJsDocumentDomainInUrl() {
0655:                    String rval = "";
0656:
0657:                    if (jsDocumentDomain != null) {
0658:                        rval = "&" + JS_DOCUMENT_DOMAIN + "="
0659:                                + jsDocumentDomain;
0660:                    }
0661:
0662:                    return rval;
0663:                }
0664:
0665:                public boolean inPrivilegeList(String privilege, String value,
0666:                        boolean ignoreCase, boolean isHost) {
0667:                    if (value == null) {
0668:                        return false;
0669:                    }
0670:                    boolean stringMatch = false;
0671:                    ArrayList privilegeList = new ArrayList(userAttrs
0672:                            .getStringList(privilege));
0673:                    if (privilegeList != null) {
0674:                        for (int i = 0; i < privilegeList.size(); i++) {
0675:                            String privilegeString = (String) privilegeList
0676:                                    .get(i);
0677:
0678:                            if (privilegeString.equals("*"))
0679:                                return true;
0680:                            if (isHost && !isIPAddress(privilegeString)
0681:                                    && privilegeString.indexOf(".") == -1) {
0682:                                // Bug# 4956878 :: Remove the validation
0683:                                // && isValidHost(privilegeString)) {
0684:                                if (serverDomain != null) {
0685:                                    privilegeString += ".";
0686:                                    privilegeString += serverDomain;
0687:                                }
0688:                            }
0689:                            if (ignoreCase) {
0690:                                stringMatch = wildcardMatch(
0691:                                        value.toLowerCase(), privilegeString
0692:                                                .toLowerCase());
0693:                            } else {
0694:                                stringMatch = wildcardMatch(value,
0695:                                        privilegeString);
0696:                            }
0697:
0698:                            // logger.info("NetletConfig.inPrivilegeList() : " +
0699:                            // "NetletConfig.inPrivilegeList() : " + " privilege : " +
0700:                            // privilege + " value : " + value + " privilegeString : " +
0701:                            // privilegeString + " ignoreCase : " + ignoreCase + "
0702:                            // isHost : "+ isHost + " result : " + stringMatch
0703:                            Object[] params = { privilege, value,
0704:                                    privilegeString, new Boolean(ignoreCase),
0705:                                    new Boolean(isHost),
0706:                                    new Boolean(stringMatch) };
0707:                            logger.log(Level.INFO, "PSSRNTLT_CSPNS011", params);
0708:
0709:                            if (stringMatch) {
0710:                                return true;
0711:                            }
0712:                        }
0713:                    }
0714:                    return false;
0715:                }
0716:
0717:                private boolean wildcardMatch(String str1, String str2) {
0718:                    int beginIndex1 = 0;
0719:                    int endIndex1 = 0;
0720:                    int beginIndex2 = 0;
0721:                    int endIndex2 = 0;
0722:                    int strlen1 = str1.length();
0723:                    int strlen2 = str2.length();
0724:                    String substr = null;
0725:
0726:                    // if one of the string is null, consider it no match.
0727:                    if ((str1 == null) || (str2 == null))
0728:                        return (false);
0729:
0730:                    if ((endIndex2 = str2.indexOf('*', beginIndex2)) != -1) {
0731:                        // get the substring prior to the first '*'
0732:                        substr = str2.substring(beginIndex2, endIndex2);
0733:
0734:                        // check if the first char in str2 is '*', i.e. the substring is
0735:                        // null
0736:                        if (endIndex2 > beginIndex2) {
0737:                            // str1 contains the substring too? if not, no match
0738:                            if ((beginIndex1 = str1
0739:                                    .indexOf(substr, beginIndex1)) == -1)
0740:                                return (false);
0741:                            // if it is not a SUFFIX match, then the prefixes should be
0742:                            // equal
0743:                            if ((beginIndex1 != beginIndex2))
0744:                                return (false);
0745:                        }
0746:                        // move the pointer to next char after the substring already
0747:                        // matched
0748:                        beginIndex1 = beginIndex1 + (endIndex2 - beginIndex2);
0749:                        if (endIndex2 >= strlen2 - 1)
0750:                            return (true);
0751:                        beginIndex2 = endIndex2 + 1;
0752:                    } else // str2 doesn't contain wildcard '*'
0753:                    {
0754:                        if ((beginIndex1 = str1.indexOf(str2)) == -1)
0755:                            return (false);
0756:                        if ((strlen1 == strlen2))
0757:                            return (true);
0758:                        return (false);
0759:                    }
0760:
0761:                    // There are more than '*'s in str2, repeat what we have done
0762:                    while ((endIndex2 = str2.indexOf('*', beginIndex2)) != -1) {
0763:                        substr = str2.substring(beginIndex2, endIndex2);
0764:                        if (endIndex2 > beginIndex2)
0765:                            if ((beginIndex1 = str1
0766:                                    .indexOf(substr, beginIndex1)) == -1)
0767:                                return (false);
0768:                        beginIndex1 = beginIndex1 + (endIndex2 - beginIndex2);
0769:                        if (endIndex2 >= strlen2 - 1)
0770:                            return (true);
0771:                        beginIndex2 = endIndex2 + 1;
0772:                    }
0773:                    // The substring after the last '*'
0774:                    substr = str2.substring(beginIndex2, strlen2);
0775:
0776:                    if ((endIndex1 = str1.lastIndexOf(substr, strlen1 - 1)) == -1)
0777:                        return (false);
0778:
0779:                    if (beginIndex1 > endIndex1)
0780:                        return (false);
0781:
0782:                    beginIndex1 = endIndex1;
0783:                    if (((strlen1 - beginIndex1) == (strlen2 - beginIndex2)))
0784:                        return (true);
0785:                    return (false);
0786:                }
0787:
0788:                public String getEncryptionType() {
0789:                    HttpServletRequest req = getReq();
0790:                    String psNetletHeader = req
0791:                            .getHeader(NetletConstants.NETLET_HEADER);
0792:                    if (psNetletHeader != null) {
0793:                        StringTokenizer tokenizer = new StringTokenizer(
0794:                                psNetletHeader, ";");
0795:                        if (tokenizer.countTokens() == 2) {
0796:                            String token = tokenizer.nextToken();
0797:                            token = tokenizer.nextToken().trim();
0798:                            if ("encryption=ssl".equals(token)) {
0799:                                return "SSL";
0800:                            }
0801:                        }
0802:                    }
0803:                    return "PLAIN";
0804:                }
0805:
0806:            }
0807:
0808:            // ///////////////////////////
0809:
0810:            public NetletConfig() {
0811:                // Added for bug 4432831
0812:                try {
0813:                    sRandom = SecureRandom.getInstance("SHA1PRNG");
0814:                    // byte seed[] = sRandom.generateSeed(20);
0815:                    byte seed[] = sRandom.generateSeed(32);
0816:                    sRandom.setSeed(seed);
0817:                } catch (NoSuchAlgorithmException ne) {
0818:                    sRandom = new SecureRandom();
0819:                }
0820:            }
0821:
0822:            private SSOToken createSSOToken(HttpServletRequest httpreq) {
0823:                SSOToken token = null;
0824:                String cookieName = SystemProperties.get(
0825:                        "com.iplanet.am.cookie.name", "iPlanetDirectoryPro");
0826:                Cookie[] cks = httpreq.getCookies();
0827:
0828:                if (cks != null) {
0829:                    for (int i = 0; i < cks.length; i++) {
0830:                        String cName = cks[i].getName();
0831:                        if (cName != null && cName.equals(cookieName)) {
0832:                            String sessID = cks[i].getValue();
0833:                            try {
0834:                                token = SSOTokenManager.getInstance()
0835:                                        .createSSOToken(sessID);
0836:                            } catch (SSOException ssoe) {
0837:                                try {
0838:                                    token = SSOTokenManager.getInstance()
0839:                                            .createSSOToken(
0840:                                                    URLDecoder.decode(sessID));
0841:                                } catch (SSOException ssoe2) {
0842:                                }
0843:                            }
0844:                            break;
0845:                        }
0846:                    }
0847:                }
0848:                return token;
0849:            }
0850:
0851:            /*
0852:             * Return the client ID in the Session author :
0853:             * Bhavanishankara.sapaliga@sun.com
0854:             */
0855:            public String getClientID(SSOToken ssoTok) {
0856:                if (ssoTok != null) {
0857:                    try {
0858:                        String dn = ssoTok.getPrincipal().getName();
0859:                        String clientId = dn.substring((dn.indexOf("=") + 1),
0860:                                dn.indexOf(","));
0861:                        return clientId;
0862:                    } catch (Exception ex) {
0863:                        // logger.severe("NetletConfig: Unable to get client ID -> " +
0864:                        // ex);
0865:                        logger.log(Level.SEVERE, "PSSRNTLT_CSPNS012", ex);
0866:                    }
0867:                }
0868:                return "";
0869:            }
0870:
0871:            private String getCommand(HttpServletRequest req) {
0872:                String command = req.getParameter("func");
0873:                try {
0874:                    String queryString = req.getQueryString();
0875:                    int funcStartIndex = queryString.indexOf("func=");
0876:                    if (funcStartIndex == -1) {
0877:                        return UrlDecoder.decode(command);
0878:                    }
0879:                    queryString = queryString.substring(funcStartIndex + 5);
0880:                    int funcEndIndex = queryString.indexOf("&");
0881:                    queryString = (funcEndIndex == -1) ? queryString
0882:                            : queryString.substring(0, funcEndIndex);
0883:                    return UrlDecoder.decode(queryString);
0884:                } catch (Exception ex) {
0885:                    // logger.severe("NetletConfig: Exception in getting the command ->
0886:                    // " + ex);
0887:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS013", ex);
0888:                }
0889:                return UrlDecoder.decode(command);
0890:            }
0891:
0892:            private boolean isNetletAvailable(NetletUser user) {
0893:                HttpServletRequest req = user.getReq();
0894:                HttpServletResponse res = user.getRes();
0895:                String psNetletHeader = req
0896:                        .getHeader(NetletConstants.NETLET_HEADER);
0897:                if (psNetletHeader == null) {
0898:                    // logger.severe("Netlet can not be accessed in open portal mode.");
0899:                    logger.severe("PSSRNTLT_CSPNS014");
0900:                    redirectToPage(res, "noGateway", null, user.getLocale(),
0901:                            user.getHTMLcharsetname());
0902:                    return false;
0903:                }
0904:                StringTokenizer tokenizer = new StringTokenizer(psNetletHeader,
0905:                        ";");
0906:                if (tokenizer.hasMoreTokens()) {
0907:                    String token = tokenizer.nextToken().trim();
0908:                    if (!"enabled=true".equals(token)) {
0909:                        // logger.severe("Gateway does not allow Netlet connections.");
0910:                        logger.severe("PSSRNTLT_CSPNS015");
0911:                        redirectToPage(res, "netletDisabled", null, user
0912:                                .getLocale(), user.getHTMLcharsetname());
0913:                        return false;
0914:                    }
0915:                }
0916:                return true;
0917:            }
0918:
0919:            private void doGetPost(HttpServletRequest req,
0920:                    HttpServletResponse res) throws ServletException,
0921:                    IOException, FileNotFoundException {
0922:
0923:                /*
0924:                 * Added for Bug# 4654663 Read the host, port, protocol information from
0925:                 * the HttpRequest
0926:                 */
0927:
0928:                if ((serverName == null) || (serverPort == null)
0929:                        || (serverProtocol == null)) {
0930:                    serverName = req.getServerName();
0931:                    if (serverName != null && serverName.trim().length() != 0
0932:                            && serverName.indexOf(".") != -1) {
0933:                        serverDomain = serverName.substring(serverName
0934:                                .indexOf(".") + 1);
0935:                    }
0936:                    serverProtocol = req.getScheme();
0937:                    int sPort = req.getServerPort();
0938:                    serverPort = "" + sPort;
0939:                    serverUrl = serverProtocol + "://" + serverName + ":"
0940:                            + serverPort;
0941:                }
0942:                String command = getCommand(req);
0943:                if (command == null || command.trim().length() == 0) {
0944:                    // logger.severe("Error no function specified");
0945:                    logger.severe("PSSRNTLT_CSPNS016");
0946:                    return;
0947:                }
0948:                try {
0949:
0950:                    SSOToken ssoTok = createSSOToken(req);
0951:                    if (!((SSOTokenManager.getInstance()).isValidToken(ssoTok))) {
0952:                        // logger.severe("Invalid SSOToken");
0953:                        logger.severe("PSSRNTLT_CSPNS017");
0954:                        redirectToPage(res, "invalidsession", null, null, null);
0955:                        return;
0956:                    }
0957:
0958:                    String sid = new String(ssoTok.getTokenID().toString());
0959:                    if (command.equalsIgnoreCase("makeJnlpPage")) {
0960:                        if (getStatus(sid) == STATUS_LOADED
0961:                                || getStatus(sid) == STATUS_NOT_STARTED) {
0962:                            // logger.info("SRA Client already loaded for " +
0963:                            // getClientID(ssoTok));
0964:                            Object[] params18 = { getClientID(ssoTok) };
0965:                            logger.log(Level.INFO, "PSSRNTLT_CSPNS018",
0966:                                    params18);
0967:                            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
0968:                            return;
0969:                        }
0970:                        setStatus(sid, STATUS_LOADING);
0971:
0972:                        String startNetlet = req.getParameter("startNetlet");
0973:                        // logger.info("req param startNetlet" + startNetlet);
0974:                        Object[] params19 = { startNetlet };
0975:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS019", params19);
0976:
0977:                        NetletUser nu = null;
0978:                        if (startNetlet != null
0979:                                && startNetlet.equalsIgnoreCase("true")) {
0980:                            nu = new NetletUser(req);
0981:                            nu.setRes(res);
0982:                            /**
0983:                             * Check whether the request is via the Gateway and whether
0984:                             * the netlet is enabled.
0985:                             */
0986:                            if (!isNetletAvailable(nu)) {
0987:                                return;
0988:                            }
0989:                            if (!nu.isAllowed()) {
0990:                                redirectToPage(res, "noprivilege", null, nu
0991:                                        .getLocale(), nu.getHTMLcharsetname());
0992:                                return;
0993:                            }
0994:                            nu.getUserAttributes();
0995:                        }
0996:
0997:                        makeJnlpPage(req, res, nu, ssoTok);
0998:                        return;
0999:                    }
1000:
1001:                    //
1002:                    // create thread-specific data container
1003:                    //
1004:                    NetletUser nu = null;
1005:
1006:                    nu = new NetletUser(req);
1007:                    nu.setRes(res);
1008:
1009:                    /**
1010:                     * Check whether the request is via the Gateway and whether the
1011:                     * netlet is enabled.
1012:                     */
1013:                    if (!isNetletAvailable(nu)) {
1014:                        return;
1015:                    }
1016:
1017:                    if (!nu.isAllowed()) {
1018:                        redirectToPage(res, "noprivilege", null,
1019:                                nu.getLocale(), nu.getHTMLcharsetname());
1020:                        return;
1021:                    }
1022:
1023:                    // logger.info("Command -> " + command);
1024:                    Object[] params20 = { command };
1025:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS020", params20);
1026:
1027:                    if (command.equals("makepage") || command.equals("load")) {
1028:                        if (getStatus(sid) == STATUS_LOADED
1029:                                || getStatus(sid) == STATUS_NOT_STARTED) {
1030:                            // logger.info("Netlet already loaded for " +
1031:                            // getClientID(nu.getSSOToken()));
1032:                            Object[] params21 = { getClientID(nu.getSSOToken()) };
1033:                            logger.log(Level.INFO, "PSSRNTLT_CSPNS021",
1034:                                    params21);
1035:                            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
1036:                            return;
1037:                        }
1038:                        setStatus(sid, STATUS_LOADING);
1039:                        makeNetletPage(nu);
1040:                        // makeNetletFrame
1041:                    } else if (command.equals("makeNetletFrame")) {
1042:                        nu.getUserAttributes();
1043:                        printRules(nu);
1044:                        makeNetletFrame(nu);
1045:
1046:                        // makeInfoFrame
1047:                    } else if (command.equals("makeInfoFrame")) {
1048:                        makeInfoFrame(nu);
1049:
1050:                        // setLoaded
1051:                    } else if (command.equals("makeDetectFrame")) {
1052:                        makeDetectNetletFrame(nu);
1053:
1054:                    } else if (command.equals("setJWSLoaded")) {
1055:                        setStatus(sid, STATUS_LOADED);
1056:                        res.setStatus(HttpServletResponse.SC_OK);
1057:                        readClientPorts(nu);
1058:                        readClientListenPort(nu);
1059:                        try {
1060:                            ssoTok.setProperty("ClientStatus", "JWS_LOADED");
1061:                        } catch (SSOException ex) {
1062:                            // logger.severe("Error setting session " + ex);
1063:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS022", ex);
1064:                        }
1065:                        // setLoading
1066:                    } else if (command.equals("setLoaded")) {
1067:                        setStatus(sid, STATUS_LOADED);
1068:                        res.setStatus(HttpServletResponse.SC_OK);
1069:                        readClientPorts(nu);
1070:                        try {
1071:                            nu.getSSOToken().setProperty("ClientStatus",
1072:                                    "APPLET_LOADED");
1073:                        } catch (SSOException ex) {
1074:                            // logger.severe("Error setting session " + ex);
1075:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS023", ex);
1076:                        }
1077:                        // setLoading
1078:                    } else if (command.equals("setLoading")) {
1079:                        setStatus(sid, STATUS_LOADING);
1080:                        res.setStatus(HttpServletResponse.SC_OK);
1081:
1082:                        // isLoaded
1083:                    } else if (command.equals("isLoaded")) {
1084:                        if (getStatus(sid) == STATUS_LOADED
1085:                                || getStatus(sid) == STATUS_LOADING) {
1086:                            res.setStatus(HttpServletResponse.SC_OK);
1087:                        } else {
1088:                            res.setStatus(HttpServletResponse.SC_NO_CONTENT);
1089:                        }
1090:                        // stopped
1091:                    } else if (command.equals("stopped")) {
1092:                        setStatus(sid, STATUS_NOT_STARTED);
1093:                        res.setStatus(HttpServletResponse.SC_OK);
1094:                        // unload
1095:                    } else if (command.equals("unload")) {
1096:                        setStatus(sid, STATUS_UNLOADED);
1097:                        res.sendRedirect(nu.getDefaultRedirectURL());
1098:                        removeClientPort(nu.getSSOTokenID().toString());
1099:                        try {
1100:                            nu.getSSOToken().setProperty("ClientStatus",
1101:                                    "UNLOADED");
1102:                        } catch (SSOException ex) {
1103:                            // logger.severe("Error setting session " + ex);
1104:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS024", ex);
1105:                        }
1106:                        // loadResources
1107:                    } else if (command.equals("loadNetletArgs")) {
1108:                        setStatus(sid, STATUS_LOADING);
1109:                        outputNetletArgs(nu);
1110:                    } else if (command.equals("loadResources")) {
1111:                        setStatus(sid, STATUS_LOADING);
1112:                        outputResources(nu);
1113:
1114:                        // parsePacFile
1115:                    } else if (command.equals("parsePacFile")) {
1116:                        parsePacFile(nu);
1117:                    } else if (command.equals("storeProxySettings")) {
1118:                        storeProxySettings(nu);
1119:                    } else if (command.equals("doReauth")) {
1120:                        doReauth(nu);
1121:                    } else {
1122:                        //
1123:                        // check to see if servlet is loaded yet
1124:                        //
1125:                        if (getStatus(sid) == STATUS_UNLOADED) {
1126:                            String agent = req.getHeader("user-agent");
1127:                            if (agent.indexOf("Mac_PowerPC") != -1
1128:                                    && agent.indexOf("MSIE") != -1) {
1129:                                makeErrorMsg(nu, "macLoadErr");
1130:                                // reset status
1131:                                setStatus(sid, STATUS_NOT_LOADED);
1132:                            } else {
1133:                                makeErrorMsg(nu, "nc2");
1134:                            }
1135:                            return;
1136:                        } else if (getStatus(sid) != STATUS_LOADED) {
1137:                            // if netlet is stopped, send msg to jws client listener.
1138:                            if (getStatus(sid) == STATUS_NOT_STARTED) {
1139:                                if (redirectToClientListener(nu, req)) {
1140:                                    return;
1141:                                }
1142:                            }
1143:                            makeLoadingPage(nu, req);
1144:                            return;
1145:                        }
1146:                        nu.getUserAttributes();
1147:                        printRules(nu);
1148:
1149:                        if (!openDynamic(nu, command)) {
1150:                            // logger.severe("Error processsing dynamic rule for " +
1151:                            // command);
1152:                            Object[] params25 = { command };
1153:                            logger.log(Level.SEVERE, "PSSRNTLT_CSPNS025",
1154:                                    params25);
1155:                        }
1156:                    }
1157:                } catch (SSOException ssoe) {
1158:                    // logger.log(Level.SEVERE, "Error in NetletConfig - doGetPost() ",
1159:                    // ssoe);
1160:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS026");
1161:                    redirectToPage(res, "invalidsession", null, null, null);
1162:                    return;
1163:                } catch (MissingResourceException ex) {
1164:                    // logger.log(Level.SEVERE, "Error in NetletConfig - doGetPost() ",
1165:                    // ex);
1166:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS027");
1167:                    return;
1168:                }
1169:            }
1170:
1171:            private void addClientPort(String sessId, Hashtable cps) {
1172:                clientPorts.put(sessId, cps);
1173:            }
1174:
1175:            private void removeClientPort(String sessId) {
1176:                clientPorts.remove(sessId);
1177:            }
1178:
1179:            private void readClientListenPort(NetletUser nu) {
1180:                HttpServletRequest req = nu.getReq();
1181:                String jwsListenURL = req.getParameter("jwsListenURL");
1182:                // logger.info("jwsListenURL " + jwsListenURL);
1183:                Object[] params28 = { jwsListenURL };
1184:                logger.log(Level.INFO, "PSSRNTLT_CSPNS028", params28);
1185:                if (jwsListenURL != null && jwsListenURL.trim().length() > 0) {
1186:                    try {
1187:                        nu.getSSOToken().setProperty("jwsListenURL",
1188:                                jwsListenURL);
1189:                    } catch (SSOException e) {
1190:
1191:                    }
1192:                }
1193:            }
1194:
1195:            private void readClientPorts(NetletUser nu) {
1196:                HttpServletRequest req = nu.getReq();
1197:                String cps = req.getParameter("clientPorts");
1198:                String contentType = req.getContentType();
1199:                if (contentType != null
1200:                        && contentType.indexOf("multipart/form-data") != -1) {
1201:                    cps = extractParameter(req, "clientPorts");
1202:                }
1203:                addClientPort(nu.getSSOTokenID().toString(),
1204:                        unformatClientPorts(cps));
1205:                // logger.info("Client ports for " + getClientID(nu.getSSOToken()) + " :
1206:                // " + clientPorts);
1207:                Object[] params29 = { getClientID(nu.getSSOToken()), " : ",
1208:                        clientPorts };
1209:                logger.log(Level.INFO, "PSSRNTLT_CSPNS029", params29);
1210:            }
1211:
1212:            private Hashtable unformatClientPorts(String str) {
1213:
1214:                // str format is
1215:                // "Telnet->30000:27832,30021:24894|FTP->30021:2343|IMAP->10025:12386,10143:38453"
1216:                // unformat this and create a Hashtable with Rulename as key.
1217:
1218:                Hashtable clientPorts = new Hashtable();
1219:
1220:                StringTokenizer rules = new StringTokenizer(str, "|");
1221:
1222:                while (rules.hasMoreTokens()) {
1223:                    String rule = rules.nextToken().trim();
1224:                    Vector v = new Vector();
1225:
1226:                    StringTokenizer nameAndPorts = new StringTokenizer(rule,
1227:                            "->");
1228:                    String ruleName = nameAndPorts.nextToken().trim();
1229:                    String portList = nameAndPorts.nextToken().trim();
1230:
1231:                    StringTokenizer ports = new StringTokenizer(portList, ",");
1232:
1233:                    while (ports.hasMoreTokens()) {
1234:                        String port = ports.nextToken();
1235:                        v.addElement(port);
1236:                    }
1237:                    clientPorts.put(ruleName, v);
1238:                }
1239:                return clientPorts;
1240:            }
1241:
1242:            private String getClientPort(String sessId, String ruleName,
1243:                    String clientPortInRule) {
1244:                String clientPort = null;
1245:                Hashtable nameAndPort = (Hashtable) clientPorts.get(sessId);
1246:                Vector ports = (Vector) nameAndPort.get(ruleName);
1247:                Enumeration enumeration = ports.elements();
1248:                while (enumeration.hasMoreElements()) {
1249:                    String elem = (String) enumeration.nextElement();
1250:                    StringTokenizer st = new StringTokenizer(elem, ":");
1251:                    String cPort = null;
1252:                    if (st.hasMoreElements()) {
1253:                        cPort = (String) st.nextElement();
1254:                        if (cPort.equals(clientPortInRule)
1255:                                && st.hasMoreElements()) {
1256:                            clientPort = (String) st.nextElement();
1257:                            break;
1258:                        }
1259:                    }
1260:                }
1261:                // logger.info("Rule name -> " + ruleName + ", Administrator configured
1262:                // client port -> " + clientPortInRule + ", Actual client port -> " +
1263:                // clientPort);
1264:                Object[] params30 = { ruleName,
1265:                        ", Administrator configured client port -> ",
1266:                        clientPortInRule, ", Actual client port -> ",
1267:                        clientPort };
1268:                logger.log(Level.INFO, "PSSRNTLT_CSPNS030", params30);
1269:                return clientPort;
1270:            }
1271:
1272:            private void addLoopbackRule(NetletUser u) {
1273:
1274:                Rules lb = new Rules();
1275:
1276:                lb.name = "loopback";
1277:                lb.url = "";
1278:
1279:                lb.lport = new Vector();
1280:                lb.lport.add(new String("" + u.getDefaultLBPort()));
1281:
1282:                lb.dport = new Vector();
1283:                lb.dport.add(serverPort);
1284:
1285:                lb.dhost = new Vector();
1286:                lb.dhost.add(serverName);
1287:
1288:                u.addRule(lb);
1289:            }
1290:
1291:            void makeJnlpPage(HttpServletRequest req, HttpServletResponse res,
1292:                    NetletUser nu, SSOToken ssoTok) throws ServletException,
1293:                    IOException, SSOException {
1294:
1295:                res.setContentType("application/x-java-jnlp-file");
1296:
1297:                // fix for bug # 6333648
1298:                //        String filePath = ResourceLoader.getInstance(System.getProperties()).
1299:                //                getProperties("PSConfig.properties").getProperty("ps.config.location");
1300:                //        filePath = filePath + File.separator+"netlet"+File.separator + "sraClient.jnlp";
1301:                String filePath = ResourceLoader.getInstance(
1302:                        System.getProperties()).getProperties(
1303:                        "PSConfig.properties").getProperty(
1304:                        "ps.product.location")
1305:                        + File.separator
1306:                        + "web-src"
1307:                        + File.separator
1308:                        + "WEB-INF"
1309:                        + File.separator
1310:                        + "netlet"
1311:                        + File.separator + "sraClient.jnlp";
1312:                // logger.info("jnlp filePath " + filePath);
1313:                Object[] params31 = { filePath };
1314:                logger.log(Level.INFO, "PSSRNTLT_CSPNS031", params31);
1315:                String page = createPage(req, res, nu, readTemplate(filePath),
1316:                        ssoTok);
1317:
1318:                // logger.info("makeJnlpPage page " + page);
1319:                Object[] params32 = { page };
1320:                logger.log(Level.INFO, "PSSRNTLT_CSPNS032", params32);
1321:                res.setContentLength(page.length());
1322:
1323:                PrintWriter out = res.getWriter();
1324:                out.print(page);
1325:                out.flush();
1326:                out.close();
1327:
1328:                res.flushBuffer();
1329:            }
1330:
1331:            private String readTemplate(String file) {
1332:                StringBuffer response = new StringBuffer(200);
1333:                try {
1334:                    FileReader fReader = new FileReader(file);
1335:                    BufferedReader bReader = new BufferedReader(fReader);
1336:                    for (;;) {
1337:                        String line = bReader.readLine();
1338:                        if (line == null) {
1339:                            break;
1340:                        }
1341:                        StringBuffer newLine = new StringBuffer(line);
1342:                        response.append(newLine);
1343:                        response.append("\n");
1344:                    }
1345:                } catch (IOException e) {
1346:                    // logger.severe("readTemplate Exception: " + e);
1347:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS033", e);
1348:                }
1349:                return response.toString();
1350:            }
1351:
1352:            private String createPage(HttpServletRequest req,
1353:                    HttpServletResponse res, NetletUser nu, String tmpl,
1354:                    SSOToken ssoTok) throws SSOException {
1355:                String gwUrl = req.getHeader("ps-gw-url");
1356:                StringBuffer newLine = new StringBuffer(tmpl);
1357:                String dynamicUrl = req.getContextPath();
1358:                String line = tmpl;
1359:                int begin = 0;
1360:                int end = 0;
1361:
1362:                for (;;) {
1363:
1364:                    line = newLine.toString();
1365:
1366:                    begin = line.indexOf("###");
1367:                    if (begin == -1) {
1368:                        break;
1369:                    }
1370:
1371:                    end = line.indexOf("###", begin + 3);
1372:                    if (end == -1) {
1373:                        break;
1374:                    }
1375:                    end = end + 3;
1376:
1377:                    String tag = newLine.substring(begin, end);
1378:                    String replace = new String();
1379:
1380:                    if (tag.equals("###CODEBASE###")) {
1381:
1382:                        String codebase = gwUrl + "/" + serverUrl + dynamicUrl
1383:                                + "/netlet";
1384:                        // logger.info("jnlp codebase" + codebase);
1385:                        Object[] params34 = { codebase };
1386:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS034", params34);
1387:                        replace = codebase;
1388:                    } else if (tag.equals("###PROPERTIES###")) {
1389:                        replace = getProperties(req);
1390:                    } else if (tag.equals("###ARGUMENTS###")) {
1391:                        replace = getJnlpArgs(req, res, nu, ssoTok);
1392:                    } else {
1393:                        replace = "UNKNOWN";
1394:                    }
1395:
1396:                    newLine = newLine.replace(begin, end, replace);
1397:
1398:                }
1399:                return newLine.toString();
1400:            }
1401:
1402:            private String getProperties(HttpServletRequest req) {
1403:                StringBuffer props = new StringBuffer(100);
1404:                // props.append(" <property name=").append("").append("
1405:                // value=").append("").append("/>\n");
1406:
1407:                return props.toString();
1408:            }
1409:
1410:            private String getJnlpArgs(HttpServletRequest req,
1411:                    HttpServletResponse res, NetletUser nu, SSOToken ssoTok) {
1412:                StringBuffer args = new StringBuffer(1000);
1413:                args.append(getCommonArguments(req, ssoTok));
1414:
1415:                if (nu != null) {
1416:                    args.append("<argument>").append("startNetlet").append(
1417:                            "</argument>").append("\n").append("<argument>")
1418:                            .append("true").append("</argument>").append("\n");
1419:                    args.append(getNetletArguments(nu));
1420:                }
1421:
1422:                String startProxylet = req.getParameter("startProxylet");
1423:                // logger.info("req param startProxylet " + startProxylet);
1424:                Object[] params35 = { startProxylet };
1425:                logger.log(Level.INFO, "PSSRNTLT_CSPNS035", params35);
1426:                if (startProxylet != null
1427:                        && startProxylet.equalsIgnoreCase("true")) {
1428:                    args.append("<argument>").append("startProxylet").append(
1429:                            "</argument>").append("\n").append("<argument>")
1430:                            .append("true").append("</argument>").append("\n");
1431:                    args.append(getProxyletArguments());
1432:                }
1433:
1434:                return args.toString();
1435:            }
1436:
1437:            private String getCommonArguments(HttpServletRequest req,
1438:                    SSOToken ssoTok) {
1439:                StringBuffer args = new StringBuffer(1000);
1440:                String dynamicUrl = req.getContextPath();
1441:                args.append("<argument>").append("cookiename").append(
1442:                        "</argument>").append("\n").append("<argument>")
1443:                        .append(
1444:                                SystemProperties.get(
1445:                                        "com.iplanet.am.cookie.name",
1446:                                        "iPlanetDirectoryPro")).append(
1447:                                "</argument>").append("\n");
1448:                args.append("<argument>").append("configURL").append(
1449:                        "</argument>").append("\n").append("<argument>")
1450:                        .append(
1451:                                req.getHeader("ps-gw-url") + serverUrl
1452:                                        + dynamicUrl + "/NetletConfig").append(
1453:                                "</argument>").append("\n");
1454:                args.append("<argument>").append("gwURL").append("</argument>")
1455:                        .append("\n").append("<argument>").append(
1456:                                req.getHeader("ps-gw-url")).append(
1457:                                "</argument>").append("\n");
1458:                args.append("<argument>").append("sessionId").append(
1459:                        "</argument>").append("\n").append("<argument>")
1460:                        .append(ssoTok.getTokenID().toString()).append(
1461:                                "</argument>").append("\n");
1462:                boolean isPDCEnabled = false;
1463:                String PDCHeader = req.getHeader("PS-GW-PDC");
1464:                if (PDCHeader != null) {
1465:                    isPDCEnabled = Boolean.getBoolean(PDCHeader);
1466:                }
1467:                if (isPDCEnabled) {
1468:                    args.append("<argument>").append("isPDCEnabled").append(
1469:                            "</argument>").append("\n").append("<argument>")
1470:                            .append("true").append("</argument>").append("\n");
1471:                }
1472:                return args.toString();
1473:            }
1474:
1475:            private String getNetletArguments(NetletUser user) {
1476:                StringBuffer args = new StringBuffer(1000);
1477:                Map argsMap = getNetletArgsMap(user);
1478:                Set entrySet = argsMap.entrySet();
1479:                Iterator it = entrySet.iterator();
1480:                while (it.hasNext()) {
1481:                    Map.Entry e = (Map.Entry) it.next();
1482:                    args.append("<argument>").append(e.getKey()).append(
1483:                            "</argument>").append("\n").append("<argument>")
1484:                            .append(e.getValue()).append("</argument>").append(
1485:                                    "\n");
1486:                }
1487:                return args.toString();
1488:            }
1489:
1490:            private Map getNetletArgsMap(NetletUser user) {
1491:                Map argsMap = new HashMap();
1492:                argsMap.put("clientBindIP", user.getClientBindIP());
1493:                argsMap.put("doPortWarning", Boolean.toString(user
1494:                        .getPortWarn()));
1495:                argsMap.put("doReauth", Boolean.toString(user.getReauth()));
1496:                argsMap.put("showPortWarnCheckbox", Boolean.toString(user
1497:                        .getPortWarnCheckbox()));
1498:                argsMap.put("defaultCipher", user.getDefaultCipher());
1499:
1500:                String proxyType = user.getNetletUserAttributes().getString(
1501:                        NetletConstants.NETLET_PROXY_TYPE, "");
1502:                if (proxyType != null && proxyType.length() > 0) {
1503:                    argsMap.put("proxytype", proxyType);
1504:                }
1505:                String proxyHost = user.getNetletUserAttributes().getString(
1506:                        NetletConstants.NETLET_PROXY_HOST, "");
1507:                if (proxyHost != null && proxyHost.length() > 0) {
1508:                    argsMap.put("proxyhost", proxyHost);
1509:                }
1510:                String proxyPort = user.getNetletUserAttributes().getString(
1511:                        NetletConstants.NETLET_PROXY_PORT, "");
1512:                if (proxyPort != null && proxyPort.length() > 0) {
1513:                    argsMap.put("proxyport", proxyPort);
1514:                }
1515:                String proxyOverride = user.getNetletUserAttributes()
1516:                        .getString(NetletConstants.NETLET_PROXY_OVERRIDE, "");
1517:                if (proxyOverride != null && proxyOverride.length() > 0) {
1518:                    argsMap.put("proxyoverride", proxyOverride);
1519:                }
1520:
1521:                int count = 0;
1522:                addLoopbackRule(user);
1523:                Enumeration e = user.getRules();
1524:
1525:                while (e.hasMoreElements()) {
1526:                    Rules r = (Rules) e.nextElement();
1527:
1528:                    // For static Rules :: Check if the rule is allowed
1529:                    if (!user.inPrivilegeList(
1530:                            NetletConstants.NETLET_DENY_RULES, r.name, false,
1531:                            false)
1532:                            && user.inPrivilegeList(
1533:                                    NetletConstants.NETLET_ACCESS_RULES,
1534:                                    r.name, false, false)) {
1535:                        for (int i = 0; i < r.lport.size(); i++) {
1536:                            argsMap.put("ruleName_" + count, r.name);
1537:                            argsMap.put("listenPort_" + count, r.lport
1538:                                    .elementAt(i));
1539:                            argsMap.put("serverPort_" + count, r.dport
1540:                                    .elementAt(i));
1541:                            argsMap.put("serverHost_" + count, r.dhost
1542:                                    .elementAt(i));
1543:                            argsMap
1544:                                    .put("cipher_" + count, user
1545:                                            .getAlgorithm(r));
1546:                            count++;
1547:                        }
1548:                    } else {
1549:
1550:                        // logger.info("Access Denied For Client ID: " +
1551:                        // getClientID(user.getSSOToken()) + " and Rule: " + r.name);
1552:                        Object[] params = { getClientID(user.getSSOToken()),
1553:                                r.name };
1554:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS036", params);
1555:                    }
1556:                }
1557:                argsMap.put("numParms", Integer.toString(count));
1558:                return argsMap;
1559:                // Resource Bundle
1560:                // args.append("<argument>").append("resourceBundle").append("</argument>").append("\n")
1561:                // .append("<argument>").append(getResources(user)).append("</argument>").append("\n");
1562:            }
1563:
1564:            private void outputNetletArgs(NetletUser user) throws IOException {
1565:                HttpServletResponse res = user.getRes();
1566:                PrintWriter out = res.getWriter();
1567:                res.setContentType("text/plain");
1568:                Map argsMap = getNetletArgsMap(user);
1569:                Set entrySet = argsMap.entrySet();
1570:                Iterator it = entrySet.iterator();
1571:                while (it.hasNext()) {
1572:                    Map.Entry e = (Map.Entry) it.next();
1573:                    out.println(e.getKey() + "=" + e.getValue());
1574:                }
1575:                out.close();
1576:            }
1577:
1578:            private String getProxyletArguments() {
1579:                // TODO : PROXYLET
1580:                StringBuffer args = new StringBuffer(1000);
1581:                // must include.
1582:                args.append("<argument>").append("clientBindIP").append(
1583:                        "</argument>").append("\n").append("<argument>")
1584:                        .append("127.0.0.1").append("</argument>").append("\n");
1585:                args.append("<argument>").append("keepWindowMinimized").append(
1586:                        "</argument>").append("\n").append("<argument>")
1587:                        .append("true").append("</argument>").append("\n");
1588:
1589:                return args.toString();
1590:            }
1591:
1592:            private String getResources(NetletUser user) {
1593:                StringBuffer res = new StringBuffer(500);
1594:                for (Enumeration e = user.getAppletBundle().getKeys(); e
1595:                        .hasMoreElements();) {
1596:                    String key = (String) e.nextElement();
1597:                    String value = user.getAppletBundle().getString(key);
1598:                    res.append(key).append("=").append(encodeJavaString(value))
1599:                            .append("|");
1600:                }
1601:                return res.toString();
1602:            }
1603:
1604:            void makeTargetPage(NetletUser user, String targets)
1605:                    throws ServletException, IOException {
1606:                PrintWriter out = user.getRes().getWriter();
1607:                out.print(targets);
1608:                out.close();
1609:            }
1610:
1611:            private boolean redirectToClientListener(NetletUser user,
1612:                    HttpServletRequest req) throws IOException {
1613:                String jwsListenURL = null;
1614:                boolean success = false;
1615:                try {
1616:                    jwsListenURL = user.getSSOToken().getProperty(
1617:                            "jwsListenURL");
1618:                    // logger.info("jwsListenURL " + jwsListenURL);
1619:                    Object[] params37 = { jwsListenURL };
1620:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS037", params37);
1621:                } catch (SSOException e) {
1622:                    // logger.info("JWS client listener URL not found ");
1623:                    logger.info("PSSRNTLT_CSPNS038");
1624:                }
1625:
1626:                String reqURL = HttpUtils.getRequestURL(req).toString() + "?"
1627:                        + req.getQueryString();
1628:                HttpServletResponse res = user.getRes();
1629:                String redirectURL = "";
1630:                if (jwsListenURL == null || jwsListenURL.length() <= 0) {
1631:                    redirectURL = reqURL;
1632:                } else {
1633:                    if (!reqURL.startsWith("/")) {
1634:                        // if not in proxylet mode.
1635:                        reqURL = req.getHeader("ps-gw-url") + reqURL;
1636:                    }
1637:                    redirectURL = jwsListenURL + "/startNetlet?redirectURL="
1638:                            + URLEncoder.encode(reqURL);
1639:                    success = true;
1640:                }
1641:
1642:                // logger.info("redirectToClientListener redirectURL " + redirectURL);
1643:                Object[] params39 = { redirectURL };
1644:                logger.log(Level.INFO, "PSSRNTLT_CSPNS039", params39);
1645:
1646:                res.sendRedirect(redirectURL);
1647:                return success;
1648:            }
1649:
1650:            /*
1651:             * The first time a netlet link is clicked, the netlet will be started and
1652:             * the netlet link will be sent to a second browser window. Since it takes a
1653:             * while for the netlet to load and for the user to accept all those
1654:             * permissions, the browser would most likely time out if we waited.
1655:             *
1656:             * So, this method will create a page that tells the user to wait for the
1657:             * netlet to start, and then click a button to continue.
1658:             */
1659:            void makeLoadingPage(NetletUser user, HttpServletRequest req)
1660:                    throws IOException {
1661:
1662:                HttpServletResponse res = user.getRes();
1663:                PrintWriter out = new PrintWriter(new BufferedWriter(
1664:                        new OutputStreamWriter(res.getOutputStream(), user
1665:                                .getHTMLcharsetname())));
1666:                res.setContentType("text/html; charset="
1667:                        + user.getHTMLcharsetname());
1668:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
1669:                res.setHeader("Pragma", "no-cache");
1670:
1671:                StringBuffer url = new StringBuffer();
1672:                String dynamicUrl = req.getContextPath();
1673:                url.append(dynamicUrl + req.getServletPath()).append("?")
1674:                        .append(req.getQueryString());
1675:
1676:                StringBuffer outBuf = new StringBuffer();
1677:
1678:                outBuf.append("<html>\n");
1679:                outBuf.append("<head>\n");
1680:                outBuf.append("<script language=javascript>\n");
1681:                outBuf.append("\t" + user.getJsDocumentDomainInPage() + "\n\n");
1682:                outBuf.append("\tfunction doRedirect() {\n");
1683:                outBuf
1684:                        .append("\t\twindow.location='" + url.toString()
1685:                                + "';\n");
1686:                outBuf.append("\t}\n");
1687:                outBuf.append("</script>\n");
1688:                outBuf.append("<title>");
1689:                outBuf.append(user.getBundle().getString("ntitle2"));
1690:                outBuf.append("</title></head>\n");
1691:                outBuf.append("<BODY TEXT=\""
1692:                        + user.getBundle().getString("ntxcolor")
1693:                        + "\" BGCOLOR=\""
1694:                        + user.getBundle().getString("nbgcolor") + "\"");
1695:                outBuf.append(">\n");
1696:                outBuf.append("<p>" + user.getBundle().getString("nc3") + "\n");
1697:                outBuf.append("<form>\n");
1698:
1699:                outBuf.append("<input type=button name=continue value='"
1700:                        + user.getBundle().getString("contButton") + "'"
1701:                        + " onClick='doRedirect()'" + ">\n");
1702:                outBuf.append("</form>\n");
1703:                outBuf.append("</body></html>\n");
1704:
1705:                out.print(outBuf.toString());
1706:                out.close();
1707:
1708:            }
1709:
1710:            void makeErrorMsg(NetletUser user, String key) throws IOException {
1711:                HttpServletResponse res = user.getRes();
1712:
1713:                PrintWriter out = new PrintWriter(new BufferedWriter(
1714:                        new OutputStreamWriter(res.getOutputStream(), user
1715:                                .getHTMLcharsetname())));
1716:                res.setContentType("text/html; charset="
1717:                        + user.getHTMLcharsetname());
1718:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
1719:                res.setHeader("Pragma", "no-cache");
1720:
1721:                out.print("<html>\n");
1722:                out.print("<head><title>");
1723:                out.print(user.getBundle().getString("ntitle"));
1724:                if (user.terminateAtLogout()) {
1725:                    out.print(user.getBundle()
1726:                            .getString("addToDetachedWindows"));
1727:                    out.print("\n");
1728:                }
1729:                out.print("</title></head>\n");
1730:                out.print("<BODY TEXT=\""
1731:                        + user.getBundle().getString("ntxcolor")
1732:                        + "\" BGCOLOR=\""
1733:                        + user.getBundle().getString("nbgcolor") + "\"");
1734:                if (user.terminateAtLogout()) {
1735:                    out.print(" onLoad=addToDetachedWindows()");
1736:                }
1737:                out.print(">\n");
1738:                out.print("<p>" + user.getBundle().getString(key)
1739:                        + "</body></html>\n");
1740:                out.close();
1741:            }
1742:
1743:            /*
1744:             * Create the frameset for the netlet mini-page that holds the actual applet
1745:             * tags for the netlet. We are using a frameset so that we can rewrite the
1746:             * main frame with different messages to give the user a clue as to what's
1747:             * happening with the netlet (loading, loaded, etc).
1748:             */
1749:            void makeNetletPage(NetletUser user) throws ServletException,
1750:                    IOException {
1751:                StringBuffer outBuffer = new StringBuffer();
1752:
1753:                HttpServletResponse res = user.getRes();
1754:                String dynamicUrl = user.getReq().getContextPath();
1755:
1756:                // make the url to call this servlet again
1757:                String url = user.getReq().getServletPath();
1758:                url = dynamicUrl + url;
1759:
1760:                PrintWriter out = new PrintWriter(new BufferedWriter(
1761:                        new OutputStreamWriter(res.getOutputStream(), user
1762:                                .getHTMLcharsetname())));
1763:
1764:                res.setContentType("text/html; charset="
1765:                        + user.getHTMLcharsetname());
1766:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
1767:                res.setHeader("Pragma", "no-cache");
1768:
1769:                outBuffer.append("<html>\n");
1770:                outBuffer.append("<head><title>");
1771:                outBuffer.append(user.getBundle().getString("ntitle"));
1772:                outBuffer.append("</title>\n");
1773:                outBuffer.append("\t<script language=javascript>\n");
1774:                outBuffer
1775:                        .append("\t" + user.getJsDocumentDomainInPage() + "\n");
1776:                outBuffer.append("\t</script>\n");
1777:                outBuffer.append("</head>\n");
1778:                Object[] values = {
1779:                        "info",
1780:                        url + "?func=makeInfoFrame"
1781:                                + user.getJsDocumentDomainInUrl(),
1782:                        "netlet",
1783:                        url + "?func=makeDetectFrame"
1784:                                + user.getJsDocumentDomainInUrl() };
1785:
1786:                String frameset = user.getBundle().getString("frameset");
1787:                MessageFormat format = new MessageFormat("");
1788:                format.applyPattern(frameset);
1789:                outBuffer.append(format.format(values).toString());
1790:
1791:                outBuffer.append("</html>\n");
1792:
1793:                out.print(outBuffer.toString());
1794:                out.close();
1795:            }
1796:
1797:            /*
1798:             * Generate the frame that will contain the applet tags and associated info
1799:             * for the netlet
1800:             */
1801:            void makeNetletFrame(NetletUser user) throws ServletException,
1802:                    IOException {
1803:                StringBuffer outBuffer = new StringBuffer();
1804:
1805:                HttpServletResponse res = user.getRes();
1806:                HttpServletRequest req = user.getReq();
1807:                String staticUrl = req.getContextPath();
1808:                String encryptionType = user.getEncryptionType();
1809:                // logger.info("Netlet encryption type -> " + encryptionType);
1810:                Object[] params40 = { encryptionType };
1811:                logger.log(Level.INFO, "PSSRNTLT_CSPNS040", params40);
1812:                boolean isNetletSSL = false;
1813:                if ("SSL".equals(encryptionType)) {
1814:                    isNetletSSL = true;
1815:                }
1816:
1817:                boolean sendJSSEJar = false;
1818:                String JSSEQueryString = req.getParameter("JSSE");
1819:                if (JSSEQueryString == null) {
1820:                    sendJSSEJar = false;
1821:                } else {
1822:                    sendJSSEJar = true;
1823:                    isNetletSSL = false;
1824:                }
1825:
1826:                boolean isPDCEnabled = false;
1827:                String PDCHeader = req.getHeader("PS-GW-PDC");
1828:
1829:                if (PDCHeader != null) {
1830:                    isPDCEnabled = Boolean.getBoolean(PDCHeader);
1831:                }
1832:
1833:                PrintWriter out = new PrintWriter(new BufferedWriter(
1834:                        new OutputStreamWriter(res.getOutputStream(), user
1835:                                .getHTMLcharsetname())));
1836:                res.setContentType("text/html; charset="
1837:                        + user.getHTMLcharsetname());
1838:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
1839:                res.setHeader("Pragma", "no-cache");
1840:
1841:                outBuffer.append("<html>\n");
1842:                outBuffer.append("<head><title>");
1843:                outBuffer.append(user.getBundle().getString("ntitle"));
1844:                outBuffer.append("</title>\n");
1845:                outBuffer.append("\t<script language=javascript>\n");
1846:                outBuffer.append("\t\tvar needToSleep = true;\n");
1847:                outBuffer.append("\t\tfunction showConfiguration()\n");
1848:                outBuffer.append("\t\t{\n");
1849:                outBuffer
1850:                        .append("\t\t\tif ((document.netapp != null) && document.netapp.isActive())\n");
1851:                outBuffer
1852:                        .append("\t\t\t\tdocument.netapp.showClientPorts();\n");
1853:                outBuffer.append("\t\t\telse\n");
1854:                outBuffer
1855:                        .append("\t\t\t\twindow.status = \"information not yet loaded\"\n");
1856:                outBuffer.append("\t\t}\n");
1857:                outBuffer.append("\t</script>\n");
1858:                outBuffer.append("</head>\n");
1859:                outBuffer.append("<BODY TEXT=\"").append(
1860:                        user.getBundle().getString("ntxcolor"));
1861:                outBuffer.append("\" BGCOLOR=\"").append(
1862:                        user.getBundle().getString("nbgcolor")).append("\">\n");
1863:                outBuffer.append(user.getBundle().getString("showClientPorts"))
1864:                        .append('\n');
1865:
1866:                // give cookie name and correct jar file to Mac MSIE so it can feed it
1867:                // to MRJ
1868:                String agent = user.getReq().getHeader("user-agent");
1869:                if (agent.indexOf("Mac_PowerPC") != -1
1870:                        && agent.indexOf("MSIE") != -1) {
1871:
1872:                    if (isNetletSSL) {
1873:                        outBuffer
1874:                                .append(
1875:                                        "<p><applet name=\"netapp\" codebase=\"")
1876:                                .append(staticUrl)
1877:                                .append(
1878:                                        "/netlet\" archive=\"netlet.mac.jar, kssl.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1879:                    } else if (sendJSSEJar) {
1880:                        outBuffer
1881:                                .append(
1882:                                        "<p><applet name=\"netapp\" codebase=\"")
1883:                                .append(staticUrl)
1884:                                .append(
1885:                                        "/netlet\" archive=\"netlet.mac.jar, netletjsse.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1886:                    } else {
1887:                        outBuffer
1888:                                .append(
1889:                                        "<p><applet name=\"netapp\" codebase=\"")
1890:                                .append(staticUrl)
1891:                                .append(
1892:                                        "/netlet\" archive=\"netlet.mac.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1893:                    }
1894:
1895:                } else {
1896:
1897:                    if (isNetletSSL) {
1898:                        outBuffer
1899:                                .append(
1900:                                        "<p><applet name=\"netapp\" codebase=\"")
1901:                                .append(staticUrl)
1902:                                .append(
1903:                                        "/netlet\" archive=\"netlet.jar, kssl.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1904:                    } else if (sendJSSEJar) {
1905:                        outBuffer
1906:                                .append(
1907:                                        "<p><applet name=\"netapp\" codebase=\"")
1908:                                .append(staticUrl)
1909:                                .append(
1910:                                        "/netlet\" archive=\"netlet.jar, netletjsse.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1911:                    } else {
1912:                        outBuffer
1913:                                .append(
1914:                                        "<p><applet name=\"netapp\" codebase=\"")
1915:                                .append(staticUrl)
1916:                                .append(
1917:                                        "/netlet\" archive=\"netlet.jar\" code=\"com/sun/portal/netlet/client/applet/NetletApplet.class\" width=1 height=1 MAYSCRIPT>\n");
1918:                    }
1919:                }
1920:                outBuffer.append("<param name=\"cookiename\" value=\""
1921:                        + SystemProperties.get("com.iplanet.am.cookie.name",
1922:                                "iPlanetDirectoryPro") + "\">\n");
1923:
1924:                String dynamicUrl = req.getContextPath();
1925:                outBuffer.append("<param name=\"configURL\" value=\"").append(
1926:                        dynamicUrl).append("/NetletConfig\">\n");
1927:                outBuffer.append("<param name=\"resourcesURL\" value=\"")
1928:                        .append(dynamicUrl).append(
1929:                                "/NetletConfig?func=loadResources\">\n");
1930:                outBuffer.append("<param name=\"gwURL\" value=\"").append(
1931:                        req.getHeader("ps-gw-url")).append("\">\n");
1932:                outBuffer.append("<param name=\"clientBindIP\" value=\"")
1933:                        .append(user.getClientBindIP()).append("\">\n");
1934:                if (user.getJsDocumentDomain() != null) {
1935:                    outBuffer.append("<param name=\"").append(
1936:                            JS_DOCUMENT_DOMAIN).append("\" value=\"").append(
1937:                            user.getJsDocumentDomain()).append("\">\n");
1938:                }
1939:
1940:                int count = 0;
1941:
1942:                addLoopbackRule(user);
1943:                Enumeration e = user.getRules();
1944:
1945:                while (e.hasMoreElements()) {
1946:                    Rules r = (Rules) e.nextElement();
1947:
1948:                    // For static Rules :: Check if the rule is allowed
1949:                    if (!user.inPrivilegeList(
1950:                            NetletConstants.NETLET_DENY_RULES, r.name, false,
1951:                            false)
1952:                            && user.inPrivilegeList(
1953:                                    NetletConstants.NETLET_ACCESS_RULES,
1954:                                    r.name, false, false)) {
1955:                        for (int i = 0; i < r.lport.size(); i++) {
1956:                            outBuffer.append("<param name=ruleName_" + count
1957:                                    + " value=" + r.name + ">\n");
1958:                            outBuffer.append("<param name=listenPort_" + count
1959:                                    + " value=" + (String) r.lport.elementAt(i)
1960:                                    + ">\n");
1961:                            /*
1962:                             * outBuffer.append(" <param name=remoteHost_" + count +"
1963:                             * value=" + user.getGatewayName() + ">\n");
1964:                             * outBuffer.append(" <param name=remotePort_" + count +"
1965:                             * value=" + user.getGatewayPort() + ">\n");
1966:                             */
1967:                            outBuffer.append("<param name=serverPort_" + count
1968:                                    + " value=" + (String) r.dport.elementAt(i)
1969:                                    + ">\n");
1970:                            outBuffer.append("<param name=serverHost_" + count
1971:                                    + " value=" + (String) r.dhost.elementAt(i)
1972:                                    + ">\n");
1973:                            // Pluggable Cipher
1974:                            outBuffer.append("<param name=cipher_" + count
1975:                                    + " value=" + user.getAlgorithm(r) + ">\n");
1976:                            count++;
1977:                        }
1978:                    } else {
1979:
1980:                        // logger.info("Access Denied For Client ID: " +
1981:                        // getClientID(user.getSSOToken()) + " and Rule: " + r.name);
1982:                        Object[] params = { getClientID(user.getSSOToken()),
1983:                                r.name };
1984:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS041", params);
1985:                    }
1986:                }
1987:
1988:                outBuffer.append("<param name=sessionId value="
1989:                        + user.getSSOTokenID().toString() + ">\n");
1990:                outBuffer.append("<param name=encryptionType value="
1991:                        + encryptionType + ">\n");
1992:                outBuffer.append("<param name=numParms value=" + count + ">\n");
1993:                outBuffer.append("<param name=doPortWarning value="
1994:                        + user.getPortWarn() + ">\n");
1995:                outBuffer.append("<param name=doReauth value="
1996:                        + user.getReauth() + ">\n");
1997:                outBuffer.append("<param name=showPortWarnCheckbox value="
1998:                        + user.getPortWarnCheckbox() + ">\n");
1999:                /*
2000:                 * outBuffer.append(" <param name=netletKeepAliveInterval value="+
2001:                 * user.getNetletKeepAliveInterval() + ">\n");
2002:                 */
2003:                // Pluggable Cipher
2004:                outBuffer.append("<param name=defaultCipher value="
2005:                        + user.getDefaultCipher() + ">\n");
2006:                outBuffer.append("<param name=proxytype value="
2007:                        + user.getNetletUserAttributes().getString(
2008:                                NetletConstants.NETLET_PROXY_TYPE, "") + ">\n");
2009:                outBuffer.append("<param name=proxyhost value="
2010:                        + user.getNetletUserAttributes().getString(
2011:                                NetletConstants.NETLET_PROXY_HOST, "") + ">\n");
2012:                outBuffer.append("<param name=proxyport value="
2013:                        + user.getNetletUserAttributes().getString(
2014:                                NetletConstants.NETLET_PROXY_PORT, "") + ">\n");
2015:                outBuffer.append("<param name=proxyoverride value="
2016:                        + user.getNetletUserAttributes().getString(
2017:                                NetletConstants.NETLET_PROXY_OVERRIDE, "")
2018:                        + ">\n");
2019:                if (sendJSSEJar) {
2020:                    outBuffer.append("<param name=isJSSEEnabled value=true>\n");
2021:                }
2022:                if (isPDCEnabled) {
2023:                    outBuffer.append("<param name=isPDCEnabled value=true>\n");
2024:                }
2025:                // count =0;
2026:                // List pluggedInAlgos = user.getPluggedInAlgorithms();
2027:                /*
2028:                 * Export Restriction if(pluggedInAlgos.size() >= 3){ int i=0; for(count =
2029:                 * 0;count <= pluggedInAlgos.size()/3;i++){ outBuffer.append(" <param
2030:                 * name=pluggedInAlgo_"+i+" value="+pluggedInAlgos.get(count)+">\n");
2031:                 * count++; outBuffer.append(" <param name=pluggedInClass_"+i+"
2032:                 * value="+pluggedInAlgos.get(count)+">\n"); count+=2; }
2033:                 * outBuffer.append(" <param name=pluggedInSize
2034:                 * value="+(pluggedInAlgos.size()/3)+">\n"); }
2035:                 */
2036:
2037:                //
2038:                outBuffer.append("</applet>\n");
2039:                outBuffer.append("</body>\n");
2040:                outBuffer.append("</html>\n");
2041:                out.print(outBuffer.toString());
2042:                out.close();
2043:            }
2044:
2045:            /*
2046:             * Generate the frame that will contain only the status for the netlet
2047:             */
2048:            void makeInfoFrame(NetletUser user) throws ServletException,
2049:                    IOException {
2050:                StringBuffer outBuffer = new StringBuffer();
2051:
2052:                HttpServletResponse res = user.getRes();
2053:                HttpServletRequest req = user.getReq();
2054:
2055:                // which status page are we supposed to display?
2056:                String stat = req.getParameter("stat");
2057:                if (stat == null || stat.equals("")) {
2058:                    stat = "nc4";
2059:                }
2060:
2061:                // For Mac MSIE, always display that Netlet is loaded since we don't
2062:                // have JSObject
2063:                // capability to have Netlet tell window that it's done loading
2064:                String agent = user.getReq().getHeader("user-agent");
2065:                if (agent.indexOf("Mac_PowerPC") != -1
2066:                        && agent.indexOf("MSIE") != -1)
2067:                    stat = "nc1";
2068:
2069:                PrintWriter out = new PrintWriter(new BufferedWriter(
2070:                        new OutputStreamWriter(res.getOutputStream(), user
2071:                                .getHTMLcharsetname())));
2072:                res.setContentType("text/html; charset="
2073:                        + user.getHTMLcharsetname());
2074:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
2075:                res.setHeader("Pragma", "no-cache");
2076:
2077:                outBuffer.append("<html>\n");
2078:                outBuffer.append("<head>\n");
2079:                outBuffer.append("\t<script language=javascript>\n");
2080:                outBuffer
2081:                        .append("\t" + user.getJsDocumentDomainInPage() + "\n");
2082:                outBuffer.append("\t</script>\n");
2083:                //        outBuffer.append(user.getBundle().getString("showClientPorts")).append("\n");
2084:                if (user.terminateAtLogout()) {
2085:                    outBuffer
2086:                            .append("<script src=\""
2087:                                    + req.getContextPath()
2088:                                    + "/close-windows.jsp\" language=\"JavaScript\" type=\"text/javascript\"></script>");
2089:                    outBuffer.append("\n");
2090:                }
2091:
2092:                outBuffer.append("</head>\n");
2093:
2094:                outBuffer.append("<BODY TEXT=\"").append(
2095:                        user.getBundle().getString("ntxcolor")).append("\"");
2096:                if (user.terminateAtLogout()) {
2097:                    outBuffer.append(" onLoad=\"").append(
2098:                            user.getBundle().getString("addNetletWindow"))
2099:                            .append("\"").append(" onUnload=\"").append(
2100:                                    user.getBundle().getString(
2101:                                            "removeNetletWindow")).append("\"");
2102:                }
2103:                outBuffer.append(" BGCOLOR=\"").append(
2104:                        user.getBundle().getString("nbgcolor")).append("\">\n");
2105:                outBuffer.append("<p>")
2106:                        .append(user.getBundle().getString(stat));
2107:                outBuffer.append("</body>\n");
2108:                outBuffer.append("</html>\n");
2109:                out.print(outBuffer.toString());
2110:                out.close();
2111:            }
2112:
2113:            /*
2114:             * Serves the netlet JSSE dectect applet
2115:             */
2116:            void makeDetectNetletFrame(NetletUser user)
2117:                    throws ServletException, IOException {
2118:                StringBuffer outBuffer = new StringBuffer();
2119:
2120:                HttpServletResponse res = user.getRes();
2121:                HttpServletRequest req = user.getReq();
2122:                String staticUrl = req.getContextPath();
2123:                String dynamicUrl = req.getContextPath();
2124:
2125:                PrintWriter out = new PrintWriter(new BufferedWriter(
2126:                        new OutputStreamWriter(res.getOutputStream(), user
2127:                                .getHTMLcharsetname())));
2128:                res.setContentType("text/html; charset="
2129:                        + user.getHTMLcharsetname());
2130:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
2131:                res.setHeader("Pragma", "no-cache");
2132:
2133:                outBuffer.append("<html>\n");
2134:                outBuffer.append("<head>\n");
2135:                outBuffer.append("\n</head>\n");
2136:                outBuffer.append("<BODY TEXT=\"").append(
2137:                        user.getBundle().getString("ntxcolor"));
2138:                outBuffer.append("\" BGCOLOR=\"").append(
2139:                        user.getBundle().getString("nbgcolor")).append("\">\n");
2140:                outBuffer
2141:                        .append("<applet name=\"netapp\" codebase=\"")
2142:                        .append(staticUrl)
2143:                        .append(
2144:                                "/netlet\" archive=\"netletdetect.jar\" code=\"com/sun/portal/netlet/client/applet/NetletEnvDetect.class\" width=1 height=1>\n");
2145:                outBuffer.append("<param name=\"configURL\" value=\"").append(
2146:                        dynamicUrl).append("/NetletConfig\">\n");
2147:                outBuffer.append("<param name=\"gwURL\" value=\"").append(
2148:                        req.getHeader("ps-gw-url")).append("\">\n");
2149:                outBuffer.append("</applet>");
2150:                outBuffer.append("</body>\n");
2151:                outBuffer.append("</html>\n");
2152:                out.print(outBuffer.toString());
2153:                out.close();
2154:            }
2155:
2156:            void outputResources(NetletUser user) throws ServletException,
2157:                    IOException {
2158:                HttpServletResponse res = user.getRes();
2159:                PrintWriter out = res.getWriter();
2160:                res.setContentType("text/plain");
2161:                for (Enumeration e = user.getAppletBundle().getKeys(); e
2162:                        .hasMoreElements();) {
2163:                    String key = (String) e.nextElement();
2164:                    String value = user.getAppletBundle().getString(key);
2165:                    out.println(key + "=" + encodeJavaString(value));
2166:                }
2167:                // Added for bug 4432831
2168:                /*
2169:                 * try { out.println("_sessionKey=" + getKey(user)); } catch
2170:                 * (SSOException se) { se.printStackTrace();
2171:                 * redirectToPage(user.getRes(), "invalidsession", null,
2172:                 * user.getLocale(), user.getHTMLcharsetname()); return; }
2173:                 */
2174:                out.close();
2175:            }
2176:
2177:            /*
2178:             * This method encodes a Unicode Java String into a sequence of ASCII
2179:             * characters with non-ascii characters represented the way they would be in
2180:             * a Java program, e.g., with \u1234.
2181:             */
2182:            static public String encodeJavaString(String s) {
2183:                StringBuffer buf = new StringBuffer();
2184:                for (int i = 0; i < s.length(); i++) {
2185:                    char c = s.charAt(i);
2186:                    int ic = (int) c;
2187:                    if (ic >= 32 && ic <= 127) {
2188:                        buf.append(c);
2189:                    } else {
2190:                        buf.append("\\u");
2191:                        for (int j = 4; j > 0; j--) {
2192:                            buf.append(Character.forDigit((ic & 0xf000) >> 12,
2193:                                    16));
2194:                            ic <<= 4;
2195:                        }
2196:                    }
2197:                }
2198:                return buf.toString();
2199:            }
2200:
2201:            /*
2202:             * Checks whether the given String is in pure IPAddress format
2203:             */
2204:            private boolean isIPAddress(String hostName) {
2205:                StringTokenizer st = new StringTokenizer(hostName, ".");
2206:                int count = 0;
2207:                while (st.hasMoreTokens()) {
2208:                    String str = st.nextToken();
2209:                    try {
2210:                        int intVal = Integer.parseInt(str);
2211:                        if (intVal > 255)
2212:                            return false;
2213:                    } catch (NumberFormatException ex) {
2214:                        return false;
2215:                    }
2216:                    ++count;
2217:                }
2218:                return count == 4 ? true : false;
2219:            }
2220:
2221:            /*
2222:             * Checks whether the given hostname is valid or not.
2223:             */
2224:            public boolean isValidHost(String hostName) {
2225:                InetAddress inetaddr = null;
2226:                try {
2227:                    inetaddr = InetAddress.getByName(hostName);
2228:                } catch (UnknownHostException uhe) {
2229:                    return false;
2230:                }
2231:                String resolvedHostName = inetaddr.getHostName();
2232:                if (isIPAddress(hostName) && hostName.equals(resolvedHostName)) {
2233:                    return false;
2234:                }
2235:                return true;
2236:            }
2237:
2238:            /*
2239:             * Returns the IPAddress of the hostName
2240:             */
2241:            private String getIPAddress(String hostName) {
2242:                InetAddress inetaddr = null;
2243:                try {
2244:                    inetaddr = InetAddress.getByName(hostName);
2245:                } catch (UnknownHostException uhe) {
2246:                    // logger.info("getIPAddress : UnknownHostException hostName " +
2247:                    // hostName);
2248:                    Object[] params = { hostName };
2249:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS042", params);
2250:                    return hostName;
2251:                }
2252:                return inetaddr.getHostAddress();
2253:            }
2254:
2255:            /*
2256:             * Returns the hostName corresponding to the IPAddress
2257:             */
2258:            private String getHostName(String IPAddress) {
2259:                InetAddress inetaddr = null;
2260:                try {
2261:                    inetaddr = InetAddress.getByName(IPAddress);
2262:                } catch (UnknownHostException uhe) {
2263:                    // logger.info("getHostName : UnknownHostException IPAddress " +
2264:                    // IPAddress);
2265:                    Object[] params = { IPAddress };
2266:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS043", params);
2267:                    return IPAddress;
2268:                }
2269:                String hostName = inetaddr.getHostName();
2270:                if (hostName.indexOf(".") == -1 && serverDomain != null) {
2271:                    hostName += ".";
2272:                    hostName += serverDomain;
2273:                }
2274:                return hostName;
2275:            }
2276:
2277:            /**
2278:             * Verifies whether the string <source>contains the substring <target>in it.
2279:             *
2280:             * @param source -
2281:             *            Source string
2282:             * @param target -
2283:             *            substring to be matched in source string.
2284:             * @return true if <source>contains <target>, false otherwise.
2285:             */
2286:            private boolean containsString(String source, String target) {
2287:                if (source == null || target == null) {
2288:                    return false;
2289:                }
2290:                int targetLen = target.length();
2291:                int sourceLen = source.length();
2292:                for (int i = 0; (sourceLen - i) >= targetLen; ++i) {
2293:                    String temp = source.substring(i, i + targetLen);
2294:                    if (target.equals(temp))
2295:                        return true;
2296:                }
2297:                return false;
2298:            }
2299:
2300:            boolean openDynamic(NetletUser user, String type)
2301:                    throws IOException {
2302:                // logger.info("openDynamic " + type);
2303:                Object[] params44 = { type };
2304:                logger.log(Level.INFO, "PSSRNTLT_CSPNS044", params44);
2305:                Rules rule = user.getRule(type);
2306:                if (rule == null) {
2307:                    // logger.info("Error No rule for " + type);
2308:                    Object[] params45 = { type };
2309:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS045", params45);
2310:                    return false;
2311:                }
2312:                String url = null;
2313:                String localIP = user.getClientBindIP();
2314:                if (rule.loopback == false) {
2315:                    url = rule.url;
2316:                } else {
2317:                    String loopbackport = getClientPort(user.getSSOTokenID()
2318:                            .toString(), type, rule.clientLoopbackPort);
2319:                    if (loopbackport == null) {
2320:                        loopbackport = getClientPort(user.getSSOTokenID()
2321:                                .toString(), "loopback",
2322:                                rule.clientLoopbackPort);
2323:                    }
2324:                    String ruleURL = rule.url;
2325:                    if (ruleURL.toLowerCase().startsWith(HTTP_PROTOCOL)) {
2326:                        int colonIndex = ruleURL.indexOf(":");
2327:                        String appletProtocol = ruleURL
2328:                                .substring(0, colonIndex);
2329:                        int urlIndex = ruleURL.indexOf("/", colonIndex + 3);
2330:                        url = appletProtocol + "://" + localIP + ":"
2331:                                + loopbackport
2332:                                + ruleURL.substring(urlIndex, ruleURL.length());
2333:                    } else {
2334:                        url = HTTP_PROTOCOL + "://" + localIP + ":"
2335:                                + loopbackport + rule.url;
2336:                    }
2337:                }
2338:                int localHostIndex = url.toLowerCase().indexOf("localhost");
2339:                if (localHostIndex >= 0) {
2340:                    url = url.substring(0, localHostIndex)
2341:                            + localIP
2342:                            + url.substring(localHostIndex
2343:                                    + "localhost".length());
2344:                }
2345:                // logger.info("Open dynamic port url " + url);
2346:                Object[] params46 = { url };
2347:                logger.log(Level.INFO, "PSSRNTLT_CSPNS046", params46);
2348:                HttpServletRequest req = user.getReq();
2349:                HttpServletResponse res = user.getRes();
2350:
2351:                String targetHost = req.getParameter("machine");
2352:                targetHost = URLEncoder.encode(targetHost);
2353:                if (targetHost == null || targetHost.equals("")) {
2354:                    // logger.info("Error: no target host specified for " + type);
2355:                    Object[] params47 = { type };
2356:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS047", params47);
2357:                    return false;
2358:                }
2359:                /*
2360:                 * Check whether user has access to this rule
2361:                 */
2362:                if (user.inPrivilegeList(NetletConstants.NETLET_DENY_RULES,
2363:                        type, false, false)) {
2364:                    redirectToPage(user.getRes(), "noprivilege.rule", type,
2365:                            user.getLocale(), user.getHTMLcharsetname());
2366:                    return false;
2367:                }
2368:                if (!user.inPrivilegeList(NetletConstants.NETLET_ACCESS_RULES,
2369:                        type, false, false)) {
2370:                    redirectToPage(user.getRes(), "noprivilege.rule", type,
2371:                            user.getLocale(), user.getHTMLcharsetname());
2372:                    return false;
2373:                }
2374:                /*
2375:                 * Create a vector of valid target hosts.
2376:                 */
2377:                String tempTargetHost = new String(targetHost);
2378:                StringTokenizer hostNames = new StringTokenizer(tempTargetHost,
2379:                        "+");
2380:                Vector newTargetHosts = new Vector();
2381:                while (hostNames.hasMoreTokens()) {
2382:                    String hostName = hostNames.nextToken();
2383:                    // Bug# 4956878 :: Remove the validation
2384:                    // if (isValidHost(hostName)) {
2385:                    if (hostName.indexOf(".") == -1 && serverDomain != null) {
2386:                        hostName += ".";
2387:                        hostName += serverDomain;
2388:                    }
2389:                    newTargetHosts.add(hostName);
2390:                    // }
2391:                }
2392:                if (newTargetHosts.size() == 0) {
2393:                    redirectToPage(user.getRes(), "invalidhost", null, user
2394:                            .getLocale(), user.getHTMLcharsetname());
2395:                    return false;
2396:                }
2397:                /*
2398:                 * Out of valid hosts remove those which are in Deny list
2399:                 */
2400:                for (int i = 0; i < newTargetHosts.size(); i++) {
2401:                    String hostName = (String) newTargetHosts.get(i);
2402:                    boolean inDeniedList = (user.inPrivilegeList(
2403:                            NetletConstants.NETLET_DENY_HOSTS,
2404:                            getHostName(hostName), true, true) || user
2405:                            .inPrivilegeList(NetletConstants.NETLET_DENY_HOSTS,
2406:                                    getIPAddress(hostName), true, true));
2407:                    if (inDeniedList) {
2408:                        newTargetHosts.remove(hostName);
2409:                        --i;
2410:                    }
2411:                }
2412:                if (newTargetHosts.size() == 0) {
2413:                    redirectToPage(user.getRes(), "noprivilege.host",
2414:                            targetHost.replace('+', ','), user.getLocale(),
2415:                            user.getHTMLcharsetname());
2416:                    return false;
2417:                }
2418:
2419:                /*
2420:                 * Out of hosts which are valid && not in deny list, remove those which
2421:                 * are not in allow list
2422:                 */
2423:                for (int i = 0; i < newTargetHosts.size(); i++) {
2424:                    String hostName = (String) newTargetHosts.get(i);
2425:                    boolean inAllowedList = (user.inPrivilegeList(
2426:                            NetletConstants.NETLET_ACCESS_HOSTS,
2427:                            getHostName(hostName), true, true) || user
2428:                            .inPrivilegeList("AccessHosts",
2429:                                    getIPAddress(hostName), true, true));
2430:                    if (!inAllowedList) {
2431:                        newTargetHosts.remove(hostName);
2432:                        --i;
2433:                    }
2434:                }
2435:                if (newTargetHosts.size() == 0) {
2436:                    redirectToPage(user.getRes(), "noprivilege.host",
2437:                            targetHost.replace('+', ','), user.getLocale(),
2438:                            user.getHTMLcharsetname());
2439:                    return false;
2440:                }
2441:                /*
2442:                 * Modified for Bug 4625720
2443:                 */
2444:                String localPort = "";
2445:                String targetPort = "";
2446:                /*
2447:                 * Form a new Targets from the hosts remained after validating and
2448:                 * checking for privileges
2449:                 */
2450:                StringBuffer newTargets = new StringBuffer();
2451:                Iterator iter = newTargetHosts.iterator();
2452:                if (iter.hasNext()) {
2453:                    newTargets.append((String) iter.next());
2454:                }
2455:                while (iter.hasNext()) {
2456:                    newTargets.append("+");
2457:                    newTargets.append((String) iter.next());
2458:                }
2459:                targetHost = newTargets.toString();
2460:
2461:                // logger.info("Server domain -> " + serverDomain + " Valid and allowed
2462:                // targets -> " + targetHost);
2463:                Object[] params = { serverDomain, targetHost };
2464:                logger.log(Level.INFO, "PSSRNTLT_CSPNS048", params);
2465:
2466:                for (int i = 0; i < rule.ruleCount; i++) {
2467:                    targetPort = (String) rule.dport.elementAt(i);
2468:                    String clientPortInRule = (String) rule.lport.elementAt(i);
2469:                    localPort = getClientPort(user.getSSOTokenID().toString(),
2470:                            type, clientPortInRule);
2471:
2472:                    // logger.info("Client port in rule -> " + clientPortInRule + "
2473:                    // Actual client port ->" + localPort);
2474:                    Object[] params49 = { clientPortInRule,
2475:                            " Actual client port ->", localPort };
2476:                    logger.log(Level.INFO, "PSSRNTLT_CSPNS049", params49);
2477:
2478:                    if (localPort == null) {
2479:                        // logger.severe("NetletConfig: No clientport corresponding to "
2480:                        // + targetPort);
2481:                        Object[] params50 = { targetPort };
2482:                        logger.log(Level.SEVERE, "PSSRNTLT_CSPNS050", params50);
2483:                        continue;
2484:                    }
2485:                    /**
2486:                     * If no loopback is required (as the case with telnet rule),
2487:                     * replace DYNAMICPORT keyword with the clientport corresponding to
2488:                     * first targetport.
2489:                     */
2490:                    if (!localPort.equals(clientPortInRule)
2491:                            && containsString(url, clientPortInRule)) {
2492:                        String temp = url;
2493:                        url = temp.substring(0, temp.indexOf(clientPortInRule));
2494:                        url += localPort;
2495:                        url += temp.substring(temp.indexOf(clientPortInRule)
2496:                                + clientPortInRule.length());
2497:                        // logger.info("URL -> " + url);
2498:                        Object[] params51 = { url };
2499:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS051", params51);
2500:                    }
2501:                    /*
2502:                     * if(i == 0 && url.indexOf("DYNAMICPORT") != -1) { String temp =
2503:                     * url; url = temp.substring(0, temp.indexOf("DYNAMICPORT")); url +=
2504:                     * localPort; url += temp.substring(temp.indexOf("DYNAMICPORT") +
2505:                     * "DYNAMICPORT".length()); }
2506:                     */
2507:                    /**
2508:                     * If there is loopback, append the clientPorts corresponding to
2509:                     * each targetport to the URL
2510:                     *
2511:                     * eg., Original URL -
2512:                     * "http://localhost:8000/portal/citrix/citrix_start.html" will now
2513:                     * change to
2514:                     * "http://localhost:8000/portal/citrix/citrix_start.html?clientPort['1494']=2333"
2515:                     *
2516:                     * The meaning of the keyValue pair clientPort['1494']=2333 is that,
2517:                     * the clientPort corresponding to targetport 1494 (at which the
2518:                     * citrix server is listening) is 2333.
2519:                     */
2520:                    if (rule.loopback == true) {
2521:                        if (i == 0)
2522:                            url += "?";
2523:                        url += "clientPort[\\'" + targetPort + "\\']="
2524:                                + localPort;
2525:                        if (i + 1 < rule.ruleCount)
2526:                            url += "&";
2527:                    }
2528:                    String targetHostInRule = (String) rule.dhost.elementAt(i);
2529:                    if (!targetHostInRule
2530:                            .equals(NetletConstants.NETLET_TARGET_HOST)) {
2531:                        continue;
2532:                    }
2533:                    try {
2534:                        user.getSSOToken().setProperty(localPort,
2535:                                targetHost + "^" + targetPort);
2536:                    } catch (SSOException ex) {
2537:                        // logger.severe("Error setting session " + ex);
2538:                        logger.log(Level.SEVERE, "PSSRNTLT_CSPNS052", ex);
2539:                        return false;
2540:                    }
2541:                }
2542:
2543:                // To auto close the browser window
2544:                if (url != null && url.startsWith("telnet")) {
2545:                    autoCloseWindow = true;
2546:                }
2547:                openPage(user, res, url);
2548:                return true;
2549:            }
2550:
2551:            void openPage(NetletUser user, HttpServletResponse res, String url)
2552:                    throws IOException {
2553:                String agent = user.getReq().getHeader("user-agent");
2554:                if (agent.indexOf("Mac_PowerPC") != -1
2555:                        && agent.indexOf("MSIE") != -1) {
2556:                    // Mac MSIE doesn't deal with the javascript redirect to launch
2557:                    // telnet
2558:                    res.sendRedirect(url);
2559:                } else {
2560:                    StringBuffer outBuffer = new StringBuffer();
2561:                    PrintWriter out = new PrintWriter(new BufferedWriter(
2562:                            new OutputStreamWriter(res.getOutputStream(), user
2563:                                    .getHTMLcharsetname())));
2564:                    res.setContentType("text/html; charset="
2565:                            + user.getHTMLcharsetname());
2566:                    outBuffer.append("<html>\n");
2567:
2568:                    if (autoCloseWindow) {
2569:                        outBuffer.append(user.getBundle().getString(
2570:                                "autoCloseWindow"));
2571:                        outBuffer.append("\n");
2572:                    } else if (user.terminateAtLogout()) {
2573:                        outBuffer
2574:                                .append("<script src=\""
2575:                                        + user.getReq().getContextPath()
2576:                                        + "/close-windows.jsp\" language=\"JavaScript\" type=\"text/javascript\"></script><script language=JavaScript> function addToDetachedWindows() { var now = new Date(); window.name=\"Netlet_\" + now.getTime(); windowOpened(window.name);} </script>");
2577:                        outBuffer.append("\n");
2578:                    }
2579:
2580:                    if (url == null || url.equals("")) {
2581:                        outBuffer.append("<body onload=window.close()>\n");
2582:                    } else {
2583:                        outBuffer.append("<body onload=\"");
2584:                        if (autoCloseWindow) {
2585:                            outBuffer.append("autoCloseWindow(); ");
2586:                        } else if (user.terminateAtLogout()) {
2587:                            outBuffer.append("addToDetachedWindows(); ");
2588:                        }
2589:                        outBuffer.append("window.opener.netletLoaded = true; ");
2590:                        outBuffer.append("window.location.replace(\'" + url
2591:                                + "\')\">\n");
2592:                    }
2593:
2594:                    outBuffer.append("</body></html>\n\n");
2595:                    out.print(outBuffer.toString());
2596:                    out.close();
2597:                }
2598:            }
2599:
2600:            void printRules(NetletUser u) {
2601:
2602:                Enumeration e = u.getRules();
2603:
2604:                while (e.hasMoreElements()) {
2605:                    Rules r = (Rules) e.nextElement();
2606:                    for (int i = 0; i < r.lport.size(); i++) {
2607:                    }
2608:                }
2609:            }
2610:
2611:            public void doGet(HttpServletRequest req, HttpServletResponse res)
2612:                    throws ServletException, IOException {
2613:                doGetPost(req, res);
2614:            }
2615:
2616:            public void doPost(HttpServletRequest req, HttpServletResponse res)
2617:                    throws ServletException, IOException {
2618:                doGetPost(req, res);
2619:            }
2620:
2621:            private synchronized int getStatus(String sid) {
2622:                Integer status = (Integer) sessionHash.get(sid);
2623:
2624:                if (status == null) {
2625:                    return STATUS_NOT_LOADED;
2626:                }
2627:
2628:                return status.intValue();
2629:            }
2630:
2631:            private synchronized void removeSession(SSOTokenID sid) {
2632:                sessionHash.remove(sid);
2633:                removeClientPort(sid.toString());
2634:            }
2635:
2636:            private synchronized void setStatus(String sid, int state) {
2637:                Integer status = (Integer) sessionHash.put(sid, new Integer(
2638:                        state));
2639:                if (status != null) {
2640:                    return;
2641:                }
2642:
2643:                try {
2644:                    SSOToken token = SSOTokenManager.getInstance()
2645:                            .createSSOToken(sid.toString());
2646:                    token.addSSOTokenListener(this );
2647:                } catch (SSOException e) {
2648:                    e.printStackTrace();
2649:                }
2650:
2651:            }
2652:
2653:            public void ssoTokenChanged(SSOTokenEvent se) {
2654:
2655:                try {
2656:                    int type = se.getType();
2657:                    removeSession(se.getToken().getTokenID());
2658:                } catch (SSOException ssoe) {
2659:                    // logger.severe("ssoTokenChanged() - SSOException : " + ssoe);
2660:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS053", ssoe);
2661:                }
2662:            }
2663:
2664:            void parsePacFile(NetletUser user) throws ServletException,
2665:                    IOException {
2666:                HttpServletResponse res = user.getRes();
2667:                PrintWriter out = res.getWriter();
2668:                res.setContentType("text/plain");
2669:                HttpServletRequest req = user.getReq();
2670:                String result = "FAILED";
2671:                try {
2672:                    String pacUrl = req.getParameter("PacFileUrl");
2673:                    String serverURL = req.getParameter("ServerURL");
2674:                    String pacFileBody = req.getParameter("PacFileBody");
2675:                    String clientIPAddr = req.getParameter("ClientIPAddr");
2676:                    // find the ip from the request Cookie
2677:                    Cookie[] cookieArr = req.getCookies();
2678:                    for (int i = 0; i < cookieArr.length; i++) {
2679:                        Cookie cookie = cookieArr[i];
2680:                        if (cookie.getName().equals("iPlanetUserId")) {
2681:                            String value = cookie.getValue();
2682:                            try {
2683:                                clientIPAddr = value.substring(0, value
2684:                                        .indexOf(":"));
2685:                            } catch (Exception ex) {
2686:                            }
2687:                        }
2688:                    }
2689:                    Enumeration e = req.getHeaderNames();
2690:                    while (e.hasMoreElements()) {
2691:                        String name = (String) e.nextElement();
2692:                    }
2693:                    // For netscape content-type: multipart/form-data
2694:                    String contentType = req.getContentType();
2695:                    if (contentType != null
2696:                            && contentType.indexOf("multipart/form-data") != -1) {
2697:                        pacFileBody = extractParameter(req, "PacFileBody");
2698:                    }
2699:
2700:                    Vector arguments = new Vector();
2701:                    arguments.add(serverURL);
2702:                    String host = "localhost";
2703:                    int indDoubleSlash = serverURL.indexOf("//");
2704:                    if (indDoubleSlash > -1) {
2705:                        int ind1 = serverURL.indexOf("/", indDoubleSlash + 2);
2706:                        int ind2 = serverURL.indexOf(":", indDoubleSlash + 2);
2707:                        if ((ind2 > -1) && (ind2 < ind1)) {
2708:                            host = serverURL
2709:                                    .substring(indDoubleSlash + 2, ind2);
2710:                        } else {
2711:                            host = serverURL
2712:                                    .substring(indDoubleSlash + 2, ind1);
2713:                        }
2714:                    }
2715:                    arguments.add(host);
2716:                    /*
2717:                     * //if we get the license to ship js.jar use the following EvalPAC
2718:                     * pacEval = EvalPAC.getInstance();
2719:                     * pacEval.setIPAddress(clientIPAddr); result=
2720:                     * pacEval.evaluate(pacFileBody,arguments) ;
2721:                     */
2722:                    try {
2723:                        Runtime rt = Runtime.getRuntime();
2724:
2725:                        String javaHome = System.getProperty("java.home",
2726:                                "/usr/java1.2/jre");
2727:                        String command = javaHome
2728:                                + "/bin/java com.sun.portal.netlet.servlet.EvalPAC "
2729:                                + URLEncoder.encode(pacFileBody) + " "
2730:                                + arguments.elementAt(0) + " "
2731:                                + arguments.elementAt(1) + " " + clientIPAddr;
2732:                        // ibm classpath problem
2733:                        Object obj = getServletContext()
2734:                                .getAttribute(
2735:                                        "com.ibm.websphere.servlet.application.classpath");
2736:                        String ibmAppClassPath = (obj == null) ? null : obj
2737:                                .toString();
2738:                        String classPath = System.getProperty(
2739:                                "java.class.path", ".");
2740:                        String env[] = new String[1];
2741:                        // env[0]=new
2742:                        // String("CLASSPATH=/opt/SUNWips/lib/js.jar:/opt/SUNWips/lib/ips_netlet.jar");
2743:                        if (ibmAppClassPath != null
2744:                                && ibmAppClassPath.trim().length() != 0)
2745:                            classPath = ibmAppClassPath;
2746:                        env[0] = new String("CLASSPATH=" + classPath);
2747:                        Process proc = rt.exec(command, env);
2748:                        DataInputStream in = new DataInputStream(proc
2749:                                .getInputStream());
2750:                        result = in.readLine();
2751:                        // logger.info("Proxy from PAC file -> " + result);
2752:                        Object[] params54 = { result };
2753:                        logger.log(Level.INFO, "PSSRNTLT_CSPNS054", params54);
2754:                    } catch (Exception ex) {
2755:                        // logger.log(Level.SEVERE, "Exception in processing PAC file:
2756:                        // ", ex);
2757:                        logger.log(Level.SEVERE, "PSSRNTLT_CSPNS055");
2758:                    }
2759:
2760:                } catch (Exception ex) {
2761:                    ex.printStackTrace();
2762:                }
2763:                out.println(result);
2764:                out.close();
2765:            }
2766:
2767:            public void redirectToPage(HttpServletResponse res, String stat,
2768:                    String val, String loc, String charset) {
2769:                StringBuffer outBuffer = new StringBuffer();
2770:                try {
2771:                    if ((charset != null) && (charset.trim().length() != 0)) {
2772:                        res.setContentType("text/html; charset=" + charset);
2773:                    } else {
2774:                        res.setContentType("text/html");
2775:                    }
2776:                    PrintWriter out = new PrintWriter(new BufferedWriter(
2777:                            new OutputStreamWriter(res.getOutputStream(),
2778:                                    charset)));
2779:                    java.util.ResourceBundle bundle = null;
2780:                    /*
2781:                     * If you donot have a valid session then use the default locale.
2782:                     */
2783:                    if ((loc == null) || (loc.trim().length() == 0)) {
2784:                        loc = SystemProperties.get("com.iplanet.am.locale",
2785:                                "en_US");
2786:                        bundle = ResourceBundle.getBundle(
2787:                                NetletConstants.NETLET_SERVLET_RES_BUNDLE,
2788:                                com.iplanet.am.util.Locale.getLocale(loc));
2789:                    } else {
2790:                        bundle = ResourceBundle.getBundle(
2791:                                NetletConstants.NETLET_SERVLET_RES_BUNDLE,
2792:                                com.iplanet.am.util.Locale.getLocale(loc));
2793:
2794:                    }
2795:                    outBuffer.append("<html>\n");
2796:                    outBuffer.append("<BODY TEXT=\"").append(
2797:                            bundle.getString("ntxcolor"));
2798:                    outBuffer.append("\" BGCOLOR=\"").append(
2799:                            bundle.getString("nbgcolor")).append("\">\n");
2800:                    outBuffer.append("<p>").append(bundle.getString(stat));
2801:                    if (val != null && val.trim().length() != 0) {
2802:                        outBuffer.append(val);
2803:                    }
2804:                    outBuffer.append("</body>\n");
2805:                    outBuffer.append("</html>\n");
2806:                    out.print(outBuffer.toString());
2807:                    out.close();
2808:                } catch (IOException ioe) {
2809:                    // logger.severe("Error redirecting to session invalid page." +
2810:                    // ioe);
2811:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS058", ioe);
2812:                }
2813:            }
2814:
2815:            public void storeProxySettings(NetletUser nu) {
2816:                HttpServletRequest req = nu.getReq();
2817:                UserAttributes attrs = nu.getNetletUserAttributes();
2818:                try {
2819:                    attrs.setString(NetletConstants.NETLET_PROXY_TYPE, req
2820:                            .getParameter("proxytype"));
2821:                    attrs.setString(NetletConstants.NETLET_PROXY_HOST, req
2822:                            .getParameter("proxyhost"));
2823:                    attrs.setString(NetletConstants.NETLET_PROXY_PORT, req
2824:                            .getParameter("proxyport"));
2825:                    attrs.setString(NetletConstants.NETLET_PROXY_OVERRIDE, req
2826:                            .getParameter("proxyoverride"));
2827:                } catch (Exception e) {
2828:                    // logger.severe("Exception in setting attribute: " + e);
2829:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS059", e);
2830:                }
2831:                nu.setNetletUserAttributes(attrs); // Update the local copy
2832:                // Send some output to the client to prevent FileNotFound exception in
2833:                // the client side
2834:                HttpServletResponse res = nu.getRes();
2835:                try {
2836:                    PrintWriter out = res.getWriter();
2837:                    out.println("");
2838:                    out.close();
2839:                } catch (IOException ioe) {
2840:                    // logger.severe("Exception in sending respose : " + ioe);
2841:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS060", ioe);
2842:                }
2843:            }
2844:
2845:            public void doReauth(NetletUser nu) {
2846:                HttpServletRequest req = nu.getReq();
2847:                String password = req.getParameter("password");
2848:                // For netscape content-type: multipart/form-data
2849:                String contentType = req.getContentType();
2850:                if (contentType != null
2851:                        && contentType.indexOf("multipart/form-data") != -1) {
2852:                    // open input stream from client to capture upload file
2853:                    password = extractParameter(req, "password");
2854:                }
2855:                String result = verifyPassword(nu, password);
2856:                writeResult(nu, result);
2857:            }
2858:
2859:            public String verifyPassword(NetletUser nu, String password) {
2860:                if (password == null || password.trim().length() == 0) {
2861:                    return "FAILED";
2862:                }
2863:                UserAttributes attrs = nu.getNetletUserAttributes();
2864:                String actualPassword = attrs.getString(
2865:                        NetletConstants.NETLET_PASSWORD,
2866:                        NetletConstants.NETLET_DEFAULT_PASSWORD);
2867:                //this validation should happen inside the method UserAttributes:getString()
2868:                //but that method checks only for 'null' value, not empty value. hence
2869:                //revalidation the password value here.. it's not a permanent fix, but
2870:                //just a stop-gap measure for now.
2871:                if (actualPassword == null
2872:                        || actualPassword.trim().length() == 0)
2873:                    actualPassword = NetletConstants.NETLET_DEFAULT_PASSWORD;
2874:
2875:                return (actualPassword.equals(password)) ? "SUCCESS" : "FAILED";
2876:            }
2877:
2878:            public void writeResult(NetletUser nu, String result) {
2879:                HttpServletResponse res = nu.getRes();
2880:                try {
2881:                    PrintWriter out = res.getWriter();
2882:                    out.println(result);
2883:                    out.close();
2884:                } catch (IOException ioe) {
2885:                    // logger.severe("Exception in sending respose : " + ioe);
2886:                    logger.log(Level.SEVERE, "PSSRNTLT_CSPNS061", ioe);
2887:                }
2888:            }
2889:
2890:            public String extractParameter(HttpServletRequest req,
2891:                    String paramName) {
2892:                HashMap reqList = new HashMap();
2893:                try {
2894:                    DataInputStream in = new DataInputStream(req
2895:                            .getInputStream());
2896:                    // get length of content data
2897:                    int formDataLength = req.getContentLength();
2898:
2899:                    // allocate a byte array to store content data
2900:                    byte dataBytes[] = new byte[formDataLength];
2901:
2902:                    in.readFully(dataBytes);
2903:
2904:                    // create string from byte array for easy manipulation
2905:                    String file = new String(dataBytes, "ISO-8859-1");
2906:                    dataBytes = null;
2907:
2908:                    StringTokenizer strTok = new StringTokenizer(file, "&");
2909:                    while (strTok.hasMoreTokens()) {
2910:                        String token = strTok.nextToken();
2911:                        int ind = token.indexOf("=");
2912:                        if (ind > -1) {
2913:                            String key = token.substring(0, ind);
2914:                            String value = token.substring(ind + 1);
2915:                            reqList.put(key, value);
2916:                        }
2917:                    }
2918:                } catch (IOException ioe) {
2919:                    return null;
2920:                }
2921:                return (URLDecoder.decode((reqList.get(paramName)).toString()));
2922:            }
2923:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.