package psdi.webclient.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ibm.tivoli.maximo.log.LogInfo;
import com.ibm.tivoli.maximo.log.MaxLoggerContext;
import com.ibm.tivoli.maximo.log.ThreadLoggerCache;

import psdi.util.DBConnect;
import psdi.util.HTML;
import psdi.util.MXApplicationException;
import psdi.util.MXApplicationWarningException;
import psdi.util.MXCipher;
import psdi.util.MXException;
import psdi.util.MXFormat;
import psdi.util.MXProperties;
import psdi.util.MXSession;
import psdi.util.MXSystemException;
import psdi.util.logging.MXLogger;
import psdi.util.logging.MXLoggerFactory;
import psdi.webclient.system.filter.FilterActivationSwitch;
import psdi.webclient.system.runtime.LoggingUtils;
import psdi.webclient.system.runtime.WebClientRuntime;
import psdi.webclient.system.serviceability.Category;
import psdi.webclient.system.serviceability.Level;
import psdi.webclient.system.serviceability.RequestEntry;
import psdi.webclient.system.session.AsyncRequestManager;
import psdi.webclient.system.session.WebClientSession;
import psdi.webclient.system.session.WebClientSessionFactory;
import psdi.webclient.system.session.WebClientSessionManager;
import psdi.webclient.system.websession.WebAppEnv;
import psdi.app.iface.comm.AESUtil;
import psdi.app.signature.SignatureServiceRemote;
import psdi.common.context.UIContext;
import psdi.mbo.MboSet;
import psdi.security.SecurityService;
import psdi.security.UserInfo;
import psdi.server.MXServer;
import static psdi.app.iface.comm.AESUtil.createCiphertext;

public class RequestManager {

    private void setThreadLogging(MXSession mxSession) {
        UserInfo userInfo = mxSession.getUserInfo();
        LogInfo logInfo = ThreadLoggerCache.getInstance().getLogInfo("UI." + userInfo.getUserName());
        if (logInfo != null) {
            MaxLoggerContext.createCurrentContext(logInfo, "" + userInfo.getMaxSessionID(), userInfo);
        }
    }

    public void manageRequest(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        WebClientSession wcs = null;
        try {
            long startTime = System.currentTimeMillis();
            UIContext.createCurrentContext(request);
            session.setAttribute("request_parameter", request.getParameterMap());
            Object checkSessionLock;
            synchronized (session) {
                checkSessionLock = session.getAttribute("checkSessionLock");
                if (checkSessionLock == null) {
                    checkSessionLock = new Object();
                    session.setAttribute("checkSessionLock", checkSessionLock);
                }
            }
            synchronized (checkSessionLock) {
                wcs = checkSession(request, response);
            }
            UIContext.getCurrentContext().setWebClientSession(wcs);
            if (wcs != null) {
                setThreadLogging(wcs.getMXSession());
                if (wcs.getCurrentApp() != null) {
                    UIContext.getCurrentContext().setCurrentApp(wcs.getCurrentApp().getId());
                    if (wcs.getCurrentApp().onListTab()) {
                        UIContext.getCurrentContext().setFromListTab();
                    }
                }
            }
            session = request.getSession();
            if (wcs != null) {
                wcs.stamp();
                RequestEntry entry = wcs.serviceability.requests.log(request, response);
                try {
                    String encoding = request.getCharacterEncoding();
                    if (request.getParameter("_tbldnld") != null) {
                        String uri = request.getRequestURI();
                        response.reset();
                        if (encoding == null) {
                            encoding = "UTF-8";
                        }
                        response.setContentType("application/vnd.ms-excel; charset=" + encoding);
                        response.setHeader("Pragma", "public");
                        response.setHeader("Cache-Control", "max-age=0");
                        String filename = uri.substring(uri.length() - 8) + ".xls";
                        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                        String url = "/webclient/common/tabledownload.jsp";
                        RequestDispatcher rd = session.getServletContext().getRequestDispatcher(url);
                        rd.include((ServletRequest)request, (ServletResponse)response);
                    } else {
                        response.setHeader("Cache-Control", "no-cache");
                        response.setHeader("Cache-Control", "no-store");
                        response.setDateHeader("Expires", 0L);
                        response.setHeader("Pragma", "no-cache");
                        WebClientSession.RequestType requestType = WebClientSession.getRequestType(request);
                        String reqContentType = request.getParameter("responsetype");
                        if (reqContentType != null) {
                            for (String split : new String[] { "\r", "\n" }) {
                                int index = reqContentType.indexOf(split);
                                if (index >= 0) {
                                    reqContentType = reqContentType.substring(0, index);
                                }
                            }
                        }
                        if (FilterActivationSwitch.cssSupportActivated) {
                            String event = request.getParameter("event");
                            if (event != null && (event.equals("importapp") || event.equals("render_xls") || event.equals("exportapp") || event.equals("exportxml") || event.equals("exportall") || event.equals("exportsql"))) {
                                reqContentType = HTML.encode(reqContentType);
                            }
                        }
                        if (WebClientRuntime.isNull(reqContentType)) {
                            if (!isXHRRequest(request)) {
                                reqContentType = "text/html";
                            }
                            else if (requestType != WebClientSession.RequestType.HIGHASYNC && requestType != WebClientSession.RequestType.NORENDER) {
                                reqContentType = "text/xml";
                            }
                        }
                        if (!WebClientRuntime.isNull(reqContentType)) {
                            if (encoding != null && encoding.length() != 0 && !encoding.equalsIgnoreCase("null")) {
                                session.setAttribute("_encoding", encoding);
                                response.setContentType(reqContentType + ";charset=" + encoding);
                            } else {
                                response.setContentType(reqContentType);
                            }
                        }
                        AsyncRequestManager asyncReqManager = null;
                        if ("true".equals(request.getParameter("designmode"))) {
                            asyncReqManager = wcs.getDesignerAsyncRequestManager();
                        } else {
                            asyncReqManager = wcs.getAsyncRequestManager();
                        }
                        asyncReqManager.manageRequest(request, response);
                        wcs.stamp();
                        long endTime = System.currentTimeMillis();
                        wcs.setPerformanceDataHASH("09_REQUEST_DONE", endTime - startTime);
                    }
                }
                catch (IOException ex) {
                    wcs.serviceability.logger.log(Level.ERROR, Category.ROOT, "Exception processed request: " + ex.getMessage(), LoggingUtils.dumpRequest(request));
                }
                catch (ServletException ex2) {
                    wcs.serviceability.logger.log(Level.ERROR, Category.ROOT, "Exception processed request: " + ex2.getMessage(), LoggingUtils.dumpRequest(request));
                }
                finally {
                    if (entry != null) {
                        entry.finish();
                    }
                }
            }
            MboSet.clearESigTransactionIdThread();
        } catch (IOException ex3) {
            LoggingUtils.logConsoleMessages(2, "Exception processed request: " + ex3.getMessage());
            LoggingUtils.logConsoleMessages(2, "WebClientSession is " + wcs);
            LoggingUtils.logConsoleMessages(2, LoggingUtils.dumpRequest(request));
            ex3.printStackTrace();
        } finally {
            UIContext.destroyCurrentContext();
            MaxLoggerContext.destroyCurrentContext();
        }
    }

    private void setLocale(MXSession s, HttpServletRequest request) {
        Object[] settings = WebClientRuntime.getLocaleFromRequest(request);
        if (settings[0] instanceof String) {
            s.setLangCode((String)settings[0]);
        }
        if (settings[1] instanceof Locale) {
            s.setLocale((Locale)settings[1]);
        }
    }

    public WebClientSession checkSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebClientSessionFactory.getWebClientSessionFactory().cleanupDiscardedSessions();
        boolean hiddenFrame = isXHRRequest(request);
        HttpSession session = request.getSession();
        WebClientSession wcs = null;
        String gotoPage = null;
        String queryString = null;
        String url = null;
        WebClientSessionManager wcsm = (WebClientSessionManager)session.getAttribute("_WCSM_");
        boolean wcsTimeout = false;
        boolean userSessionsMaxed = false;
        boolean wcsAvailable = WebClientSessionFactory.getWebClientSessionFactory().hasAvailableSessions();
        if (wcsm != null) {
            try {
                wcs = wcsm.getWebClientSession(request);
                if (wcs != null) {
                    if (MXServer.isMTEnabled() && MXServer.getTenantContext() == -1 && wcs.getMXSession() != null && wcs.getMXSession().getUserInfo() != null) {
                        MXServer.setTenantContext(wcs.getMXSession().getUserInfo());
                    }
                    if (wcs.isValid()) {
                        wcs.stamp();
                        wcs.useLeftContextInterval(false);
                    }
                    else {
                        wcsTimeout = true;
                        wcs = null;
                    }
                }
            }
            catch (MXException e6) {
                wcsTimeout = true;
            }
            if (wcsAvailable) {
                wcsAvailable = wcsm.hasAvailableSessions();
                userSessionsMaxed = !wcsAvailable;
            }
        }
        boolean formAuth = session.getAttribute("formAuth") != null && WebAppEnv.useAppServerSecurity();
        boolean madeConnection = false;
        if (wcsm != null && wcsm.getSessionInvalidated()) {
            session.removeAttribute("MXSession");
        }
        MXSession s = WebClientRuntime.getMXSession(session);
        if (s == null) {
            MXLogger uiSessionLogger = MXLoggerFactory.getLogger("maximo.webclient.uisession");
            if (uiSessionLogger.isFatalEnabled()) {
                uiSessionLogger.fatal("Unable to create MXSessions so users cannot login into maximo");
            }
            response.sendError(503);
            return null;
        }
        boolean designMode = Boolean.valueOf(request.getParameter("designmode")) || Boolean.valueOf((String)request.getAttribute("designmode"));
        if (wcsTimeout) {
            gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
            queryString = "timeout=true";
        } else if (wcsAvailable || designMode) {
            if (s.isConnected()) {
                if(session.getAttribute("isNewPasswordRequired") != null)
                {
                    String requestMethod = request.getMethod();
                    String paramEvent = request.getParameter("event");
                    String paramValue = request.getParameter("value");
                    String loginID = s.getUserInfo().getLoginID();
                    if(requestMethod != null && requestMethod.equalsIgnoreCase("get") && (paramEvent == null || paramValue == null || paramEvent.equalsIgnoreCase("loadapp") && !paramValue.equalsIgnoreCase("changepswd")))
                        try {
                            SignatureServiceRemote ssr = (SignatureServiceRemote)s.lookup("SIGNATURE");
                            if(ssr.hasPasswordExpired(loginID, s.getUserInfo()))
                            {
                                gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                                session.setAttribute("signoutmessage", s.getMessage("jspmessages", "passwdExpired"));
                                session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                            } else
                            {
                                session.removeAttribute("isNewPasswordRequired");
                            }
                        } catch (MXException e) {
                            session.setAttribute("loginexception", e);
                        }
                }
                if (wcs == null) {
                    if (hiddenFrame) {
                        gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                        queryString = "timeout=true";
                        session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                    } else {
                        wcs = WebClientSessionFactory.getWebClientSessionFactory().createSession(request, response);
                    }
                } else {
                    boolean loggedout = false;
                    String msg = null;
                    try {
                        loggedout = s.hasAdminLogout();
                    }
                    catch (MXException e2) {
                        loggedout = true;
                        msg = e2.getMessage();
                        e2.printStackTrace();
                    }
                    if (loggedout) {
                        if (msg == null) {
                            msg = wcs.getMessage("signature", "LoggedOutByAdmin");
                        }
                        String logoutPage = gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage", request.getContextPath() + "/index.html");
                        queryString = wcs.getUISessionUrlParameter() + wcs.getCSRFTokenParameter();
                        session.setAttribute("signoutmessage", msg);
                        session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                    }
                }
            } else {
                setLocale(s, request);
                boolean loadBalancerUsed = false;
                try {
                    loadBalancerUsed = MXFormat.stringToBoolean(MXServer.getMXServer().getProperty("mxe.system.usingLoadBalancer"));
                } catch (MXApplicationException ex2) {}
                String clientAddr = request.getHeader("X-Forwarded-For");
                if (loadBalancerUsed && clientAddr != null) {
                    int index = clientAddr.indexOf(",");
                    if (index > -1) {
                        clientAddr = clientAddr.substring(0, index);
                    }
                    s.setClientHost(clientAddr);
                    s.setClientAddr(clientAddr);
                } else {
                    s.setClientHost(request.getRemoteHost());
                    s.setClientAddr(request.getRemoteAddr());
                }
                if (WebClientRuntime.isMTEnabled()) {
                    String tenant = request.getParameter("tenant");
                    if (tenant == null) {
                        tenant = (String)request.getSession().getAttribute("tenant");
                    }
                    if (tenant != null) {
                        s.setTenant(tenant);
                    }
                }
                if (wcs != null) {
                    wcs.cleanup();
                    wcs = null;
                }
                if (WebAppEnv.useAppServerSecurity()) {
                    boolean fromWelcome = request.getParameter("welcome") != null;
                    if (hiddenFrame) {
                        if (formAuth) {
                            MXException timeout = new MXApplicationException("jspmessages", "session_timeout");
                            session.setAttribute("formauthtowarning", timeout);
                            RequestDispatcher rd = session.getServletContext().getRequestDispatcher("/webclient/login/timeoutwait.jsp");
                            try
                            {
                                rd.include(request, response);
                                return null;
                            }
                            catch(Exception e)
                            {
                                url = WebClientRuntime.getMaximoRequestURL(request);
                            }
                        } else {
                            gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                            try
                            {
                                session.setAttribute("signoutmessage", s.getMessage("jspmessages", "session_timeout"));
                            }
                            catch(MXException mxexception) { }
                            session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                            session.setAttribute("sessiontimeout", "true");
                        }
                    } else {
                        try {
                            s.connect();
                            session = secureSession(session, request);
                            madeConnection = true;
                            wcs = WebClientSessionFactory.getWebClientSessionFactory().createSession(request, response);
                            if (wcs != null) {
                                MXException warning = (MXException)session.getAttribute("formauthtowarning");
                                if (warning != null) {
                                    wcs.addWarning(warning);
                                    session.removeAttribute("formauthtowarning");
                                }
                                if ("1".equals(MXServer.getMXServer().getProperty("mxe.AllowUserMgmt"))) {
                                    SignatureServiceRemote ssr = (SignatureServiceRemote)s.lookup("SIGNATURE");
                                    if (ssr.hasPasswordExpired(s.getUserInfo().getLoginID(), s.getUserInfo())) {
                                        Set<String> appList = (Set<String>)s.getProfile().getApps();
                                        String startapp = WebClientRuntime.getWebClientProperty("webclient.changepwdapp", "changepswd");
                                        if (!appList.contains(startapp.toUpperCase())) {
                                            gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage", "none");
                                            session.setAttribute("signoutmessage", s.getMessage("jspmessages", "passwdExpiredSysAdm"));
                                            session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                                        }
                                        url = WebClientRuntime.getMaximoRequestURL(request) + "?event=loadapp&value=" + startapp + "&" + wcs.getUISessionUrlParameter();
                                    }
                                    else if (ssr.showPasswordWarning(s.getUserInfo().getLoginID(), s.getUserInfo())) {
                                        Object[] p = { ssr.passwordWillExpire(s.getUserInfo().getUserName(), s.getUserInfo()) + "" };
                                        wcs.addWarning((MXException)new MXApplicationWarningException("jspmessages", "passwdWillExpire", p));
                                    }
                                }
                            }
                        } catch (MXException e3) {
                            if (fromWelcome) {
                                url = WebClientRuntime.getMaximoRequestURL(request);
                            }
                            else {
                                gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                                session.setAttribute("signoutmessage", e3.getMessage());
                                session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                                session.setAttribute("loginexception", e3);
                            }
                        }
                    }
                } else {
                    String login = request.getParameter("login");
                    if (login != null) {
                        boolean perfomLogin = true;
                        if (login.equals("jsp")) {
                            String loginStamp = request.getParameter("loginstamp");
                            String stamp = (String)session.getAttribute("allowlogin");
                            if (stamp == null || loginStamp == null || !stamp.equals(loginStamp)) {
                                perfomLogin = false;
                                try {
                                    session.setAttribute("signoutmessage", s.getMessage("jspmessages", "redirectlogin"));
                                }
                                catch (MXException ex4) {}
                            }
                        }
                        if (perfomLogin) {
                            try {
                                session.removeAttribute("allowlogin");
                                if (login.equals("selfreg")) {
                                    String username = HTML.decode(request.getParameter("username"));
                                    if (MXServer.isMTEnabled() && WebClientRuntime.isNull(username)) {
                                        throw new MXApplicationException("mt", "loginrequired");
                                    }
                                    s.connectAsRegUser(username);
                                    madeConnection = true;
                                    wcs = WebClientSessionFactory.getWebClientSessionFactory().createSession(request, response);
                                }
                                else {
                                    String username = HTML.decode(request.getParameter("username"));
                                    String password = HTML.decode(request.getParameter("password"));
                                    /*-------------SSO---------------*/
                                    boolean isOALogin = false;  //门户单点登陆标识
                                    String stoken = request.getParameter("token");
                                    if(stoken!=null&&!stoken.equals(""))
                                        isOALogin = true;
                                    if(isOALogin){
                                        //get user in token
                                        String stoken2 = AESUtil.getPlaintext(stoken);
                                        if(stoken2==null||stoken2.equals("")){
                                            stayLoginpage(request, response);
                                            throw new MXApplicationException("jspmessages", "blanklogin");  //no userid
                                        } else if (stoken2.startsWith("Error:")) {
                                            stayLoginpage(request, response);
                                            String[] as = {"Token", ". " + stoken2};
                                            throw new MXApplicationException("jspmessages", "gllookupInvalidCode", as);
                                        }
                                        String[] asToken = stoken2.split("-"); //userid - appid
                                        if (asToken.length < 2) {
                                            stayLoginpage(request, response);
                                            String[] as = {"AppID", " "};
                                            throw new MXApplicationException("jspmessages", "gllookupInvalidCode", as);
                                        }
                                        if (!asToken[1].equals(APPID)) {
                                            stayLoginpage(request, response);
                                            String[] as = {"AppID", ". " + asToken[1]};
                                            throw new MXApplicationException("jspmessages", "gllookupInvalidCode", as);
                                        }

                                        String sOAUser = asToken[0];
                                        String[] ruslt = getPassword(sOAUser);
                                        username =ruslt[0];
                                        password =ruslt[1];

                                        if(password.equals("portaluserNotExists")){
                                            stayLoginpage(request, response);
                                            String[] as = {"Userid", "(" + username + ")"};
                                            throw new MXApplicationException("jspmessages", "gllookupInvalidCode", as);//系统中没有找到OA系统登录所使用的用户。
                                        }

                                        if ((WebClientRuntime.isNull(username)) || (WebClientRuntime.isNull(password))){
                                            stayLoginpage(request, response);
                                            throw new MXApplicationException("jspmessages", "blanklogin");
                                        }
                                        //connect
                                        session = secureSession(session, request);
                                        s.setUserName(username);
                                        s.setPassword(password);
                                        s.connect();
                                    } else {
                                        if (WebClientRuntime.isNull(username) || WebClientRuntime.isNull(password)) {
                                            throw new MXApplicationException("jspmessages", "blanklogin");
                                        }
                                        session = secureSession(session, request);
                                        s.setUserName(username);
                                        s.setPassword(password);
                                        s.connect();
                                    }
                                    /*-------------------------------*/
//                                    if (WebClientRuntime.isNull(username) || WebClientRuntime.isNull(password)) {
//                                        throw new MXApplicationException("jspmessages", "blanklogin");
//                                    }
//                                    session = secureSession(session, request);
//                                    s.setUserName(username);
//                                    s.setPassword(password);
//                                    s.connect();
                                    if (s.isConnected()) {
                                        madeConnection = true;
                                        wcs = WebClientSessionFactory.getWebClientSessionFactory().createSession(request, response);
                                        if (wcs != null) {
                                            SignatureServiceRemote ssr2 = (SignatureServiceRemote)s.lookup("SIGNATURE");
                                            if (ssr2.hasPasswordExpired(username, s.getUserInfo())) {
                                                Set<String> appList2 = (Set<String>)s.getProfile().getApps();
                                                String startapp2 = WebClientRuntime.getWebClientProperty("webclient.changepwdapp", "changepswd");
                                                if (!appList2.contains(startapp2.toUpperCase())) {
                                                    gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage", "none");
                                                    session.setAttribute("signoutmessage", s.getMessage("jspmessages", "passwdExpiredSysAdm"));
                                                    session.setAttribute("signoutfrom", WebClientRuntime.getMaximoRequestURL(request));
                                                }
                                                url = WebClientRuntime.getMaximoRequestURL(request) + "?event=loadapp&value=" + startapp2 + "&" + wcs.getUISessionUrlParameter();
                                                session.setAttribute("isNewPasswordRequired", true);
                                            }
                                            else if (ssr2.showPasswordWarning(username, s.getUserInfo())) {
                                                Object[] p2 = { ssr2.passwordWillExpire(username, s.getUserInfo()) + "" };
                                                wcs.addWarning((MXException)new MXApplicationWarningException("jspmessages", "passwdWillExpire", p2));
                                            }
                                        }
                                    }
                                }
                            }
                            catch (RemoteException re) {
                                session.setAttribute("loginexception", new MXSystemException("system", "remoteexception", (Throwable)re));
                            } catch (MXException e4) {
                                session.setAttribute("loginexception", e4);
                            } catch (Exception e5) {
                                session.setAttribute("loginexception", e5);
                            }
                        }
                    }
                    if (!s.isConnected() && !hiddenFrame) {
                        gotoPage = WebClientRuntime.getWebClientProperty("webclient.loginpage", request.getContextPath() + "/index.html");
                        if (login == null || !login.equals("selfreg")) {
                            queryString = request.getQueryString();
                        }
                    }
                }
            }
        }
        if (wcs == null && gotoPage == null) {
            if (madeConnection) {
                try {
                    if (s.isConnected()) {
                        s.disconnect();
                    }
                }
                catch (MXException mxe) {
                    mxe.printStackTrace();
                }
            }
            if (hiddenFrame) {
                gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                queryString = "timeout=true";
            }
            else {
                if (WebAppEnv.useAppServerSecurity() && (madeConnection || wcsm == null || !wcsm.hasSessions())) {
                    gotoPage = WebClientRuntime.getWebClientProperty("webclient.logoutpage");
                }
                else {
                    gotoPage = WebClientRuntime.getWebClientProperty("webclient.loginerrorpage");
                }
                queryString = "unavailable=true";
            }
        }
        if (WebAppEnv.useAppServerSecurity() && !isRunningInWebLogic()) {
            try {
                SecurityService secServ = (SecurityService)MXServer.getMXServer().lookup("SECURITY");
                secServ.invalidateLtpaToken(request);
            }
            catch (Exception e5) {
                MXLoggerFactory.getLogger("maximo.webclient.uisession").warn("Exception while updating LTPA Token", (Throwable)e5);
            }
        }
        if (gotoPage == null && url == null) {
            return wcs;
        }
        String langcode = null;
        Locale locale = null;
        if (s.getUserInfo() != null) {
            langcode = s.getUserInfo().getLangCode();
            locale = s.getUserInfo().getLocale();
        }
        else {
            Object[] settings = WebClientRuntime.getLocaleFromRequest(request);
            if (settings[0] instanceof String) {
                langcode = (String)settings[0];
            }
            if (settings[1] instanceof Locale) {
                locale = (Locale)settings[1];
            }
        }
        if (langcode != null) {
            session.setAttribute("langcode", langcode);
        }
        if (locale != null) {
            session.setAttribute("_locale_", locale);
        }
        if (url == null) {
            url = new URL(new URL(WebClientRuntime.getMaximoRequestURL(request)), gotoPage).toString() + ((queryString == null) ? "" : ("?" + queryString));
        }
        if (!wcsAvailable && wcs == null && !wcsTimeout && WebClientRuntime.send503Error(response, s, userSessionsMaxed)) {
            return null;
        }
        if (hiddenFrame) {
            response.setContentType("text/xml");
            response.getWriter().println("<?xml version=\"1.0\" ?>");
            response.getWriter().println("<server_response>");
            response.getWriter().println("<redirect><![CDATA[" + url + "]]></redirect>");
            response.getWriter().println("</server_response>");
        }
        else {
            response.sendRedirect(url);
        }
        return null;
    }

    public static boolean isXHRRequest(HttpServletRequest request) {
        return request.getParameter("events") != null;
    }

    private HttpSession secureSession(HttpSession oldSession, HttpServletRequest request) throws MXException {
        if (isRunningInWebLogic()) {
            return oldSession;
        }
        try {
            SecurityService secServ = (SecurityService)MXServer.getMXServer().lookup("SECURITY");
            secServ.validateLtpaToken(request);
        }
        catch (RemoteException e) {
            MXLoggerFactory.getLogger("maximo.webclient.uisession").warn("Remote Exception while validating LTPA Token", (Throwable)e);
        }
        Map<String, Object> savedAttrs = new HashMap<String, Object>();
        Enumeration<String> attrNames = (Enumeration<String>)oldSession.getAttributeNames();
        while (attrNames.hasMoreElements()) {
            String attrName = attrNames.nextElement();
            savedAttrs.put(attrName, oldSession.getAttribute(attrName));
        }
        oldSession.removeAttribute("MXSession");
        WebClientSessionManager wcsm = WebClientSessionManager.getWebClientSessionManager(oldSession);
        if (wcsm != null) {
            wcsm.preserveMXSession();
        }
        oldSession.invalidate();
        HttpSession newSession = request.getSession(true);
        for (String attrKey : savedAttrs.keySet()) {
            newSession.setAttribute(attrKey, savedAttrs.get(attrKey));
        }
        return newSession;
    }

    private boolean isRunningInWebLogic() {
        boolean inWebLogic = false;
        ClassLoader currentClassLoader = getClass().getClassLoader();
        try {
            Class.forName("weblogic.security.services.Authentication", true, currentClassLoader);
            inWebLogic = true;
        }
        catch (ClassNotFoundException e) {
            inWebLogic = false;
        }
        MXLogger uiSessionLogger = MXLoggerFactory.getLogger("maximo.webclient.uisession");
        if (uiSessionLogger.isDebugEnabled()) {
            uiSessionLogger.debug(("*** isRunningInWebLogic? " + inWebLogic));
        }
        return inWebLogic;
    }

    public String[] getPassword(String username) throws Exception {
        String personid = username.toUpperCase();
        ResultSet rs = null;
        Connection con = null;
        InputStream in = getClass().getResourceAsStream("/maximo.properties");// 读取配置文件
        Properties properties = MXProperties.loadProperties(in, true);
        String dbUrl = properties.getProperty("mxe.db.url");
        String dbUsername = properties.getProperty("mxe.db.user");
        String dbPassword = properties.getProperty("mxe.db.password");
        String dbSchema = properties.getProperty("mxe.db.schemaowner");
        String ciphertext = "";// 密码密文
        String loginid ="";

        con = DBConnect.getConnection(dbUrl, dbUsername, dbPassword, dbSchema);// 链接数据库
        Statement stmt = con.createStatement();
        stmt.execute("select loginid,password from maxuser where status= 'ACTIVE' and userid='"+ personid + "'");// 获取用户表的信息
        rs = stmt.getResultSet();//查询结果
        while (rs.next()) {
            loginid= rs.getString(1);
            ciphertext = rs.getString(2);// 从数据库获取密码密文
        }
        rs.close();

        if (ciphertext == null || ciphertext.equals("")){
            String ruslt[] = {"jspmessages", "portaluserNotExists"};
            return ruslt;  // 没有找到登录所使用的用户。
        }
        // 密文字符串
        byte[] byte2 = StrToBytes(ciphertext);

        String algTest = "DESede";
        String modeTest = "CBC";
        String paddingTest = "PKCS5Padding";
        String keyTest = "Sa#qk5usfmMI-@2dbZP9`jL3";
        String specTest = "beLd7$lB";
        String modTest = "";
        String providerTest = "";

        MXCipher mxc = new MXCipher(algTest, modeTest, paddingTest, keyTest,specTest, modTest, providerTest);
        String password =  mxc.decData(byte2);// 解密密文获取明文
        String ruslt[] = {loginid, password};
        return ruslt;
    }

    /**
     * 将密文字符串转化为 字节数组
     *
     * @param ciphertext
     * @return
     */
    private static byte[] StrToBytes(String ciphertext) {
        int len = ciphertext.length();
        if (len == 0 || len % 2 == 1) {
            return null;
        }
        byte[] b = new byte[len / 2];
        for (int i = 0; i < ciphertext.length(); i += 2) {
            String val = "0x" + ciphertext.substring(i, i + 2);
            b[i / 2] = (byte) Integer.decode(val).intValue();
        }

        return b;
    }

    /**
     * 单点登录认证出现错误时，留在登录界面
     * @param request
     * @param response
     * @throws IOException
     */
    private void stayLoginpage(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String gotoPage = WebClientRuntime.getWebClientProperty("webclient.loginpage");
        String queryString = "welcome=true";
        String	url = new URL(new URL(WebClientRuntime.getMaximoRequestURL(request)), gotoPage).toString() + (queryString == null ? "" : new StringBuilder().append("?").append(queryString).toString());
        response.sendRedirect(url);
    }

    public final String REQUEST_PARAMETER = "request_parameter";
    public static final String XHR_REQUEST = "events";
    public static final String RESPONSETYPE_PARAMETER = "responsetype";
    private static final String WEBLOGIC_CLASS = "weblogic.security.services.Authentication";
    private static final String HEADER_X_FORWARDED_FOR = "X-Forwarded-For";
    private static final String APPID = "OA2EAMIFACE";
}
