Source Code Cross Referenced for ProxyletServlet.java in  » Portal » Open-Portal » com » sun » portal » proxylet » 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.proxylet.servlet 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        package com.sun.portal.proxylet.servlet;
0002:
0003:        import com.sun.portal.proxylet.util.SSOUtil;
0004:        import com.sun.portal.proxylet.util.ProxyletConstants;
0005:        import com.sun.portal.proxylet.util.ProxyletUtil;
0006:        import com.sun.portal.proxylet.util.UserAttributes;
0007:        import com.iplanet.sso.*;
0008:
0009:        import java.io.*;
0010:        import java.net.*;
0011:        import java.util.Enumeration;
0012:        import java.util.*;
0013:        import java.util.logging.Logger;
0014:        import javax.servlet.ServletException;
0015:        import javax.servlet.http.HttpServlet;
0016:        import javax.servlet.http.HttpServletRequest;
0017:        import javax.servlet.http.HttpServletResponse;
0018:        import com.sun.portal.log.common.*;
0019:        import com.sun.portal.util.ResourceLoader;
0020:
0021:        public class ProxyletServlet extends HttpServlet implements 
0022:                ProxyletConstants, SSOTokenListener {
0023:            private static Logger logger = null;
0024:            private ClientInfo ci = null;
0025:            private Hashtable sessionHash = new Hashtable();
0026:
0027:            private final int STATUS_LOADED = 1;
0028:            private final int STATUS_UNLOADED = 2;
0029:
0030:            public static final String UNKNOWN = "unknown";
0031:
0032:            public ProxyletServlet() {
0033:                logger = PortalLogger.getLogger(ProxyletServlet.class);
0034:            }
0035:
0036:            /**
0037:             * doGet
0038:             *
0039:             *      This function overrides the HttpServlet's doGet method.
0040:             *      It inteprets the various commands and handles them
0041:             *      appropriately.
0042:             */
0043:            public void doGet(HttpServletRequest req, HttpServletResponse res)
0044:                    throws ServletException, IOException {
0045:                try {
0046:                    SSOToken ssoTok = null;
0047:                    String sid = null;
0048:
0049:                    ClientInfo.setLogger(logger);
0050:                    ci = new ClientInfo(req);
0051:                    SSOUtil ssoUtil = new SSOUtil(req);
0052:                    logger.info(" Inside doGet");
0053:
0054:                    ssoTok = ci.getSSOToken();
0055:                    sid = new String(ssoTok.getTokenID().toString());
0056:                    if (!((SSOTokenManager.getInstance()).isValidToken(ssoTok))) {
0057:                        res.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
0058:                        logger.info("Invalid sso token");
0059:                        return;
0060:                    }
0061:
0062:                    //
0063:                    // Find the requested command
0064:                    //
0065:                    String command = req.getParameter("command");
0066:
0067:                    logger.info(" Command " + command);
0068:
0069:                    if (command.equals("loadProxylet")) {
0070:                        serveTopFrame(req, res, ci, ssoUtil);
0071:                    } else if (command.equals("loadApplet")) {
0072:                        serveAppletFrame(req, res, ci, ssoUtil);
0073:                    } else if (command.equals("loadDownloadMgr")) {
0074:                        serveDownloadMgr(req, res, ci, ssoUtil);
0075:                    } else if (command.equals("loadDownloadMgrLite")) {
0076:                        serveDownloadMgrLite(req, res, ci, ssoUtil);
0077:                    } else if (command.equals("parsePacFile")) {
0078:                        parsePacFile(req, res);
0079:                    } else if (command.equals("loadResourceBundle")) {
0080:                        serveResourceBundle(req, res, ci);
0081:                    } else if (command.equals("loadJWSApp")) {
0082:                        serveApp(req, res, ci, sid, "loadProxletJNLPFile");
0083:                    } else if (command.equals("loadApp")) {
0084:                        serveApp(req, res, ci, sid, "loadProxylet");
0085:                    } else if (command.equals("loadProxletJNLPFile")) {
0086:                        serveJnlpFile(req, res, ci);
0087:                    } else if (command.equals("setJWSLoaded")
0088:                            || command.equals("setAppletLoaded")) {
0089:                        setStatus(sid, STATUS_LOADED);
0090:                        res.setStatus(HttpServletResponse.SC_OK);
0091:                        try {
0092:                            ssoTok.setProperty("ClientStatus", "LOADED");
0093:                        } catch (SSOException ex) {
0094:                            logger.info("Error setting session " + ex);
0095:                        }
0096:                        return;
0097:                    } else if (command.equals("setJWSUnLoaded")
0098:                            || command.equals("setAppletUnLoaded")) {
0099:
0100:                        setStatus(sid, STATUS_UNLOADED);
0101:                        res.setStatus(HttpServletResponse.SC_OK);
0102:                        try {
0103:                            ssoTok.setProperty("ClientStatus", "UNLOADED");
0104:                        } catch (SSOException ex) {
0105:                            logger.info("Error setting session " + ex);
0106:                        }
0107:                        return;
0108:                    } else if (command.equals("getPacfile")) {
0109:                        servePacFile(req, res, ci);
0110:                    } else if (command.equals("validatesession")) {
0111:                        res.setStatus(HttpServletResponse.SC_OK);
0112:                        return;
0113:                    }
0114:
0115:                } catch (Exception e) {
0116:                    redirectToPage(res, e.getMessage(), null, ci.getLocale(),
0117:                            ci.getHTMLcharsetname());
0118:                    return;
0119:                }
0120:
0121:            }
0122:
0123:            public void doPost(HttpServletRequest req, HttpServletResponse res)
0124:                    throws ServletException, IOException {
0125:                doGet(req, res);
0126:            }
0127:
0128:            /**
0129:             * serveTopFrame
0130:             *
0131:             * This function serves the page that contains the frameset
0132:             */
0133:            private void serveTopFrame(HttpServletRequest req,
0134:                    HttpServletResponse resp, ClientInfo ci, SSOUtil ssoUtil)
0135:                    throws Exception {
0136:                logger.info("Inside serveTopFrame");
0137:
0138:                String agent = req.getHeader("user-agent");
0139:                String cookie = req.getHeader("Cookie");
0140:
0141:                logger.info("suffix " + getSuffix(agent));
0142:                Template topFrame = new Template(getTemplateDir() + "frameset_"
0143:                        + getSuffix(agent) + ".html");
0144:
0145:                substituteCommanParameters(topFrame, req, ci);
0146:
0147:                String downloadURL = formatURLForNextRequest("loadDownloadMgr",
0148:                        req);
0149:                String appletURL = formatURLForNextRequest("loadApplet", req);
0150:                String appletProgressMsg = ssoUtil.getResourceBundle(
0151:                        PROXYLET_SERVLET_RES_BUNDLE).getString(
0152:                        "appletProgressMesg");
0153:
0154:                downloadURL = downloadURL + "&COOKIE=" + cookie;
0155:
0156:                appletURL = appletURL + "&COOKIE=" + cookie;
0157:
0158:                topFrame.set("$DOWNLOAD_URL", downloadURL);
0159:                topFrame.set("$APPLET_URL", appletURL);
0160:                topFrame.set("$APPLET_PROGRESS_MESG", appletProgressMsg);
0161:
0162:                renderPage(topFrame, resp);
0163:
0164:            }
0165:
0166:            /**
0167:             * serveDownloadMgr
0168:             *
0169:             * This page downloads a downloadMgr applet, which would download the
0170:             * real applet and signed script. This is provided as a workaround for
0171:             * JAR URL problem in Netscape.
0172:             *
0173:             * In Mozilla, the only way to download secure script is to through JAR
0174:             * URL. But, Mozilla is not able to resolve HTTPs URL eg JAR:HTTPS..
0175:             * does not work, while JAR:http works.
0176:             *
0177:             * Therefore, we run an other applet that runs on particular port and downloads
0178:             * the secure script as jar:http://localhost:port/....etc
0179:             */
0180:
0181:            private void serveDownloadMgr(HttpServletRequest req,
0182:                    HttpServletResponse resp, ClientInfo ci, SSOUtil ssoUtil)
0183:                    throws Exception {
0184:                logger.info("Inside serveDownloadMgr");
0185:                String agent = req.getHeader("user-agent");
0186:
0187:                Template appletPage = new Template(getTemplateDir()
0188:                        + "downloadmgr_" + getSuffix(agent) + ".html");
0189:                appletPage.set("$APPLET_PROGRESS_MESG", ssoUtil
0190:                        .getResourceBundle(PROXYLET_SERVLET_RES_BUNDLE)
0191:                        .getString("appletProgressMesg"));
0192:                substituteCommanParameters(appletPage, req, ci);
0193:
0194:                logger.info("Render downloadmgr Page");
0195:                renderPage(appletPage, resp);
0196:            }
0197:
0198:            /**
0199:             * serveDownloadMgrLite
0200:             *
0201:             * This page downloads the DownloadManagerLite applet, which would extract
0202:             * the files requested by the browser - 'proxyletCommandListener.html'
0203:             * and 'proxyletscripts.jar'.
0204:             */
0205:            private void serveDownloadMgrLite(HttpServletRequest req,
0206:                    HttpServletResponse resp, ClientInfo ci, SSOUtil ssoUtil)
0207:                    throws Exception {
0208:                logger.info("Inside serveDownloadMgrLite");
0209:
0210:                Template appletPage = new Template(getTemplateDir()
0211:                        + "downloadmgrlite.html");
0212:                substituteCommanParameters(appletPage, req, ci);
0213:
0214:                logger.info("Render downloadmgrlite Page");
0215:                renderPage(appletPage, resp);
0216:            }
0217:
0218:            /**
0219:             * serveAppletFrame
0220:             *
0221:             * This function serves the page that contains the Applet
0222:             * tag. The page contains script code that would
0223:             * download the archive files based on the client JVM
0224:             * version and browser type.
0225:             */
0226:            private void serveAppletFrame(HttpServletRequest req,
0227:                    HttpServletResponse resp, ClientInfo ci, SSOUtil ssoUtil)
0228:                    throws Exception {
0229:                logger.info("Inside serveAppletFrame");
0230:                String agent = req.getHeader("user-agent");
0231:                String gwURL = req.getHeader("PS-GW-Rewriting-URL");
0232:
0233:                Template appletPage = new Template(getTemplateDir() + "applet_"
0234:                        + getSuffix(agent) + ".html");
0235:
0236:                System.out.println("******************");
0237:                System.out.println("appletPage = " + appletPage.render());
0238:
0239:                appletPage.set("$APPLET_PROGRESS_MESG", ssoUtil
0240:                        .getResourceBundle(PROXYLET_SERVLET_RES_BUNDLE)
0241:                        .getString("appletProgressMesg"));
0242:
0243:                System.out.println("message = "
0244:                        + ssoUtil
0245:                                .getResourceBundle(PROXYLET_SERVLET_RES_BUNDLE)
0246:                                .getString("appletProgressMesg"));
0247:                System.out.println("appletPage = " + appletPage.render());
0248:
0249:                System.out.println("******************");
0250:
0251:                substituteCommanParameters(appletPage, req, ci);
0252:
0253:                logger.info("Render Applet Frame Page");
0254:                renderPage(appletPage, resp);
0255:            }
0256:
0257:            /**
0258:             * parsePacFile
0259:             *
0260:             * This function parses the pacfile content and extracts the proxy host and port
0261:             * for gateway address, and sends this to the applet.
0262:             *
0263:             * Function looks up the request object for the following parameters
0264:             *
0265:             * pacfileurl : This parameter is the actual PAC file url that was configured in
0266:             *              the client browser.
0267:             * pacfilebody: This parameter is the actual content of the PAC file as read by
0268:             *              the applet
0269:             * serverurl  : This is the URL of the gateway server. This will be used as a
0270:             *              parameter to execute the script
0271:             * clientIP   : The IP address of the applet client.
0272:             */
0273:            private void parsePacFile(HttpServletRequest req,
0274:                    HttpServletResponse resp) throws Exception {
0275:                logger.info(" Enter parsepacfile ");
0276:                resp.setContentType("text/plain");
0277:                PrintWriter respOut = resp.getWriter();
0278:                //
0279:                // Retrive parameters from Query string
0280:                //
0281:                String serverURL = req.getParameter("serverURL");
0282:                String clientIP = req.getParameter("clientIP");
0283:                logger.info(" serverURL  " + serverURL + " " + "clientIP "
0284:                        + clientIP);
0285:                //
0286:                // Retrive pacfile content from the posted data
0287:                //
0288:                String contentType = req.getContentType();
0289:                logger.info("contentType " + contentType);
0290:                String pacFileBody;
0291:                if (contentType != null
0292:                        && contentType.indexOf("multipart/form-data") != -1) {
0293:                    MultipartRequest mreq = new MultipartRequest(req);
0294:                    pacFileBody = mreq.getMultipartHeader("PacFileBody");
0295:                    logger.info(" multipartrequest " + mreq);
0296:                } else {
0297:                    //W'll take a chance
0298:                    pacFileBody = req.getParameter("PacFileBody");
0299:                    logger.info(" query string pacFileBody " + pacFileBody);
0300:                }
0301:                //
0302:                // If content is empty, proceed no further
0303:                //
0304:                if (pacFileBody == null || pacFileBody.equals("")) {
0305:                    //
0306:                    // Send response as DIRECT
0307:                    //
0308:                    logger.info(" DIRECT ");
0309:                    respOut.println("DIRECT");
0310:                    respOut.close();
0311:                    return;
0312:                }
0313:                //
0314:                // Parse the FindProxyURL in the PAC file content using Rhino jars,
0315:                // and extract the host and port for gateway address
0316:                //
0317:                //
0318:                // Find out the host parameter from serverURL
0319:                //
0320:                int indDoubleSlash = serverURL.indexOf("//");
0321:                int indEnd = 0;
0322:                String host = null;
0323:                if (indDoubleSlash != -1) {
0324:                    indEnd = serverURL.indexOf(":", indDoubleSlash + 2);
0325:                    if (indEnd == -1)
0326:                        indEnd = serverURL.indexOf("/", indDoubleSlash + 2);
0327:                    if (indEnd == -1)
0328:                        indEnd = serverURL.length();
0329:
0330:                    host = serverURL.substring(indDoubleSlash + 2, indEnd);
0331:                    logger.info(" host " + host);
0332:                }
0333:                try {
0334:                    PacScriptEvaluator pacEval = new PacScriptEvaluator();
0335:                    pacEval.setMyIpAddress(clientIP);
0336:                    String result = pacEval.evaluate(pacFileBody, serverURL,
0337:                            host);
0338:                    if (result == null || result.equalsIgnoreCase("null"))
0339:                        result = "DIRECT";
0340:                    logger.info(" RESULT " + result);
0341:                    respOut.println(result);
0342:                    respOut.flush();
0343:                    respOut.close();
0344:                } catch (Exception ignore) {
0345:
0346:                    logger.info(ignore.getMessage());
0347:                    ignore.printStackTrace();
0348:                    respOut.println("DIRECT");
0349:                    respOut.close();
0350:                    return;
0351:                }
0352:
0353:            }
0354:
0355:            /**
0356:             * serveResourceBundle
0357:             *
0358:             * This function serves the resource file contents containing
0359:             * parameterized messages
0360:             */
0361:            private void serveResourceBundle(HttpServletRequest req,
0362:                    HttpServletResponse resp, ClientInfo ci) throws Exception {
0363:
0364:                PrintWriter out = resp.getWriter();
0365:                resp.setContentType("text/plain");
0366:
0367:                String propertyfile = req.getParameter("propertyfile");
0368:                logger.info("propertyfile " + propertyfile);
0369:                ResourceBundle rb = null;
0370:                if (propertyfile == null)
0371:                    rb = ci.getAppletBundle();
0372:                else {
0373:                    if (propertyfile.indexOf("http") != -1) {
0374:                        try {
0375:                            URL u = new URL(propertyfile);
0376:                            HttpURLConnection huc = (HttpURLConnection) u
0377:                                    .openConnection();
0378:                            // set follow redirects. the default is set, just want to make sure
0379:                            huc.setFollowRedirects(true);
0380:                            huc.setRequestMethod("GET");
0381:                            huc.connect();
0382:
0383:                            int code = huc.getResponseCode();
0384:
0385:                            if (code >= 200 && code < 300) {
0386:                                // has the contents
0387:                                //Get the input stream from the connection object
0388:                                BufferedReader inStream = new BufferedReader(
0389:                                        new InputStreamReader(huc
0390:                                                .getInputStream()));
0391:
0392:                                String response = "";
0393:                                StringBuffer resourcestrings = new StringBuffer();
0394:                                // get the proxy pac file
0395:                                while ((response = inStream.readLine()) != null) {
0396:                                    resourcestrings.append(response + "\n");
0397:                                }
0398:
0399:                                ByteArrayInputStream bis = new ByteArrayInputStream(
0400:                                        (resourcestrings.toString()).getBytes());
0401:                                rb = new PropertyResourceBundle(bis);
0402:
0403:                            } else {
0404:                                rb = null;
0405:                            }
0406:                            huc.disconnect();
0407:
0408:                        } catch (Exception e) {
0409:                        }
0410:                    }
0411:                }
0412:
0413:                logger.info("resourcebundle " + rb);
0414:                if (rb != null) {
0415:                    for (Enumeration e = rb.getKeys(); e.hasMoreElements();) {
0416:                        String key = (String) e.nextElement();
0417:                        String value = rb.getString(key);
0418:                        out.println(key + "=" + encodeJavaString(value));
0419:                        logger.info(key + "=" + value);
0420:                    }
0421:                }
0422:
0423:                out.flush();
0424:                out.close();
0425:            }
0426:
0427:            /**
0428:             * serveJWSApp
0429:             *
0430:             * This function sends a redirect respose to download JNLP file or redirect to
0431:             * the application URL based on the state of JWS download.
0432:             * If java webstart proxylet is already downloaded to user's machine, this redirects
0433:             * the request to application URL. Otherwise, to JNLP file.
0434:             *
0435:             * @param req
0436:             * @param res
0437:             * @param ci
0438:             * @param sid
0439:             * @param command
0440:             * @throws Exception
0441:             */
0442:            private void serveApp(HttpServletRequest req,
0443:                    HttpServletResponse res, ClientInfo ci, String sid,
0444:                    String command) throws Exception {
0445:                Template appURL;
0446:                boolean automaticdownload = false;
0447:                try {
0448:                    // retrive app url from query string
0449:                    String followUp = req.getParameter(FOLLOWUP_PARAM).trim();
0450:                    String portalUrl = req.getParameter(PROXYLET_PORTAL_URL)
0451:                            .trim();
0452:                    String referer = req.getHeader("Referer");
0453:                    logger.info("followUP app url " + followUp);
0454:
0455:                    // check if JWS is already downloaded to machine
0456:                    int status = getStatus(sid);
0457:                    logger.info("Status " + status);
0458:
0459:                    if (followUp.equalsIgnoreCase("NOURL"))
0460:                        automaticdownload = true;
0461:                    logger.info("Autodowownload set to  " + automaticdownload);
0462:
0463:                    if (status == STATUS_UNLOADED) {
0464:                        String appurlFile = "";
0465:                        if (command.equalsIgnoreCase("loadProxylet")) {
0466:                            appurlFile = "launchApplet.html";
0467:                            appURL = new Template(getTemplateDir() + appurlFile);
0468:                            appURL.set("$COMMAND", command);
0469:
0470:                            substituteCommanParameters(appURL, req, ci);
0471:                        } else if (command
0472:                                .equalsIgnoreCase("loadProxletJNLPFile")) {
0473:                            String osType = req.getParameter("os_type");
0474:                            if (osType.equals("windows"))
0475:                                appurlFile = "launchJWS_winOS.html";
0476:                            else
0477:                                appurlFile = "launchJWS_nonWinOS.html";
0478:
0479:                            // create template to load JWS & app url
0480:                            Template script = new Template(getTemplateDir()
0481:                                    + "jwsScript.html");
0482:                            script.set("$COMMAND", command);
0483:
0484:                            appURL = new Template(getTemplateDir() + appurlFile);
0485:                            substituteCommanParameters(appURL, req, ci);
0486:                            substituteCommanParameters(script, req, ci);
0487:
0488:                            String temp = script.render();
0489:                            appURL.set("$SCRIPT", temp);
0490:                        } else {
0491:                            throw new IllegalArgumentException("command '"
0492:                                    + command + "' is not supported");
0493:                        }
0494:
0495:                        if (automaticdownload) {
0496:                            appURL.set("$followUp", portalUrl);
0497:                            followUp = portalUrl;
0498:                        } else
0499:                            appURL.set("$followUp", followUp);
0500:                    } else {
0501:                        logger.info("Proxylet already loaded in client ");
0502:
0503:                        // create template to load the app url
0504:                        appURL = new Template(getTemplateDir()
0505:                                + "launchApplication.html");
0506:                        appURL.set("$followUp", followUp);
0507:                    }
0508:
0509:                    if (followUp != null
0510:                            && followUp.equalsIgnoreCase(portalUrl))
0511:                        appURL.set("$REFRESHPARENT", "true");
0512:                    else if (referer != null && followUp != null
0513:                            && referer.equalsIgnoreCase(followUp))
0514:                        appURL.set("$REFRESHPARENT", "true");
0515:                    else
0516:                        appURL.set("$REFRESHPARENT", "false");
0517:
0518:                    if (command.equals("loadProxletJNLPFile"))
0519:                        appURL.set("$APP", "application");
0520:                    else
0521:                        appURL.set("$APP", "applet");
0522:
0523:                    if (automaticdownload)
0524:                        appURL.set("$AUTODOWNLOAD", "true");
0525:                    else
0526:                        appURL.set("$AUTODOWNLOAD", "false");
0527:
0528:                    renderPage(appURL, res);
0529:                    res.flushBuffer();
0530:                } catch (Exception e) {
0531:                    logger.info(e.getMessage());
0532:                }
0533:            }
0534:
0535:            private void serveJnlpFile(HttpServletRequest req,
0536:                    HttpServletResponse res, ClientInfo ci) throws Exception {
0537:
0538:                logger.info("serveJnlpfile");
0539:                String filePath = getTemplateDir() + "proxylet.jnlp";
0540:                logger.info("file path jnlp" + filePath);
0541:                Template jnlppage = new Template(filePath);
0542:                //get browser
0543:                String agent = req.getHeader("user-agent");
0544:                jnlppage.set("$BROWSER", getSuffix(agent));
0545:
0546:                substituteCommanParameters(jnlppage, req, ci);
0547:                res.setContentType("application/x-java-jnlp-file");
0548:                String page = jnlppage.render();
0549:                res.setContentLength(page.length());
0550:                res.addDateHeader("Date", Calendar.getInstance().getTime()
0551:                        .getTime());
0552:                res.addDateHeader("Last-Modified", Calendar.getInstance()
0553:                        .getTime().getTime());
0554:                res.setHeader("Pragma", "no-cache");
0555:                res.setHeader("Cache-Control",
0556:                        "no-store, no-cache, must-revalidate, max-age=0");
0557:
0558:                PrintWriter out = res.getWriter();
0559:                out.print(page);
0560:                out.flush();
0561:                out.close();
0562:
0563:                res.flushBuffer();
0564:                logger.info("end of serveJWS page");
0565:
0566:            }
0567:
0568:            /**
0569:             * This function reads the pac file from the given pacfile location and
0570:             * sends the output to client
0571:             * @param req
0572:             * @param res
0573:             * @param ci
0574:             * @throws Exception
0575:             */
0576:
0577:            private void servePacFile(HttpServletRequest req,
0578:                    HttpServletResponse res, ClientInfo ci) throws Exception {
0579:                // get pacfile location
0580:                String pacLocation = ci.getPacLocation();
0581:                if (pacLocation == null) {
0582:                    res.setStatus(HttpServletResponse.SC_NO_CONTENT);
0583:                    return;
0584:                }
0585:
0586:                if (pacLocation.indexOf("http") != -1) {
0587:                    StringBuffer proxysettings = new StringBuffer();
0588:                    URL u = new URL(pacLocation);
0589:                    HttpURLConnection huc = (HttpURLConnection) u
0590:                            .openConnection();
0591:                    // set follow redirects. the default is set, just want to make sure
0592:                    huc.setFollowRedirects(true);
0593:                    huc.setRequestMethod("GET");
0594:                    huc.connect();
0595:
0596:                    int code = huc.getResponseCode();
0597:
0598:                    if (code >= 200 && code < 300) {
0599:                        // has the contents
0600:                        //Get the input stream from the connection object
0601:                        BufferedReader inStream = new BufferedReader(
0602:                                new InputStreamReader(huc.getInputStream()));
0603:
0604:                        String response = "";
0605:                        // get the proxy pac file
0606:                        while ((response = inStream.readLine()) != null) {
0607:                            proxysettings.append(response + "\n");
0608:                        }
0609:
0610:                    } else {
0611:                        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
0612:                        return;
0613:                    }
0614:                    huc.disconnect();
0615:                    renderPage(proxysettings.toString(), res);
0616:                } else {
0617:
0618:                    Template pacfile;
0619:                    // create pacfile template
0620:                    try {
0621:                        pacfile = new Template(pacLocation);
0622:                    } catch (Exception e) {
0623:                        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
0624:                        return;
0625:                    }
0626:                    // if things are fine, send the file to client
0627:                    renderPage(pacfile, res);
0628:
0629:                }
0630:
0631:                return;
0632:            }
0633:
0634:            /**
0635:             * ========= ========== Utility functions ========= ===========
0636:             */
0637:
0638:            private void  substituteCommanParameters(Template template, HttpServletRequest req, ClientInfo ci )
0639:    {
0640:
0641:        String servletPath= getServletPath(req);
0642:        String gwURL           = req.getHeader("PS-GW-Rewriting-URL");
0643:        String followUp        = req.getParameter(FOLLOWUP_PARAM);
0644:
0645:        String clientIP        = req.getParameter("hostname");
0646:        String propertyfile = req.getParameter(CUSTOMIZED_PROP_FILE);
0647:
0648:        Enumeration enum = req.getHeaderNames();
0649:        while (enum.hasMoreElements()) {
0650:            String name = (String)enum.nextElement();
0651:            String val = req.getHeader(name);
0652:            logger.info(name + "=" + val);
0653:        }
0654:
0655:
0656:        logger.info("Client host name " + clientIP );
0657:
0658:        //
0659:        //  CODEBASE - used by the applet to locale the jars
0660:        //
0661:        String codebase = gwURL +  servletPath ;
0662:        template.set("$CODEBASE", codebase );
0663:        logger.info("codebase " + codebase);
0664:        logger.info("gwurl " + gwURL);
0665:
0666:        //
0667:        //  GW_HOST - used by the applet to communicate with gateway
0668:        //  GW_PORT
0669:        //  GW_MODE
0670:        //
0671:        String gwHost  = gwURL.substring( gwURL.indexOf("//") +2, gwURL.length() );
0672:        String gwPort = "-1";
0673:        String gwMode = "";
0674:        String sesId = "";
0675:        int index = gwHost.indexOf("/");
0676:        if (-1 != index) {
0677:            sesId = gwHost.substring(index+1,gwHost.length());
0678:            gwHost = gwHost.substring(0, index);
0679:        }
0680:        index = gwHost.indexOf(":");
0681:        logger.info("Gateway url: "+ gwURL);
0682:
0683:        if ( index != -1)
0684:        {
0685:            gwPort = gwHost.substring(index+1, gwHost.length());
0686:            gwHost = gwHost.substring(0, index );
0687:        }
0688:        else
0689:        {
0690:            if( gwURL.indexOf("https") != -1 )
0691:                gwPort= "443";
0692:            else
0693:                gwPort= "80";
0694:        }
0695:
0696:        if (gwHost.endsWith("/") )
0697:            gwHost = gwHost.substring(0, gwHost.length() -1 );
0698:
0699:        if (gwPort.endsWith("/") )
0700:            gwPort = gwPort.substring(0, gwPort.length() -1 );
0701:
0702:        if( gwURL.indexOf("https") != -1 )
0703:            gwMode = "secure";
0704:        else
0705:            gwMode = "non-secure";
0706:
0707:        template.set("$GW_HOST", gwHost );
0708:        template.set("$GW_PORT", gwPort );
0709:        template.set("$GW_MODE", gwMode );
0710:
0711:        // In case of cookieless we need to rewrite the url
0712:        template.set("$SESSION_ID", sesId );
0713:
0714:        //
0715:        //  COOKIE - Used to verify the authentication
0716:        //
0717:        String cookie   = req.getHeader("Cookie");
0718:        template.set("$COOKIE", cookie );
0719:
0720:        //
0721:        //  SERVLET_URL - used by the applet to dynamically construct URLs to fetch resources
0722:        //  GW_URL
0723:        //
0724:        template.set("$SERVLET_URL", servletPath );
0725:        template.set("$GW_URL", gwURL );
0726:
0727:        //
0728:        //  NAME - name to uniquely identify the gateway instance
0729:        //
0730:        String name ="";
0731:        index = gwHost.indexOf(".");
0732:        if (index != -1 )
0733:            name= gwHost.substring(0, index);
0734:
0735:        if( name != null || name != "" )
0736:        {
0737:            name = convertascii(name);
0738:        }
0739:
0740:        template.set("$NAME", name );
0741:
0742:        //
0743:        //  FOLLOWUP -  URL to redirect the user after the applet finishes downloading.
0744:        //           -  This is applicable only for autodownloads
0745:        //
0746:        template.set("$FOLLOWUP", followUp );
0747:
0748:        template.set("$HOSTNAME", clientIP );
0749:
0750:        //
0751:        // Retrive User specified port and IP address
0752:        //
0753:        template.set("$BINDIP", ci.getBindIP() );
0754:        template.set("$BINDPPORT", ci.getBindPort() );
0755:
0756:        template.set("$DOWNLOAD_MGR_PORT", DOWNLOAD_MANAGER_PORT);
0757:
0758:
0759:
0760:        // Add rules only if Pac file is not configured
0761:        if( ci.getPacLocation() == null || ci.getPacLocation().equals(""))
0762:            template.set("$RULES", getRules(req));
0763:
0764:        // set platform config URL
0765:        template.set("$platformloginurl", ci.getPlatformLoginURL() );
0766:        logger.info("sessionIdle timeout " + ci.getSessionIdleTimeout() );
0767:        template.set("$sessionIdleTimeout", new Integer(ci.getSessionIdleTimeout() ).toString());
0768:
0769:        // set customized property filename
0770:        if( propertyfile != null ) {
0771:            propertyfile = propertyfile.trim();
0772:            template.set("$PROPERTY_FILE", propertyfile);
0773:        }
0774:        logger.info("End of substitutecommandparameters" );
0775:    }
0776:
0777:            private String formatURLForNextRequest(String command,
0778:                    HttpServletRequest req) {
0779:                String servletPath = getServletPath(req);
0780:
0781:                servletPath = servletPath + "?command=" + command;
0782:                logger.info("formatURLForNext Request " + servletPath);
0783:                return servletPath;
0784:            }
0785:
0786:            public String getDynamicUrl() {
0787:                try {
0788:                    return getServletConfig().getServletContext()
0789:                            .getInitParameter("dynamicContext");
0790:                } catch (NullPointerException npe) {
0791:                    return (new String("/ips"));
0792:                }
0793:            }
0794:
0795:            public String getStaticUrl() {
0796:                try {
0797:                    return getServletConfig().getServletContext()
0798:                            .getInitParameter("staticContext");
0799:                } catch (NullPointerException npe) {
0800:                    return (new String("/ips-static"));
0801:                }
0802:            }
0803:
0804:            public String getTemplateDir() {
0805:                try {
0806:                    // fix for bug # 6333648
0807:                    //            String filePath = ResourceLoader.getInstance(System.getProperties()).
0808:                    //                    getProperties("PSConfig.properties").getProperty("ps.config.location");
0809:                    String filePath = ResourceLoader.getInstance(
0810:                            System.getProperties()).getProperties(
0811:                            "PSConfig.properties").getProperty(
0812:                            "ps.product.location");
0813:                    return filePath + File.separator + "web-src"
0814:                            + File.separator + "WEB-INF" + File.separator
0815:                            + "proxylet" + File.separator;
0816:                } catch (Exception npe) {
0817:                    return (new String(""));
0818:                }
0819:            }
0820:
0821:            private void renderPage(Template page, HttpServletResponse res)
0822:                    throws Exception {
0823:                logger.info(" Inside RenderPage ");
0824:                res.setContentType("text/html; charset=UTF-8");
0825:
0826:                PrintWriter out = res.getWriter();
0827:
0828:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
0829:                res.setHeader("Pragma", "no-cache");
0830:                String output = page.render();
0831:                res.setHeader("Content-Length", new Integer(output.length())
0832:                        .toString());
0833:                out.print(page.render());
0834:                out.close();
0835:                out.flush();
0836:                logger.info(" End of RenderPage");
0837:            }
0838:
0839:            private void renderPage(String page, HttpServletResponse res)
0840:                    throws Exception {
0841:                logger.info(" Inside RenderPage ");
0842:                if (page == null) {
0843:                    res.setStatus(HttpServletResponse.SC_NO_CONTENT);
0844:                    return;
0845:                }
0846:                res.setContentType("text/html; charset=UTF-8");
0847:
0848:                PrintWriter out = res.getWriter();
0849:
0850:                res.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
0851:                res.setHeader("Pragma", "no-cache");
0852:                res.setHeader("Content-Length", new Integer(page.length())
0853:                        .toString());
0854:                out.print(page);
0855:                out.close();
0856:                out.flush();
0857:                logger.info(" End of RenderPage");
0858:
0859:            }
0860:
0861:            private static String getSuffix(String agent) {
0862:                String suffix = null;
0863:
0864:                if (agent == null)
0865:                    return null;
0866:
0867:                if (agent.indexOf("Netscape") != -1
0868:                        || agent.indexOf("Mozilla") != -1) {
0869:                    suffix = "nav6up";
0870:                }
0871:
0872:                if (agent.indexOf("MSIE") != -1) {
0873:                    suffix = "msie5up";
0874:                }
0875:
0876:                return suffix;
0877:            }
0878:
0879:            /*
0880:             * This method encodes a Unicode Java String into a sequence of
0881:             * ASCII characters with non-ascii characters represented the way
0882:             * they would be in a Java program, e.g., with \u1234.
0883:             **/
0884:            static public String encodeJavaString(String s) {
0885:                StringBuffer buf = new StringBuffer();
0886:                for (int i = 0; i < s.length(); i++) {
0887:                    char c = s.charAt(i);
0888:                    int ic = (int) c;
0889:                    if (ic >= 32 && ic <= 127) {
0890:                        buf.append(c);
0891:                    } else {
0892:                        buf.append("\\u");
0893:                        for (int j = 4; j > 0; j--) {
0894:                            buf.append(Character.forDigit((ic & 0xf000) >> 12,
0895:                                    16));
0896:                            ic <<= 4;
0897:                        }
0898:                    }
0899:                }
0900:                return buf.toString();
0901:            }
0902:
0903:            private String convertascii(String name) {
0904:                char[] cname = name.toCharArray();
0905:                String sname = "";
0906:                for (int i = 0; i < cname.length; i++) {
0907:                    if ((cname[i] >= 'a' && cname[i] <= 'z')
0908:                            || (cname[i] >= 'A' && cname[i] <= 'Z')
0909:                            || (cname[i] >= '0' && cname[i] <= '9')) {
0910:                        sname += cname[i];
0911:                    }
0912:                }
0913:
0914:                return sname;
0915:            }
0916:
0917:            private String getRules(HttpServletRequest req) {
0918:                UserAttributes attrs = ProxyletUtil.getUserAttributes(req);
0919:                String rules = attrs.getString(PROXYLET_RULES);
0920:                return rules;
0921:                /*List list = attrs.getStringList(PROXYLET_RULES);
0922:                if( list == null )
0923:                return "";
0924:
0925:                Iterator listIterator = list.iterator();
0926:                StringBuffer rules = new StringBuffer();
0927:                while (listIterator.hasNext()) {
0928:                rules.append((String)listIterator.next());
0929:                rules.append("|");
0930:                }
0931:                return rules.toString();*/
0932:            }
0933:
0934:            private synchronized int getStatus(String sid) {
0935:                if (sid == null)
0936:                    return STATUS_UNLOADED;
0937:
0938:                Integer status = (Integer) sessionHash.get(sid);
0939:
0940:                if (status == null) {
0941:                    return STATUS_UNLOADED;
0942:                }
0943:
0944:                return status.intValue();
0945:            }
0946:
0947:            private synchronized void removeSession(SSOTokenID sid) {
0948:                sessionHash.remove(sid);
0949:            }
0950:
0951:            private synchronized void setStatus(String sid, int state) {
0952:                Integer status = (Integer) sessionHash.put(sid, new Integer(
0953:                        state));
0954:                if (status != null) {
0955:                    return;
0956:                }
0957:
0958:                try {
0959:                    SSOToken token = SSOTokenManager.getInstance()
0960:                            .createSSOToken(sid.toString());
0961:                    token.addSSOTokenListener(this );
0962:                } catch (SSOException e) {
0963:                    e.printStackTrace();
0964:                }
0965:
0966:            }
0967:
0968:            public void ssoTokenChanged(SSOTokenEvent se) {
0969:
0970:                try {
0971:                    int type = se.getType();
0972:                    removeSession(se.getToken().getTokenID());
0973:                } catch (SSOException ssoe) {
0974:                    logger.info("ssoTokenChanged() - SSOException : " + ssoe);
0975:                }
0976:            }
0977:
0978:            String getServletPath(HttpServletRequest req) {
0979:                String servletHost = req.getServerName();
0980:                String servletPort = new Integer(req.getServerPort())
0981:                        .toString();
0982:                String servletProtocol = req.getScheme();
0983:
0984:                String servletPath = servletProtocol + "://" + servletHost
0985:                        + ":" + servletPort + req.getContextPath()
0986:                        + req.getServletPath();
0987:
0988:                return servletPath;
0989:            }
0990:
0991:            public void redirectToPage(HttpServletResponse res, String stat,
0992:                    String val, String loc, String charset) {
0993:                StringBuffer outBuffer = new StringBuffer();
0994:                try {
0995:                    if ((charset != null) && (charset.trim().length() != 0)) {
0996:                        res.setContentType("text/html; charset=" + charset);
0997:                    } else {
0998:                        res.setContentType("text/html");
0999:                    }
1000:                    PrintWriter out = new PrintWriter(new BufferedWriter(
1001:                            new OutputStreamWriter(res.getOutputStream(),
1002:                                    charset)));
1003:                    java.util.ResourceBundle bundle = null;
1004:                    /*
1005:                     * If you donot have a valid session then use the default locale.
1006:                     */
1007:                    if ((loc == null) || (loc.trim().length() == 0)) {
1008:                        loc = "en_US";
1009:                        bundle = ResourceBundle.getBundle(
1010:                                ProxyletConstants.PROXYLET_SERVLET_RES_BUNDLE,
1011:                                com.iplanet.am.util.Locale.getLocale(loc));
1012:                    } else {
1013:                        bundle = ResourceBundle.getBundle(
1014:                                ProxyletConstants.PROXYLET_SERVLET_RES_BUNDLE,
1015:                                com.iplanet.am.util.Locale.getLocale(loc));
1016:
1017:                    }
1018:                    outBuffer.append("<html>\n");
1019:                    outBuffer.append("<BODY TEXT=\"").append(
1020:                            bundle.getString("ntxcolor"));
1021:                    outBuffer.append("\" BGCOLOR=\"").append(
1022:                            bundle.getString("nbgcolor")).append("\">\n");
1023:                    outBuffer.append("<p>").append(bundle.getString(stat));
1024:                    if (val != null && val.trim().length() != 0) {
1025:                        outBuffer.append(val);
1026:                    }
1027:                    outBuffer.append("</body>\n");
1028:                    outBuffer.append("</html>\n");
1029:                    out.print(outBuffer.toString());
1030:                    out.close();
1031:                } catch (IOException ioe) {
1032:                    // logger.severe("Error redirecting to session invalid page." +
1033:                    // ioe);
1034:                }
1035:            }
1036:
1037:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.