List of usage examples for javax.servlet.http HttpSession invalidate
public void invalidate();
From source file:net.shopxx.controller.shop.RegisterController.java
/** * ??//from w w w. ja va 2s . c o m */ @RequestMapping(value = "/submit_email", method = RequestMethod.POST) public @ResponseBody Message submitEmail(String captchaId, String captcha, String email, Long userId, String registStep, String userImg, String trueName, String idCardImg, HttpServletRequest request, HttpServletResponse response, HttpSession session, ModelMap model) { Setting setting = SettingUtils.get(); Member member = new Member(); if (userId != null) {// id? member = memberService.find(userId); if ("2".equals(registStep)) {// member.setUserImg(userImg); List<MemberAttribute> memberAttributes = memberAttributeService.findList(); for (MemberAttribute memberAttribute : memberAttributes) { String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId()); if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text || memberAttribute.getType() == Type.select) { if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, parameter); } else if (memberAttribute.getType() == Type.gender) { Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null; if (memberAttribute.getIsRequired() && gender == null) { return Message.error("shop.common.invalid"); } member.setGender(gender); } else if (memberAttribute.getType() == Type.birth) { try { Date birth = StringUtils.isNotEmpty(parameter) ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS) : null; if (memberAttribute.getIsRequired() && birth == null) { return Message.error("shop.common.invalid"); } member.setBirth(birth); } catch (ParseException e) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.area) { Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null; if (area != null) { member.setArea(area); } else if (memberAttribute.getIsRequired()) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.checkbox) { String[] parameterValues = request .getParameterValues("memberAttribute_" + memberAttribute.getId()); List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null; if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, options); } } net.shopxx.Template activateAccountMailTemplate = templateService.get("activateAccount"); SafeKey safeKey = new SafeKey(); safeKey.setValue( UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30))); safeKey.setExpire(setting.getSafeKeyExpiryTime() != 0 ? DateUtils.addMinutes(new Date(), setting.getSafeKeyExpiryTime()) : null); member.setSafeKey(safeKey); Map<String, Object> param = new HashMap<String, Object>(); param.put("member", member); param.put("domain", setting.getSiteUrl());// http mailService.send(member.getEmail(), "???", activateAccountMailTemplate.getTemplatePath(), param); } else if ("3".equals(registStep)) { member.setTrueName(trueName); member.setIdCardImg(idCardImg); } member.setRegistStep(registStep);// ?? memberService.update(member); } else {// id String password = rsaService.decryptParameter("enPassword", request); rsaService.removePrivateKey(request); if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) { return Message.error("shop.captcha.invalid"); } if (!setting.getIsRegisterEnabled()) { return Message.error("shop.register.disabled"); } if (!isValid(Member.class, "password", password, Save.class)) { return Message.error("shop.common.invalid"); } if (password.length() < setting.getPasswordMinLength() || password.length() > setting.getPasswordMaxLength()) { return Message.error("shop.common.invalid"); } member.setPassword(DigestUtils.md5Hex(password)); member.setPoint(setting.getRegisterPoint()); member.setAmount(new BigDecimal(0)); member.setBalance(new BigDecimal(0)); member.setIsEnabled(true); member.setIsLocked(false); member.setLoginFailureCount(0); member.setLockedDate(null); member.setRegisterIp(request.getRemoteAddr()); member.setLoginIp(request.getRemoteAddr()); member.setLoginDate(new Date()); member.setSafeKey(null); member.setMemberRank(memberRankService.findDefault()); member.setFavoriteProducts(null); member.setUsername(email);// ?? member.setEmail(email);// member.setRegistStep("1");// ?? memberService.save(member); } Cart cart = cartService.getCurrent(); if (cart != null && cart.getMember() == null) { cartService.merge(member, cart); WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME); WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME); } Map<String, Object> attributes = new HashMap<String, Object>(); Enumeration<?> keys = session.getAttributeNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); attributes.put(key, session.getAttribute(key)); } session.invalidate(); session = request.getSession(); for (Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } member = memberService.find(member.getId()); // Message message = new Message(); // message.setType(Message.Type.success); // message.setContent("????"); // message.setScript(member.getId().toString()); request.getSession().setAttribute("currentMemberSession", member); return Message.success("????"); }
From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java
protected void doChangePassword2(HttpServletRequest req, HttpServletResponse resp) throws Exception { logger.info("doChangePassword2"); try {/*from ww w . j a v a 2s. co m*/ HttpSession session = req.getSession(false); if (session == null) { logger.debug("null session"); // this shouldn't happen, make the user start over resp.sendRedirect("./jsp/loggedOut.jsp"); return; } String username = req.getParameter("userid"); if (username != null) { username = username.toUpperCase(); } String newPassword = req.getParameter("newpswd1"); String newPassword2 = req.getParameter("newpswd2"); // Security enhancement String question1 = (String) req.getParameter("question1"); String answer1 = (String) req.getParameter("answer1"); String question2 = (String) req.getParameter("question2"); String answer2 = (String) req.getParameter("answer2"); String question3 = (String) req.getParameter("question3"); String answer3 = (String) req.getParameter("answer3"); logger.debug("changing request: " + question1 + "=" + answer1 + " " + question2 + "=" + answer2 + " " + question3 + "=" + answer3); logger.debug("username " + username); //begin - CADSRPASSW-73 String status = ""; try { logger.info("doChangePassword: checking account status ..."); status = doValidateAccountStatus(username, session, req, resp, "./jsp/resetPassword.jsp"); logger.debug("doChangePassword: account status check done"); } catch (Exception e1) { logger.debug("doChangePassword: account status was: [" + status + "]"); if (status != null && status.equals("")) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } else { logger.debug("doChangePassword: account status check error was: " + e1.getMessage()); e1.printStackTrace(); } } //end - CADSRPASSW-73 if (status.indexOf(Constants.LOCKED_STATUS) > -1) { logger.debug("doChangePassword2:status [" + status + "] returning without doing anything ..."); return; } //=== begin of moved down (CADSRPASSW-5) if (Messages.getString("PasswordChangeHelper.3").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.3")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.4").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.4")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.5").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.5")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } //begin - CADSRPASSW-88 if (Messages.getString("PasswordChangeHelper.6").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.6")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } //end - CADSRPASSW-88 if (Messages.getString("PasswordChangeHelper.7").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { logger.debug("entered username doesn't match session " + username + " " + req.getParameter("userid").toUpperCase()); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.7")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.8").equals(PasswordChangeHelper.validateChangePassword( username, null, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { logger.debug("new password mis-typed"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.8")); resp.sendRedirect("./jsp/resetPassword.jsp"); return; } //=== end of moved down (CADSRPASSW-5) connect(); PasswordChangeDAO changeDAO = new PasswordChangeDAO(datasource); Result passwordChangeResult = changeDAO.resetPassword(username, newPassword); disconnect(); if (passwordChangeResult.getResultCode() == ResultCode.PASSWORD_CHANGED) { logger.info("password reset"); resetUserStoredAttemptedCount(username); //CADSRPASSW-42 logger.debug("answer count reset"); connect(); PasswordNotifyDAO dao = new PasswordNotifyDAO(datasource); User usr = new User(); usr.setUsername(username); logger.debug("doChangePassword: removing the user [" + usr.getUsername() + "] removed from the notification queue ..."); dao.removeQueue(usr); //CADSRPASSW-72 logger.info( "doChangePassword: user [" + usr.getUsername() + "] removed from the notification queue"); session.invalidate(); // they are done, log them out resp.sendRedirect("./jsp/passwordChanged.jsp"); } else { logger.info("password change failed"); String errorMessage = passwordChangeResult.getMessage(); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, errorMessage); resp.sendRedirect("./jsp/resetPassword.jsp"); } } catch (Throwable theException) { logger.error(CommonUtil.toString(theException)); } }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "/AccountView", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView viewAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { ModelAndView model = null;// w w w . j av a 2 s .co m ResultSet rs = null; ResultSet rs_details = null; ResultSet rs_details_personal = null; String ViewDetails = ""; String ViewUserSelect = null; String role = (String) session.getAttribute("Role"); try { if (role == null) { model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("EMPLOYEE")) { try { model = new ModelAndView(); ViewAccounts handler = new ViewAccounts(); List<AccountDetails> accountReqstdetails = new ArrayList<AccountDetails>(); rs = handler.requestAccountHandler(); try { while (rs.next()) { AccountDetails view = new AccountDetails(); view.setUserName(rs.getString("requestfrom")); accountReqstdetails.add(view); } model.addObject("accountView", accountReqstdetails); //request.setAttribute(", o); } catch (SQLException e) { // TODO Auto-generated catch block LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("index"); LOG.error("Issue while viewing the account" + e.getMessage()); } if (request.getParameter("submit") != null) { ViewDetails = request.getParameter("Type"); ViewUserSelect = request.getParameter("radio"); if (ViewUserSelect == null) { model.addObject("Select", "No User selected"); model.setViewName("AccountDetails"); return model; } List<AccountDetails> accountDetailsView = new ArrayList<AccountDetails>(); if (ViewDetails.equals("Account")) { rs_details = handler.requestAccountDetailsHandler(ViewUserSelect); try { while (rs_details.next()) { AccountDetails view = new AccountDetails(); view.setUserNameAccount(rs_details.getString("username")); view.setAccountNumber(rs_details.getString("accountnumber")); view.setAccountType(rs_details.getString("accounttype")); view.setBalance(rs_details.getDouble("balance")); accountDetailsView.add(view); } model.addObject("AccountDetails", "1"); model.addObject("accountDetailsView", accountDetailsView); //request.setAttribute(", o); } catch (SQLException e) { // TODO Auto-generated catch block LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("index"); LOG.error("Issue while getting the account details " + e.getMessage()); } } if (ViewDetails.equals("Personal")) { rs_details_personal = handler.requestPersonalDetailsHandler(ViewUserSelect); List<PersonalDetails> personalDetailsView = new ArrayList<PersonalDetails>(); try { while (rs_details_personal.next()) { PersonalDetails view = new PersonalDetails(); view.setFirstName(rs_details_personal.getString("firstname")); view.setLastName(rs_details_personal.getString("lastname")); view.setAddress(rs_details_personal.getString("address")); view.setGender(rs_details_personal.getString("gender")); view.setState(rs_details_personal.getString("state")); view.setZip(rs_details_personal.getString("zip")); view.setPhonenumber(rs_details_personal.getString("phonenumber")); view.setDob(rs_details_personal.getString("dateofbirth")); view.setEmail(rs_details_personal.getString("email")); personalDetailsView.add(view); } model.addObject("PersonalDetails", "1"); model.addObject("personalDetailsView", personalDetailsView); //request.setAttribute(", o); } catch (SQLException e) { // TODO Auto-generated catch block LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("index"); LOG.error("Issue while getting the personal details " + e.getMessage()); } } } } catch (Exception e) { LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("index"); LOG.error("Issue while getting the personal details " + e.getMessage()); LOG.error("Issue while viewing the account" + e.getMessage()); } model.setViewName("AccountDetails"); } else { model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); } } catch (Exception e) { LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("index"); LOG.error("Issue while viewing the account" + e.getMessage()); } finally { try { if (rs_details != null) { rs_details.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (rs_details_personal != null) { rs_details_personal.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; }
From source file:org.josso.servlet.agent.JossoFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; debug = 1;//w ww. j av a 2 s . com if (debug == 1) log.debug("Processing : " + hreq.getContextPath()); try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); //_agent.setCatalinaContainer(container); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; // T1 si l'appli n'est pas partenaire alors pas de SSO on continue if (!_agent.isPartnerApp(vhost, contextPath)) { filterChain.doFilter(hreq, hres); logg("T1 Context is not a josso partner app : " + hreq.getContextPath()); hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte"); return; } else { logg("T1 Context IS a josso partner app =" + hreq.getContextPath()); } //T2 // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } //T9 // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { logg("T9 ressource non ssois (accs libre)"); filterChain.doFilter(hreq, hres); return; } // Get our session ... HttpSession session = hreq.getSession(true); testCookieSession(hreq); //TA1 pas de cookie et on trouve la page de login attendue dans la dclaration du contexte agent logg("TA1 uri=" + hreq.getRequestURI() + " se termine par " + cfg.getLoginPage() + " rep=" + hreq.getRequestURI().endsWith(cfg.getLoginPage()) + " test cookie=" + testCookie2Session(hreq, session.getId())); if (!testCookie2Session(hreq, session.getId()) && hreq.getRequestURI().endsWith(cfg.getLoginPage())) { logg("TA1 on demande l'authentification locale on switche vers Josso"); Cookie gato = newJossoCookie2(hreq.getContextPath(), session.getId(), COOKIE_LOGIN); hres.addCookie(gato); String loginUrl = _agent.buildLoginUrl(hreq); hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); //response.setHeader("Location", jeVeux); hres.sendRedirect(loginUrl); return; } //T3 on revient aprs authentification russie et pour finalisation if (_agent.isSSOIDloged(jossoSessionId)) { iBoucle++; logg("T3 Info retour authentifi pour " + jossoSessionId + " faire retour vers " + theOriginal); SSOAgentRequest r = doMakeSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (debug == 1) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not supported : session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (debug == 1) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (debug == 1) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-"); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) { if (debug == 1) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, session); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (debug == 1) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (debug == 1) log.debug("SSO cookie is not present, but login optional process is not required"); } } try { logg("Avant sur webProgrammaticLogin -------------" + iBoucle); if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) { logg("Erreur sur webProgrammaticLogin"); } else { logg("Russite sur webProgrammaticLogin"); } logg("Aprs sur webProgrammaticLogin-------------" + iBoucle); } catch (Exception err) { logg("SSOAgentValve Erreur2 finalisation contexte securit", err); throw new ServletException(err); } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } //T4 // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (debug == 1) log.debug("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) { if (debug == 1) log.debug("T4 josso_login_request received for uri '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) { saveLoginBackToURL(hreq, session, true); } else { saveLoginBackToURL(hreq, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (debug == 1) log.debug("T4 Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } //T5 // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (debug == 1) log.debug("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) { if (debug == 1) log.debug("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (debug == 1) log.debug("T5 Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-"); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } //T6 testCookieSession(hreq); //T7 // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (debug == 1) { log.debug("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) { if (debug == 1) { log.debug("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest( SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } //T8 // si pas de cookie de session SSO if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (debug == 1) log.debug("T8 SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (debug == 1) log.debug("T8-1 " + _agent.getJOSSOSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(session); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq)) { if (debug == 1) log.debug("T8-2 SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, session); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (debug == 1) log.debug("T8-2 Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (debug == 1) log.debug("T8-2 SSO cookie is not present, but login optional process is not required"); } } if (debug == 1) log.debug("T8-3 SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("T8-3 SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // This URI should be protected by SSO, go on ... if (debug == 1) log.debug("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (debug == 1) log.debug("Executing agent..."); //T10 /josso_security_check // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (debug == 1) log.debug("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (debug == 1) log.debug("T10 josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); GenericServletSSOAgentRequest relayRequest; if (debug == 1) log.debug("T10 Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error("T10-1 Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException("No Principal found. Verify your SSO Agent Configuration!"); } if (debug == 1) log.debug("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (debug == 1) log.debug("T10-2 Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(session); if (requestURI == null) { requestURI = getSavedRequestURL(session); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJOSSOSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (debug == 1) log.debug("T10 No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(session); _agent.clearAutomaticLoginReferer(hreq); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (debug == 1) log.debug("T10 Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (debug == 1) log.debug("T10 Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } _agent.addEntrySSOIDsuccessed(entry.ssoId, entry.getPrincipal().getName()); return; } } finally { if (debug == 1) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:com.tmwsoft.sns.web.action.MainAction.java
public ActionForward cp_common(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal"); Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig"); String op = Common.trim(request.getParameter("op")); if ("logout".equals(op)) { if (sGlobal.get("uhash").equals(request.getParameter("uhash"))) { int supe_uid = (Integer) sGlobal.get("supe_uid"); if (supe_uid > 0) { dataBaseService.executeUpdate("DELETE FROM sns_session WHERE uid=" + supe_uid); dataBaseService.executeUpdate("DELETE FROM sns_adminsession WHERE uid=" + supe_uid); }//from w w w . j a va2 s . c o m CookieHelper.clearCookie(request, response); CookieHelper.removeCookie(request, response, "_refer"); // session HttpSession session = request.getSession(); if (session.getAttribute("third") != null) { session.invalidate(); } } int allowRewrite = (Integer) sConfig.get("allowrewrite"); String indexPath = allowRewrite == 0 ? "portal.action" : "portal.html"; return showMessage(request, response, "security_exit", indexPath, 1, ""); } else if ("seccode".equals(op)) { if (mainService.checkSeccode(request, response, sGlobal, sConfig, request.getParameter("code"))) { return showMessage(request, response, "succeed"); } else { return showMessage(request, response, "incorrect_code"); } } else if ("report".equals(op)) { String idType = Common.trim(request.getParameter("idtype")); int id = Common.intval(request.getParameter("id")); String[] idTypes = { "picid", "blogid", "albumid", "tagid", "tid", "sid", "uid", "pid", "eventid", "comment", "post" }; if (!Common.in_array(idTypes, idType)) { return showMessage(request, response, "report_error"); } Map space = (Map) request.getAttribute("space"); List<Map<String, Object>> query = dataBaseService .executeQuery("SELECT * FROM sns_report WHERE id='" + id + "' AND idtype='" + idType + "'"); Map uidArr = null; Map<String, Object> report = null; if (query.size() > 0) { report = query.get(0); uidArr = Serializer.unserialize((String) report.get("uids"), false); if (!Common.empty(uidArr.get(space.get("uid")))) { return showMessage(request, response, "repeat_report"); } } else { uidArr = new HashMap(); report = new HashMap<String, Object>(); } try { if (submitCheck(request, "reportsubmit")) { String reason = Common.getStr(request.getParameter("reason"), 150, true, true, false, 0, 0, request, response); reason = "<li><strong><a href=\"zone.action?uid=" + space.get("uid") + "\" target=\"_blank\">" + sGlobal.get("supe_username") + "</a>:</strong> " + reason + " (" + Common.sgmdate(request, "MM-dd HH:mm", (Integer) sGlobal.get("timestamp")) + ")</li>"; uidArr.put(space.get("uid"), space.get("username")); String uids = Common.addSlashes(Serializer.serialize(uidArr)); if (Common.empty(report)) { Map<String, Object> setarr = new HashMap<String, Object>(); setarr.put("id", id < 0 ? 0 : id); setarr.put("idtype", idType); setarr.put("num", 1); setarr.put("new", 1); setarr.put("reason", reason); setarr.put("uids", uids); setarr.put("dateline", sGlobal.get("timestamp")); dataBaseService.insertTable("sns_report", setarr, false, false); } else { reason = Common.addSlashes((String) report.get("reason")) + reason; dataBaseService.executeUpdate("UPDATE sns_report SET num=num+1, reason='" + reason + "', dateline='" + sGlobal.get("timestamp") + "', uids='" + uids + "' WHERE rid='" + report.get("rid") + "'"); } return showMessage(request, response, "report_success"); } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } Integer num = (Integer) report.get("num"); if (num != null && num < 1) { return showMessage(request, response, "the_normal_information"); } String reason = Common.getData("reason"); if (reason != null) { String[] reasonArr = reason.replaceAll("(\\s*(\r\n|\n\r|\n|\r)\\s*)", "\r\n").trim().split("\r\n"); if (Common.isArray(reasonArr) && reasonArr.length == 1 && Common.empty(reasonArr[0])) { reasonArr = null; } request.setAttribute("reason", reasonArr); } request.setAttribute("idType", idType); request.setAttribute("id", id); } else if ("ignore".equals(op)) { String type = Common.trim(request.getParameter("type")).replaceAll("[^0-9a-zA-Z\\_\\-\\.]", ""); try { if (submitCheck(request, "ignoresubmit")) { int authorId = Common.intval(request.getParameter("authorid")); if (!Common.empty(type)) { Map space = (Map) request.getAttribute("space"); Map privacy = (Map) space.get("privacy"); String typeUid = type + "|" + authorId; if (Common.empty(privacy.get("filter_note")) || !Common.isArray(privacy.get("filter_note"))) { privacy.put("filter_note", new HashMap()); } Map filterNote = (Map) privacy.get("filter_note"); filterNote.put(typeUid, typeUid); mainService.privacyUpdate(privacy, (Integer) sGlobal.get("supe_uid")); } return showMessage(request, response, "do_success", request.getParameter("refer")); } } catch (Exception e) { return showMessage(request, response, e.getMessage()); } String formId = Common.getRandStr(8, false); request.setAttribute("formid", formId); request.setAttribute("type", type); } else if ("getuserapp".equals(op)) { ArrayList myUserApp = new ArrayList(); if (Common.empty(request.getParameter("subop"))) { Iterator it = ((Map) sGlobal.get("my_userapp")).keySet().iterator(); Map userApp = (Map) sGlobal.get("userapp"); while (it.hasNext()) { Map value = (Map) it.next(); if (!Common.empty(value.get("allowsidenav")) && userApp.containsKey(value.get("appid"))) { myUserApp.add(value); } } } else { myUserApp = (ArrayList) sGlobal.get("my_menu"); } request.setAttribute("my_userapp", myUserApp); } else if ("closefeedbox".equals(op)) { CookieHelper.setCookie(request, response, "closefeedbox", "1"); } else if ("changetpl".equals(op)) { String dir = Common.trim(request.getParameter("name")).replace(".", ""); if (!Common.empty(dir)) { File file = new File(SysConstants.snsRoot + "/template/" + dir + "/style.css"); if (file.exists()) { CookieHelper.setCookie(request, response, "mytemplate", dir, 365 * 24 * 3600); } } return showMessage(request, response, "do_success", "zone.action?do=home", 0); } return include(request, response, sConfig, sGlobal, "cp_common.jsp"); }
From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java
protected void doChangePassword(HttpServletRequest req, HttpServletResponse resp) throws Exception { logger.info("doChangePassword"); try {/*from w w w. ja v a 2s . c om*/ HttpSession session = req.getSession(false); if (session == null) { logger.debug("null session"); // this shouldn't happen, make the user start over resp.sendRedirect("./jsp/loggedOut.jsp"); return; } session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, ""); String username = req.getParameter("userid"); if (username != null) { username = username.toUpperCase(); } String oldPassword = req.getParameter("pswd"); String newPassword = req.getParameter("newpswd1"); String newPassword2 = req.getParameter("newpswd2"); logger.debug("doChangePassword:username " + username); //begin - CADSRPASSW-73 String status = ""; try { logger.info("doChangePassword: checking account status ..."); status = doValidateAccountStatus(username, session, req, resp, "./jsp/changePassword.jsp"); logger.debug("doChangePassword: account status check done"); } catch (Exception e1) { logger.debug("doChangePassword: account status was: [" + status + "]"); if (status != null && status.equals("")) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } else { logger.debug("doChangePassword: account status check error was: " + e1.getMessage()); e1.printStackTrace(); } } //end - CADSRPASSW-73 if (status.indexOf(Constants.LOCKED_STATUS) > -1) { logger.debug("doChangePassword:status [" + status + "] returning without doing anything ..."); return; } //CADSRPASSW-50 if (status.equals(Constants.EXPIRED_STATUS)) { connect(); PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource); try { try { if (!userDAO.checkValidUser(username)) { //incorrect user id session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } //begin - CADSRPASSW-97 if (!ConnectionUtil.isExpiredAccount(username, oldPassword)) { //meaning incorrect password session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 resp.sendRedirect("./jsp/changePassword.jsp"); return; } //end - CADSRPASSW-97 } catch (Exception e) { e.printStackTrace(); logger.error(e); } finally { disconnect(); } } catch (Exception e) { e.printStackTrace(); } finally { disconnect(); } } else { UserBean userBean = null; connect(); PasswordChangeDAO loginDAO = new PasswordChangeDAO(datasource); userBean = loginDAO.checkValidUser(username, oldPassword); disconnect(); session.setAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE, userBean); logger.debug("validUser " + userBean.isLoggedIn()); logger.debug("resultCode " + userBean.getResult().getResultCode().toString()); if (!userBean.isLoggedIn()) { String errorMessage1 = userBean.getResult().getMessage(); logger.debug("errorMessage " + errorMessage1); if (userBean.getResult().getResultCode() != ResultCode.LOCKED_OUT) { //CADSRPASSW-60 status = doValidateAccountStatus(username, session, req, resp, "./jsp/changePassword.jsp"); if (status.indexOf(Constants.LOCKED_STATUS) > -1) { logger.debug("doChangePassword:status [" + status + "] returning without doing anything ..."); return; } session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102")); } else { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.103")); } resp.sendRedirect(Constants.CHANGE_PASSWORD_URL + "?donotclear"); return; } } //begin CADSRPASSW-16 // Map<String, String> userQuestions = new HashMap<String, String>(); // Map<String, String> userAnswers = new HashMap<String, String>(); // loadUserStoredQna(username, userQuestions, userAnswers); // if(userQuestions.size() == 0) { // logger.info("no security question found"); // String msg = Messages.getString("PasswordChangeHelper.136"); // session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, msg); // resp.sendRedirect("./jsp/changePassword.jsp"); // return; // } //end CADSRPASSW-16 //=== begin of moved down (CADSRPASSW-48) if (Messages.getString("PasswordChangeHelper.3").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.3")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.4").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.4")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.5").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.5")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } //begin - CADSRPASSW-88 if (Messages.getString("PasswordChangeHelper.6").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.6")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } //end - CADSRPASSW-88 if (Messages.getString("PasswordChangeHelper.7").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { logger.debug("entered username doesn't match session " + username + " " + req.getParameter("userid").toUpperCase()); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.7")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } if (Messages.getString("PasswordChangeHelper.8").equals(PasswordChangeHelper.validateChangePassword( username, oldPassword, newPassword, newPassword2, username, req.getParameter("newpswd2")))) { logger.debug("new password mis-typed"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.8")); resp.sendRedirect("./jsp/changePassword.jsp"); return; } //=== end of moved down (CADSRPASSW-48) connect(); PasswordChangeDAO changeDAO = new PasswordChangeDAO(datasource); Result passwordChangeResult = changeDAO.changePassword(username, oldPassword, newPassword); disconnect(); if (passwordChangeResult.getResultCode() == ResultCode.PASSWORD_CHANGED) { logger.info("password changed"); resetUserStoredAttemptedCount(username); //CADSRPASSW-42 logger.debug("answer count reset"); connect(); PasswordNotifyDAO dao = new PasswordNotifyDAO(datasource); User usr = new User(); usr.setUsername(username); logger.debug("doChangePassword: removing the user [" + usr.getUsername() + "] removed from the notification queue ..."); dao.removeQueue(usr); //CADSRPASSW-72 logger.info( "doChangePassword: user [" + usr.getUsername() + "] removed from the notification queue"); resetUserStoredAttemptedCount(username); //CADSRPASSW-70 logger.debug("notification queue removed"); session.invalidate(); // they are done, log them out resp.sendRedirect("./jsp/passwordChanged.jsp"); } else { logger.info("password change failed"); String errorMessage = passwordChangeResult.getMessage(); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, errorMessage); resp.sendRedirect("./jsp/changePassword.jsp"); } } catch (Throwable theException) { logger.error(theException); } }
From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.MainServlet.java
protected void doSaveQuestions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, Exception { logger.info("doSaveQuestions"); try {//from www. j a va 2s. c o m // req.getSession().invalidate(); //invalid session everytime // HttpSession session = req.getSession(true); HttpSession session = req.getSession(false); //caDSR Password Change Station CADSRPASSW-43 Reset security questions/answers are the same if (session == null) { logger.debug("null session"); // this shouldn't happen, make the user start over resp.sendRedirect("./jsp/loggedOut.jsp"); return; } // Security enhancement int paramCount = 0; String loginID = req.getParameter("userid"); //CADSRPASSW-40 if (loginID != null) { loginID = loginID.toUpperCase(); } String question1 = req.getParameter("question1"); String answer1 = req.getParameter("answer1"); String question2 = req.getParameter("question2"); String answer2 = req.getParameter("answer2"); String question3 = req.getParameter("question3"); String answer3 = req.getParameter("answer3"); //begin - CADSRPASSW-73 String status = ""; try { logger.info("doSaveQuestions: checking account status ..."); status = doValidateAccountStatus(loginID, session, req, resp, "./jsp/setupPassword.jsp"); logger.debug("doSaveQuestions: account status check done"); } catch (Exception e1) { logger.debug("doSaveQuestions: account status was: [" + status + "]"); if (status != null && status.equals("")) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101")); resp.sendRedirect("./jsp/setupPassword.jsp"); return; } else { logger.debug("doSaveQuestions: account status check error was: " + e1.getMessage()); e1.printStackTrace(); } } //end - CADSRPASSW-73 if (status.indexOf(Constants.LOCKED_STATUS) > -1) { logger.debug("doSaveQuestions:status [" + status + "] returning without doing anything ..."); return; } //"remember" the questions selected by the user String selectedQ[] = { question1, question2, question3 }; handleQuestionsOptions(req, selectedQ); req.getSession().setAttribute("userid", loginID); //CADSRPASSW-40 session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, ""); UserBean userBean = (UserBean) session.getAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE); // String username = req.getParameter("userid"); String password = req.getParameter("password"); //xss prevention (http://ha.ckers.org/xss.html) if (!StringEscapeUtils.escapeHtml4(answer1).equals(answer1) || !StringEscapeUtils.escapeHtml4(answer2).equals(answer2) || !StringEscapeUtils.escapeHtml4(answer3).equals(answer3)) { logger.debug("invalid character failed during questions/answers save"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.160")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } //DoS attack using string length overflow if (!CommonUtil.truncate(answer1, Constants.MAX_ANSWER_LENGTH).equals(answer1) || !CommonUtil.truncate(answer2, Constants.MAX_ANSWER_LENGTH).equals(answer2) || !CommonUtil.truncate(answer3, Constants.MAX_ANSWER_LENGTH).equals(answer3) || !CommonUtil.truncate(question1, Constants.MAX_ANSWER_LENGTH).equals(question1) || !CommonUtil.truncate(question2, Constants.MAX_ANSWER_LENGTH).equals(question2) || !CommonUtil.truncate(question3, Constants.MAX_ANSWER_LENGTH).equals(question3)) { logger.debug("invalid answer(s) length during questions/answers save"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.112")); // req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } logger.debug("saveQuestions:username " + loginID); //CADSRPASSW-54 CADSRPASSW-82 // if(ConnectionUtil.isExpiredAccount(loginID, password)) { // logger.debug("expired password status for userid " + loginID); // session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.104")); // //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 // req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); // return; // } //CADSRPASSW-49 if (status != null && status.indexOf(Constants.EXPIRED_STATUS) > -1) { connect(); PasswordChangeDAO userDAO = new PasswordChangeDAO(datasource); try { if (!userDAO.checkValidUser(loginID)) { //incorrect user id session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.101")); req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } //CADSRPASSW-82 if (!ConnectionUtil.isExpiredAccount(loginID, password)) { //meaning incorrect password session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } } catch (Exception e) { e.printStackTrace(); } finally { disconnect(); } } else { connect(); PasswordChangeDAO loginDAO = new PasswordChangeDAO(datasource); userBean = loginDAO.checkValidUser(loginID, password); disconnect(); session.setAttribute(UserBean.USERBEAN_SESSION_ATTRIBUTE, userBean); logger.debug("validUser" + userBean.isLoggedIn()); logger.debug("resultCode " + userBean.getResult().getResultCode().toString()); if (!userBean.isLoggedIn()) { logger.debug("auth failed during questions/answers save"); if (userBean.getResult().getResultCode() != ResultCode.LOCKED_OUT) { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.102")); } else { session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.103")); } //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } } // Security enhancement Map<String, String> userQuestions = new HashMap<String, String>(); userQuestions.put(question1, ""); userQuestions.put(question2, ""); userQuestions.put(question3, ""); if (question1 != null && !question1.equals("")) paramCount++; if (question2 != null && !question2.equals("")) paramCount++; if (question3 != null && !question3.equals("")) paramCount++; if (userQuestions.size() < TOTAL_QUESTIONS && paramCount == TOTAL_QUESTIONS) { logger.debug("security Q&A validation failed"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.135")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } userQuestions = new HashMap<String, String>(); Map<String, String> userAnswers = new HashMap<String, String>(); if (question1 != null && !question1.equals("") && answer1 != null && !answer1.equals("")) userQuestions.put(Constants.Q1, question1); userAnswers.put(Constants.A1, answer1); if (question2 != null && !question2.equals("") && answer2 != null && !answer2.equals("")) userQuestions.put(Constants.Q2, question2); userAnswers.put(Constants.A2, answer2); if (question3 != null && !question3.equals("") && answer3 != null && !answer3.equals("")) userQuestions.put(Constants.Q3, question3); userAnswers.put(Constants.A3, answer3); logger.debug("saving request: " + question1 + "=" + answer1 + " " + question2 + "=" + answer2 + " " + question3 + "=" + answer3); if (Messages.getString("PasswordChangeHelper.125").equals(PasswordChangeHelper .validateSecurityQandA(TOTAL_QUESTIONS, loginID, userQuestions, userAnswers))) { logger.debug("security Q&A validation failed"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.125")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } if (!PasswordChangeHelper.validateQuestionsLength(TOTAL_QUESTIONS, userQuestions, userAnswers)) { logger.debug("security Q&A validation failed"); session.setAttribute(ERROR_MESSAGE_SESSION_ATTRIBUTE, Messages.getString("PasswordChangeHelper.150")); //req.getRequestDispatcher(Constants.SETUP_QUESTIONS_URL).forward(req, resp); //didn't work for jboss 4.0.5 req.getRequestDispatcher("./jsp/setupPassword.jsp").forward(req, resp); return; } logger.info("saving request: user provided " + userQuestions + " " + userAnswers); saveUserStoredQna(loginID, userQuestions, userAnswers); //TBD - retrieve all questions related to the users from dao and set them into sessions session.setAttribute(Constants.USERNAME, loginID); session.invalidate(); resp.sendRedirect(Constants.SETUP_SAVED_URL); } catch (Throwable theException) { logger.error(theException); } }
From source file:com.sundevils.web.controller.TopController.java
@RequestMapping(value = "/updateAllow", method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView updateAllow(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws SQLException { String role = (String) session.getAttribute("Role"); ModelAndView model = null;//from w w w . jav a 2 s . c o m ResultSet result_from = null; String[] deleteRequests = null; ResultSet result = null; String ViewRequests = null; try { if (role == null) { model = new ModelAndView(); model.setViewName("index"); return model; } else if (role.equals("MANAGER")) { String toUserName = ""; String fromUserName = ""; String firstname = ""; String lastName = ""; String middleName = ""; String firstname_Recipient = ""; String lastName_Recipient = ""; String middleName_Recipient = ""; String userType = ""; String type = ""; String status = ""; String forUser = ""; String email = ""; fromUserName = (String) session.getAttribute("USERNAME"); transactionViewRequestHandler handler_request = new transactionViewRequestHandler(); model = new ModelAndView(); List<TransactionRequestDetails> transReqstdetails = new ArrayList<TransactionRequestDetails>(); if (request.getParameter("submitDelete") != null) { model = new ModelAndView(); deleteRequests = request.getParameterValues("check"); if (deleteRequests == null) { model.setViewName("allowViewRequests"); model.addObject("Select", "No request selected"); ResultSet rs = handler_request.getRequestHandler(fromUserName); try { while (rs.next()) { TransactionRequestDetails view = new TransactionRequestDetails(); view.setRequstID(rs.getString("requestid")); view.setRqstTo(rs.getString("requestto")); view.setRqstFrom(rs.getString("requestfrom")); view.setRqstFor(rs.getString("requestfor")); view.setRqstType(rs.getString("requesttype")); view.setRqstTime(rs.getString("requestdate")); view.setRqstStatus(rs.getString("requeststatus")); transReqstdetails.add(view); } model.addObject("requestDetails", transReqstdetails); } catch (SQLException e) { LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("login"); LOG.error("Issue while accessing the requests" + e.getMessage()); } } transactionViewRequestHandler handler = new transactionViewRequestHandler(); handler.transactionDeleteHandler(deleteRequests); return model; } if (request.getParameter("submitView") != null) { model = new ModelAndView(); ViewRequests = request.getParameter("radio"); if (ViewRequests == null) { model.setViewName("allowViewRequests"); model.addObject("SelectView", "No User selected"); model.setViewName("allowViewRequests"); ResultSet rs = handler_request.getRequestHandler(fromUserName); try { while (rs.next()) { TransactionRequestDetails view = new TransactionRequestDetails(); view.setRequstID(rs.getString("requestid")); view.setRqstTo(rs.getString("requestto")); view.setRqstFrom(rs.getString("requestfrom")); view.setRqstFor(rs.getString("requestfor")); view.setRqstType(rs.getString("requesttype")); view.setRqstTime(rs.getString("requestdate")); view.setRqstStatus(rs.getString("requeststatus")); transReqstdetails.add(view); } model.addObject("requestDetails", transReqstdetails); } catch (SQLException e) { LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("login"); LOG.error("Issue while accessing the requests" + e.getMessage()); } return model; } transactionViewRequestHandler handler = new transactionViewRequestHandler(); ResultSet rs = handler.transactionViewHandler(ViewRequests); try { while (rs.next()) { TransactionRequestDetails view = new TransactionRequestDetails(); view.setUserName(rs.getString("username")); view.setTransactionID(rs.getString("transactionid")); view.setTransactionAmount(rs.getString("transactionamount")); view.setSourceAccount(rs.getString("sourceaccountnumber")); view.setDestAccount(rs.getString("destinationaccountnumber")); view.setDateandTime(rs.getString("dateandtime")); view.setTransferType(rs.getString("transfertype")); view.setStatus(rs.getString("status")); transReqstdetails.add(view); } model.addObject("requestView", transReqstdetails); //request.setAttribute(", o); } catch (SQLException e) { // TODO Auto-generated catch block LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("login"); LOG.error("Issue while accessing the requests" + e.getMessage()); } model.setViewName("ViewTransactions"); return model; } if (request.getParameter("submit") != null) { forUser = request.getParameter("username"); userType = request.getParameter("userType"); toUserName = request.getParameter("adminID"); fromUserName = (String) session.getAttribute("USERNAME"); ValidateUserhandler validate_Handler = new ValidateUserhandler(); result = validate_Handler.ValidateHandler(forUser); result_from = validate_Handler.ValidateHandler(fromUserName); result_from.next(); if (result.next()) { ResultSet rsStatus = handler_request.getRequestStatusHandler(forUser, fromUserName); while (rsStatus.next()) { if (rsStatus.getString("requeststatus").equals("Pending")) { status = rsStatus.getString("requeststatus"); break; } else status = rsStatus.getString("requeststatus"); } type = result.getString("Usertype"); email = result.getString("Email"); firstname_Recipient = result.getString("Firstname"); middleName_Recipient = result.getString("Middlename"); lastName_Recipient = result.getString("Lastname"); firstname = result_from.getString("Firstname"); middleName = result_from.getString("Middlename"); lastName = result_from.getString("Lastname"); if (type.equals("USER")) { if (!status.equals("Pending")) { updateAllowHandler handler = new updateAllowHandler(); if (toUserName.isEmpty()) { toUserName = forUser; OtpUtility.sendEmailViewRequest(email, role, "", firstname, middleName, lastName, "", "", "", ""); String date = TimeUtility.generateSysDateMethod(); handler.requestUpdateHandler(forUser, fromUserName, toUserName, "View", date); } else { ResultSet result_next = validate_Handler.ValidateHandler(toUserName); if (result_next.next()) { type = result_next.getString("Usertype"); email = result_next.getString("Email"); OtpUtility.sendEmailViewRequest(email, role, fromUserName, firstname, middleName, lastName, forUser, firstname_Recipient, middleName_Recipient, lastName_Recipient); if (type.equals(userType)) { String date = TimeUtility.generateSysDateMethod(); handler.requestUpdateHandler(forUser, fromUserName, toUserName, "View", date); } } else model.addObject("AdminStatus", "Invalid Admin ID"); } } else { model.addObject("Status", "User already has Pending request"); } } else { model.addObject("Validity", "Invalid Recipient"); } } else { model.addObject("Validity", "Invalid Recipient"); } //result.next(); } ResultSet rs = handler_request.getRequestHandler(fromUserName); try { while (rs.next()) { TransactionRequestDetails view = new TransactionRequestDetails(); view.setRequstID(rs.getString("requestid")); view.setRqstTo(rs.getString("requestto")); view.setRqstFrom(rs.getString("requestfrom")); view.setRqstFor(rs.getString("requestfor")); view.setRqstType(rs.getString("requesttype")); view.setRqstTime(rs.getString("requestdate")); view.setRqstStatus(rs.getString("requeststatus")); transReqstdetails.add(view); } model.addObject("requestDetails", transReqstdetails); } catch (SQLException e) { LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("login"); LOG.error("Issue while accessing the requests" + e.getMessage()); } model.setViewName("allowViewRequests"); return model; } else { model = new ModelAndView(); LoginHandler handler = new LoginHandler(); String userName = (String) session.getAttribute("USERNAME"); handler.updateLoggedInFlag(userName, 0); session.invalidate(); model.setViewName("index"); return model; } } catch (Exception e) { model = new ModelAndView(); LoginHandler handler_logout; handler_logout = new LoginHandler(); String userSessionName = (String) session.getAttribute("USERNAME"); handler_logout.updateLoggedInFlag(userSessionName, 0); model.setViewName("login"); LOG.error("Issue while accessing the requests" + e.getMessage()); } finally { if (result != null) { result.close(); } if (result_from != null) { result_from.close(); } } return model; }
From source file:org.apache.jsp.html.portal.error_jsp.java
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null;//w w w . j av a 2 s.co m HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; /** * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ out.write('\n'); out.write('\n'); /** * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ out.write('\n'); out.write('\n'); /** * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); // liferay-theme:defineObjects com.liferay.taglib.theme.DefineObjectsTag _jspx_th_liferay_002dtheme_005fdefineObjects_005f0 = (com.liferay.taglib.theme.DefineObjectsTag) _005fjspx_005ftagPool_005fliferay_002dtheme_005fdefineObjects_005fnobody .get(com.liferay.taglib.theme.DefineObjectsTag.class); _jspx_th_liferay_002dtheme_005fdefineObjects_005f0.setPageContext(_jspx_page_context); _jspx_th_liferay_002dtheme_005fdefineObjects_005f0.setParent(null); int _jspx_eval_liferay_002dtheme_005fdefineObjects_005f0 = _jspx_th_liferay_002dtheme_005fdefineObjects_005f0 .doStartTag(); if (_jspx_th_liferay_002dtheme_005fdefineObjects_005f0 .doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fliferay_002dtheme_005fdefineObjects_005fnobody .reuse(_jspx_th_liferay_002dtheme_005fdefineObjects_005f0); return; } _005fjspx_005ftagPool_005fliferay_002dtheme_005fdefineObjects_005fnobody .reuse(_jspx_th_liferay_002dtheme_005fdefineObjects_005f0); com.liferay.portal.theme.ThemeDisplay themeDisplay = null; com.liferay.portal.model.Company company = null; com.liferay.portal.model.Account account = null; com.liferay.portal.model.User user = null; com.liferay.portal.model.User realUser = null; com.liferay.portal.model.Contact contact = null; com.liferay.portal.model.Layout layout = null; java.util.List layouts = null; java.lang.Long plid = null; com.liferay.portal.model.LayoutTypePortlet layoutTypePortlet = null; java.lang.Long scopeGroupId = null; com.liferay.portal.security.permission.PermissionChecker permissionChecker = null; java.util.Locale locale = null; java.util.TimeZone timeZone = null; com.liferay.portal.model.Theme theme = null; com.liferay.portal.model.ColorScheme colorScheme = null; com.liferay.portal.theme.PortletDisplay portletDisplay = null; java.lang.Long portletGroupId = null; themeDisplay = (com.liferay.portal.theme.ThemeDisplay) _jspx_page_context.findAttribute("themeDisplay"); company = (com.liferay.portal.model.Company) _jspx_page_context.findAttribute("company"); account = (com.liferay.portal.model.Account) _jspx_page_context.findAttribute("account"); user = (com.liferay.portal.model.User) _jspx_page_context.findAttribute("user"); realUser = (com.liferay.portal.model.User) _jspx_page_context.findAttribute("realUser"); contact = (com.liferay.portal.model.Contact) _jspx_page_context.findAttribute("contact"); layout = (com.liferay.portal.model.Layout) _jspx_page_context.findAttribute("layout"); layouts = (java.util.List) _jspx_page_context.findAttribute("layouts"); plid = (java.lang.Long) _jspx_page_context.findAttribute("plid"); layoutTypePortlet = (com.liferay.portal.model.LayoutTypePortlet) _jspx_page_context .findAttribute("layoutTypePortlet"); scopeGroupId = (java.lang.Long) _jspx_page_context.findAttribute("scopeGroupId"); permissionChecker = (com.liferay.portal.security.permission.PermissionChecker) _jspx_page_context .findAttribute("permissionChecker"); locale = (java.util.Locale) _jspx_page_context.findAttribute("locale"); timeZone = (java.util.TimeZone) _jspx_page_context.findAttribute("timeZone"); theme = (com.liferay.portal.model.Theme) _jspx_page_context.findAttribute("theme"); colorScheme = (com.liferay.portal.model.ColorScheme) _jspx_page_context.findAttribute("colorScheme"); portletDisplay = (com.liferay.portal.theme.PortletDisplay) _jspx_page_context .findAttribute("portletDisplay"); portletGroupId = (java.lang.Long) _jspx_page_context.findAttribute("portletGroupId"); out.write('\n'); out.write('\n'); /** * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write('\n'); out.write('\n'); Boolean staleSession = (Boolean) session.getAttribute(WebKeys.STALE_SESSION); String userLogin = user.getEmailAddress(); if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_SN)) { userLogin = user.getScreenName(); } else if (company.getAuthType().equals(CompanyConstants.AUTH_TYPE_ID)) { userLogin = String.valueOf(user.getUserId()); } out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f0.setParent(null); // /html/portal/error.jsp(32,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f0.setTest((staleSession != null) && staleSession.booleanValue()); int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag(); if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f0(_jspx_th_c_005fif_005f0, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); out.write("\n"); out.write("\t"); session.invalidate(); out.write('\n'); out.write('\n'); int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f1.setParent(null); // /html/portal/error.jsp(43,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f1 .setTest(SessionErrors.contains(request, LayoutPermissionException.class.getName())); int _jspx_eval_c_005fif_005f1 = _jspx_th_c_005fif_005f1.doStartTag(); if (_jspx_eval_c_005fif_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f1(_jspx_th_c_005fif_005f1, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); int evalDoAfterBody = _jspx_th_c_005fif_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f1); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f1); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f2 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f2.setParent(null); // /html/portal/error.jsp(49,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f2 .setTest(SessionErrors.contains(request, PortletActiveException.class.getName())); int _jspx_eval_c_005fif_005f2 = _jspx_th_c_005fif_005f2.doStartTag(); if (_jspx_eval_c_005fif_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f2(_jspx_th_c_005fif_005f2, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); int evalDoAfterBody = _jspx_th_c_005fif_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f2); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f2); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f3 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f3.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f3.setParent(null); // /html/portal/error.jsp(55,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f3.setTest(SessionErrors.contains(request, PrincipalException.class.getName())); int _jspx_eval_c_005fif_005f3 = _jspx_th_c_005fif_005f3.doStartTag(); if (_jspx_eval_c_005fif_005f3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f3(_jspx_th_c_005fif_005f3, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); int evalDoAfterBody = _jspx_th_c_005fif_005f3.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f3); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f3); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f4 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f4.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f4.setParent(null); // /html/portal/error.jsp(61,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f4 .setTest(SessionErrors.contains(request, RequiredLayoutException.class.getName())); int _jspx_eval_c_005fif_005f4 = _jspx_th_c_005fif_005f4.doStartTag(); if (_jspx_eval_c_005fif_005f4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f4(_jspx_th_c_005fif_005f4, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); int evalDoAfterBody = _jspx_th_c_005fif_005f4.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f4); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f4); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f5 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f5.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f5.setParent(null); // /html/portal/error.jsp(67,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f5.setTest(SessionErrors.contains(request, RequiredRoleException.class.getName())); int _jspx_eval_c_005fif_005f5 = _jspx_th_c_005fif_005f5.doStartTag(); if (_jspx_eval_c_005fif_005f5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); if (_jspx_meth_liferay_002dui_005fmessage_005f5(_jspx_th_c_005fif_005f5, _jspx_page_context)) return; out.write("\n"); out.write("\t</div>\n"); int evalDoAfterBody = _jspx_th_c_005fif_005f5.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f5); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f5); out.write('\n'); out.write('\n'); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f6 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest .get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f6.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f6.setParent(null); // /html/portal/error.jsp(73,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f6.setTest(SessionErrors.contains(request, UserActiveException.class.getName())); int _jspx_eval_c_005fif_005f6 = _jspx_th_c_005fif_005f6.doStartTag(); if (_jspx_eval_c_005fif_005f6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t<div class=\"portlet-msg-error\">\n"); out.write("\t\t"); out.print(LanguageUtil.format(pageContext, "your-account-with-login-x-is-not-active", new LanguageWrapper[] { new LanguageWrapper("", HtmlUtil.escape(user.getFullName()), ""), new LanguageWrapper("<strong><em>", HtmlUtil.escape(userLogin), "</em></strong>") }, false)); out.write("<br /><br />\n"); out.write("\t</div>\n"); out.write("\n"); out.write("\t"); out.print(LanguageUtil.format(pageContext, "if-you-are-not-x-logout-and-try-again", HtmlUtil.escape(user.getFullName()), false)); out.write('\n'); int evalDoAfterBody = _jspx_th_c_005fif_005f6.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f6); return; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f6); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) { } if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
From source file:org.kchine.r.server.http.frontend.CommandServlet.java
protected void doAny(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = null; Object result = null;/*from w ww. j a va 2 s. com*/ try { final String command = request.getParameter("method"); do { if (command.equals("ping")) { result = "pong"; break; } else if (command.equals("logon")) { session = request.getSession(false); if (session != null) { result = session.getId(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); boolean namedAccessMode = login.contains("@@"); String sname = null; if (namedAccessMode) { sname = login.substring(login.indexOf("@@") + "@@".length()); login = login.substring(0, login.indexOf("@@")); } System.out.println("login :" + login); System.out.println("pwd :" + pwd); if (_rkit == null && (!login.equals(System.getProperty("login")) || !pwd.equals(System.getProperty("pwd")))) { result = new BadLoginPasswordException(); break; } HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); RPFSessionInfo.get().put("LOGIN", login); RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr()); RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost()); boolean nopool = !options.keySet().contains("nopool") || ((String) options.get("nopool")).equals("") || !((String) options.get("nopool")).equalsIgnoreCase("false"); boolean save = options.keySet().contains("save") && ((String) options.get("save")).equalsIgnoreCase("true"); boolean selfish = options.keySet().contains("selfish") && ((String) options.get("selfish")).equalsIgnoreCase("true"); String privateName = (String) options.get("privatename"); int memoryMin = DEFAULT_MEMORY_MIN; int memoryMax = DEFAULT_MEMORY_MAX; try { if (options.get("memorymin") != null) memoryMin = Integer.decode((String) options.get("memorymin")); if (options.get("memorymax") != null) memoryMax = Integer.decode((String) options.get("memorymax")); } catch (Exception e) { e.printStackTrace(); } boolean privateEngineMode = false; RServices r = null; URL[] codeUrls = null; if (_rkit == null) { if (namedAccessMode) { try { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname); } } else { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname); } } } catch (Exception e) { e.printStackTrace(); } } else { if (nopool) { /* ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System .getProperty("private.servant.node.name"); Registry registry = spFactory.getServantProvider().getRegistry(); NodeManager nm = null; try { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName); } catch (NotBoundException nbe) { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name")); } catch (Exception e) { result = new NoNodeManagerFound(); break; } r = (RServices) nm.createPrivateServant(nodeName); */ if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class }); if (privateName != null && !privateName.equals("")) { try { r = (RServices) dbLayer.lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { final String uid = (privateName != null && !privateName.equals("")) ? privateName : UUID.randomUUID().toString(); final String[] jobIdHolder = new String[1]; new Thread(new Runnable() { public void run() { try { String command = "java -Dlog.file=" + System.getProperty("submit.ssh.biocep.home") + "/log/%{uid}.log" + " -Drmi.port.start=" + System.getProperty("submit.ssh.rmi.port.start") + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host=" + System.getProperty("submit.ssh.host") + " -Dwait=true" + " -jar " + System.getProperty("submit.ssh.biocep.home") + "/biocep-core.jar"; jobIdHolder[0] = SSHUtils.execSshBatch(command, uid, System.getProperty("submit.ssh.prefix"), System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home")); System.out.println("jobId:" + jobIdHolder[0]); } catch (Exception e) { e.printStackTrace(); } } }).start(); long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout")); long tStart = System.currentTimeMillis(); while ((System.currentTimeMillis() - tStart) < TIMEOUT) { try { r = (RServices) dbLayer.lookup(uid); } catch (Exception e) { } if (r != null) break; try { Thread.sleep(10); } catch (Exception e) { } } if (r != null) { try { r.setJobId(jobIdHolder[0]); } catch (Exception e) { r = null; } } } } else { System.out.println("LocalHttpServer.getLocalHttpServerPort():" + LocalHttpServer.getLocalHttpServerPort()); System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():" + LocalHttpServer.getLocalHttpServerPort()); if (privateName != null && !privateName.equals("")) { try { r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { codeUrls = (URL[]) options.get("urls"); System.out.println("CODE URL->" + Arrays.toString(codeUrls)); //String r = ServerManager.createR(System.getProperty("r.binary"), false, false, PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(), ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(), LocalRmiRegistry.getLocalRmiRegistryPort()), memoryMin, memoryMax, privateName, false, codeUrls, null, (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1"); } privateEngineMode = true; } } else { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy .getDynamicProxy(System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "servant.provider", new Class<?>[] { ServantProvider.class }); boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxy() : servantProvider.borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxyNoWait() : servantProvider.borrowServantProxyNoWait(poolname)); } System.out.println("---> borrowed : " + r); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxy() : spFactory.getServantProvider().borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxyNoWait() : spFactory.getServantProvider() .borrowServantProxyNoWait(poolname)); } } } } } else { r = _rkit.getR(); } if (r == null) { result = new NoServantAvailableException(); break; } session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "RS"); session.setAttribute("R", r); session.setAttribute("NOPOOL", nopool); session.setAttribute("SAVE", save); session.setAttribute("LOGIN", login); session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode); session.setAttribute("PROCESS_ID", r.getProcessId()); session.setAttribute("JOB_ID", r.getJobId()); session.setAttribute("SELFISH", selfish); session.setAttribute("IS_RELAY", _rkit != null); if (privateName != null) session.setAttribute("PRIVATE_NAME", privateName); if (codeUrls != null && codeUrls.length > 0) { session.setAttribute("CODEURLS", codeUrls); } session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext() .getAttribute("R_SESSIONS")).get(r); if (sessionVector == null) { sessionVector = new Vector<HttpSession>(); ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS")) .put(r, sessionVector); } sessionVector.add(session); if (_rkit == null && save) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r); } System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners()); if (selfish || !r.hasRCollaborationListeners()) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GDDevice[] devices = r.listDevices(); for (int i = 0; i < devices.length; ++i) { String deviceName = devices[i].getId(); System.out.println("??? ---- deviceName=" + deviceName); session.setAttribute(deviceName, devices[i]); } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } if (privateEngineMode) { if (options.get("newdevice") != null) { GDDevice deviceProxy = null; GDDevice[] dlist = r.listDevices(); if (dlist == null || dlist.length == 0) { deviceProxy = r.newDevice(480, 480); } else { deviceProxy = dlist[0]; } String deviceName = deviceProxy.getId(); session.setAttribute(deviceName, deviceProxy); session.setAttribute("maindevice", deviceProxy); saveSessionAttributes(session); } if (options.get("newgenericcallbackdevice") != null) { GenericCallbackDevice genericCallBackDevice = null; GenericCallbackDevice[] clist = r.listGenericCallbackDevices(); if (clist == null || clist.length == 0) { genericCallBackDevice = r.newGenericCallbackDevice(); } else { genericCallBackDevice = clist[0]; } String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); session.setAttribute("maingenericcallbackdevice", genericCallBackDevice); saveSessionAttributes(session); } } result = session.getId(); break; } else if (command.equals("logondb")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "DBS"); session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry()); session.setAttribute("SUPERVISOR", new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry())); session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); result = session.getId(); break; } session = request.getSession(false); if (session == null) { result = new NotLoggedInException(); break; } if (command.equals("logoff")) { if (session.getAttribute("TYPE").equals("RS")) { if (_rkit != null) { /* Enumeration<String> attributeNames = session.getAttributeNames(); while (attributeNames.hasMoreElements()) { String aname = attributeNames.nextElement(); if (session.getAttribute(aname) instanceof GDDevice) { try { _rkit.getRLock().lock(); ((GDDevice) session.getAttribute(aname)).dispose(); } catch (Exception e) { e.printStackTrace(); } finally { _rkit.getRLock().unlock(); } } } */ } } try { session.invalidate(); } catch (Exception ex) { ex.printStackTrace(); } result = null; break; } final boolean[] stop = { false }; final HttpSession currentSession = session; if (command.equals("invoke")) { String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname")); final Object servant = session.getAttribute(servantName); if (servant == null) { throw new Exception("Bad Servant Name :" + servantName); } String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname")); ClassLoader urlClassLoader = this.getClass().getClassLoader(); if (session.getAttribute("CODEURLS") != null) { urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"), this.getClass().getClassLoader()); } Class<?>[] methodSignature = (Class[]) PoolUtils .hexToObject(request.getParameter("methodsignature")); final Method m = servant.getClass().getMethod(methodName, methodSignature); if (m == null) { throw new Exception("Bad Method Name :" + methodName); } final Object[] methodParams = (Object[]) PoolUtils .hexToObject(request.getParameter("methodparameters"), urlClassLoader); final Object[] resultHolder = new Object[1]; Runnable rmiRunnable = new Runnable() { public void run() { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); resultHolder[0] = m.invoke(servant, methodParams); if (resultHolder[0] == null) resultHolder[0] = RMICALL_DONE; } catch (InvocationTargetException ite) { if (ite.getCause() instanceof ConnectException) { currentSession.invalidate(); resultHolder[0] = new NotLoggedInException(); } else { resultHolder[0] = ite.getCause(); } } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new RmiCallInterrupted(); } else { resultHolder[0] = e; } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } }; Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable); ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread); rmiThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) { rmiThread.interrupt(); resultHolder[0] = new RmiCallTimeout(); break; } try { Thread.sleep(10); } catch (Exception e) { } } try { ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread); } catch (IllegalStateException e) { } if (resultHolder[0] instanceof Throwable) { throw (Throwable) resultHolder[0]; } if (resultHolder[0] == RMICALL_DONE) { result = null; } else { result = resultHolder[0]; } break; } if (command.equals("interrupt")) { final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")) .getThreads().clone(); for (int i = 0; i < tvec.size(); ++i) { try { tvec.elementAt(i).interrupt(); } catch (Exception e) { e.printStackTrace(); } } stop[0] = true; ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads()) .removeAllElements(); result = null; break; } else if (command.equals("saveimage")) { UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("loadimage")) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("newdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); boolean broadcasted = new Boolean(request.getParameter("broadcasted")); GDDevice deviceProxy = null; if (broadcasted) { deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } else { deviceProxy = ((RServices) session.getAttribute("R")).newDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } String deviceName = deviceProxy.getId(); System.out.println("deviceName=" + deviceName); session.setAttribute(deviceName, deviceProxy); saveSessionAttributes(session); result = deviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("listdevices")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); result = new Vector<String>(); for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) { String attributeName = e.nextElement(); if (attributeName.startsWith("device_")) { ((Vector<String>) result).add(attributeName); } } break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newgenericcallbackdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R")) .newGenericCallbackDevice(); String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); saveSessionAttributes(session); result = genericCallBackDeviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newspreadsheetmodeldevice")) { String spreadsheetModelDeviceId = request.getParameter("id"); SpreadsheetModelRemote model = null; if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) { model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote( Integer.decode(request.getParameter("rowcount")), Integer.decode(request.getParameter("colcount"))); } else { model = ((RServices) session.getAttribute("R")) .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId); } SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice(); String spreadsheetDeviceId = spreadsheetDevice.getId(); session.setAttribute(spreadsheetDeviceId, spreadsheetDevice); saveSessionAttributes(session); result = spreadsheetDeviceId; break; } else if (command.equals("list")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } result = spFactory.getServantProvider().getRegistry().list(); break; } } while (true); } catch (TunnelingException te) { result = te; te.printStackTrace(); } catch (Throwable e) { result = new TunnelingException("Server Side", e); e.printStackTrace(); } response.setContentType("application/x-java-serialized-object"); new ObjectOutputStream(response.getOutputStream()).writeObject(result); response.flushBuffer(); }