List of usage examples for javax.servlet.http HttpSession getServletContext
public ServletContext getServletContext();
From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.SSOAssertionConsumerService.java
private void handleRequestFromLoginPage(HttpServletRequest req, HttpServletResponse resp, String ssoTokenID, String assertionConsumerUrl, String id, String issuer, String userName, String subject, String rpSession, String requestMsgString, String relayState) throws IOException, ServletException, SAML2SSOUIAuthenticatorException { HttpSession session = req.getSession(); // instantiate the service client String serverURL = CarbonUIUtil.getServerURL(session.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) session.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); SAMLSSOServiceClient ssoServiceClient = new SAMLSSOServiceClient(serverURL, configContext); // Create SAMLSSOAuthnReqDTO using the request Parameters SAMLSSOAuthnReqDTO authnReqDTO = new SAMLSSOAuthnReqDTO(); authnReqDTO.setAssertionConsumerURL(assertionConsumerUrl); authnReqDTO.setId(id);/*from www . j a v a2 s .co m*/ authnReqDTO.setIssuer(issuer); //TODO FIX NEED TO BE DONE authnReqDTO.setUser(null); authnReqDTO.setPassword("federated_idp_login"); authnReqDTO.setSubject(subject); authnReqDTO.setRpSessionId(rpSession); authnReqDTO.setRequestMessageString(requestMsgString); // authenticate the user SAMLSSORespDTO authRespDTO = ssoServiceClient.authenticate(authnReqDTO, ssoTokenID); if (authRespDTO.getSessionEstablished()) { // authentication is SUCCESSFUL // Store the cookie storeSSOTokenCookie(ssoTokenID, req, resp); // add relay state, assertion string and ACS URL as request parameters. req.setAttribute(SAMLConstants.RELAY_STATE, relayState); req.setAttribute(SAMLConstants.ASSERTION_STR, authRespDTO.getRespString()); req.setAttribute(SAMLConstants.ASSRTN_CONSUMER_URL, authRespDTO.getAssertionConsumerURL()); req.setAttribute(SAMLConstants.SUBJECT, authRespDTO.getSubject()); RequestDispatcher reqDispatcher = req .getRequestDispatcher("/carbon/sso-acs/federation_ajaxprocessor.jsp"); reqDispatcher.forward(req, resp); return; } }
From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.authenticator.SAML2SSOUIAuthenticator.java
public void unauthenticate(Object o) throws Exception { String auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_FAILED; HttpServletRequest request = null;//from w w w . ja v a2s . c om HttpSession session = null; if (o instanceof HttpSession) { session = (HttpSession) o; } else { request = (HttpServletRequest) o; session = request.getSession(); } String username = (String) session.getAttribute(CarbonConstants.LOGGED_USER); ServletContext servletContext = session.getServletContext(); ConfigurationContext configContext = (ConfigurationContext) servletContext .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String backendServerURL = CarbonUIUtil.getServerURL(servletContext, session); try { String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN); SAML2SSOAuthenticationClient authClient = new SAML2SSOAuthenticationClient(configContext, backendServerURL, cookie, session); authClient.logout(session); // // memory cleanup : remove the invalid session from the invalid session list at the SSOSessionManager // CarbonSSOSessionManager ssoSessionManager = // SAML2SSOAuthFEDataHolder.getInstance().getCarbonSSOSessionManager(); // ssoSessionManager.removeInvalidSession(session.getId()); if (request != null) { // this attribute is used to avoid generate the logout request request.setAttribute(SAML2SSOAuthenticatorConstants.HTTP_ATTR_IS_LOGOUT_REQ, Boolean.valueOf(true)); request.setAttribute(SAML2SSOAuthenticatorConstants.LOGGED_IN_USER, session.getAttribute("logged-user")); if (!Util.isLogoutSupportedIDP()) { request.setAttribute(SAML2SSOAuthenticatorConstants.EXTERNAL_LOGOUT_PAGE, Util.getExternalLogoutPage()); } } auditResult = SAML2SSOAuthenticatorConstants.AUDIT_RESULT_SUCCESS; if (username != null && !"".equals(username.trim()) && request != null && "true".equalsIgnoreCase(request.getParameter("logoutcomplete"))) { if (session.getAttribute("tenantDomain") != null) { // Build username for authorized user login // username in the session is in tenantAware manner username = username + UserCoreConstants.TENANT_DOMAIN_COMBINER + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); } else { // Keep same username for unauthorized user login } log.info(username + " successfully logged out"); } } catch (Exception ignored) { String msg = "Configuration context is null."; log.error(msg); throw new Exception(msg); } finally { if (username != null && username.trim().length() > 0 && AUDIT_LOG.isInfoEnabled() && request != null && "true".equalsIgnoreCase(request.getParameter("logoutcomplete"))) { // use the username built above (when printing info log) String auditInitiator = username; String auditData = ""; AUDIT_LOG.info(String.format(SAML2SSOAuthenticatorConstants.AUDIT_MESSAGE, auditInitiator, SAML2SSOAuthenticatorConstants.AUDIT_ACTION_LOGOUT, AUTHENTICATOR_NAME, auditData, auditResult)); } } }
From source file:org.everit.authentication.cas.CasAuthentication.java
/** * When an {@link HttpSession} is destroyed it must be removed from the * {@link CasHttpSessionRegistry}.// w w w .j av a2 s . co m */ @Override public void sessionDestroyed(final HttpSessionEvent httpSessionEvent) { HttpSession httpSession = httpSessionEvent.getSession(); ServletContext servletContext = httpSession.getServletContext(); CasHttpSessionRegistry casHttpSessionRegistry = CasHttpSessionRegistry.getInstance(servicePid, servletContext); casHttpSessionRegistry.removeBySession(httpSession); }
From source file:org.wso2.carbon.identity.authenticator.saml2.sso.ui.SSOAssertionConsumerService.java
private void handleExternalLogout(HttpServletRequest req, HttpServletResponse resp, String externalLogoutPage) throws IOException { HttpSession currentSession = req.getSession(false); if (currentSession != null) { // check if current session has expired currentSession.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER); currentSession.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER); try {//from w ww. j a v a2 s . co m currentSession.invalidate(); if (log.isDebugEnabled()) { log.debug("Frontend session invalidated"); } } catch (Exception ignored) { // Ignore exception when invalidating and invalidated session } } clearCookies(req, resp); if (log.isDebugEnabled()) { log.debug("Sending to " + externalLogoutPage); } resp.sendRedirect(externalLogoutPage); }
From source file:org.hdiv.web.servlet.tags.UrlTagTests.java
protected void initDataComposer() { String[] files = { "/org/hdiv/config/hdiv-core-applicationContext.xml", "/hdiv-config.xml", "/hdiv-validations.xml", }; if (this.hdivContext == null) { this.hdivContext = new ClassPathXmlApplicationContext(files); }/*from www. j a v a2 s .c o m*/ //API mock de Servlet // HttpServletRequest request = (MockHttpServletRequest) this.hdivContext.getBean("mockRequest"); MockHttpServletRequest request = (MockHttpServletRequest) context.getRequest(); HttpSession httpSession = request.getSession(); ServletContext servletContext = httpSession.getServletContext(); HDIVUtil.setHttpServletRequest(request); //inicializar StateCache en session this.initStateCache(httpSession); //inicializar HDIVConfig en ServletContext HDIVConfig hdivConfig = (HDIVConfig) this.hdivContext.getBean("config"); HDIVUtil.setHDIVConfig(hdivConfig, servletContext); //inicializar IApplication en ServletContext IApplication application = (IApplication) this.hdivContext.getBean("application"); HDIVUtil.setApplication(application, servletContext); //inicializar MessageSource en ServletContext MessageSource messageSource = (MessageSource) this.hdivContext; HDIVUtil.setMessageSource(messageSource, servletContext); //inicializar el datacomposer DataComposerFactory dataComposerFactory = (DataComposerFactory) this.hdivContext .getBean("dataComposerFactory"); IDataComposer dataComposer = dataComposerFactory.newInstance(); dataComposer.beginRequest("/testFormTag.do"); HDIVUtil.setDataComposer(dataComposer, request); }
From source file:us.mn.state.health.lims.reports.action.AuditTrailReportBySampleProcessAction.java
protected List populateHistoryList(HttpServletRequest request, List historyRecords, String rootNodeName, String xslMappingFileName) throws LIMSRuntimeException { List list = new ArrayList(); try {//from w ww .j av a 2s .c o m SystemUserDAO systemUserDAO = new SystemUserDAOImpl(); AuditTrailDAO auditTrailDAO = new AuditTrailDAOImpl(); for (int i = 0; i < historyRecords.size(); i++) { History historyRecord = (History) historyRecords.get(i); Timestamp date = historyRecord.getTimestamp(); String stringLocale = SystemConfiguration.getInstance().getDefaultLocale().toString(); String dateForDisplay = DateUtil.convertTimestampToStringDateAndTime(date, stringLocale); SystemUser systemUser = new SystemUser(); systemUser.setId(historyRecord.getSysUserId()); systemUserDAO.getData(systemUser); String blob = null; if (!historyRecord.getActivity().equals(AUDIT_TRAIL_INSERT)) { blob = auditTrailDAO.retrieveBlobData(historyRecord.getId()); } //this is temporary until 2593 has been completed if (historyRecord.getActivity().equals(IActionConstants.AUDIT_TRAIL_UPDATE)) { blob = "<" + rootNodeName + ">" + blob + "</" + rootNodeName + ">"; } if (!StringUtil.isNullorNill(blob)) { HistoryXmlHelper historyXmlHelper = new HistoryXmlHelper(); historyXmlHelper.setActivity(historyRecord.getActivity()); historyXmlHelper.setUserName(systemUser.getNameForDisplay()); String media = null, title = null, charset = null, xsldata = ""; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // NOTE!!!! // in order to run this in oc4j I needed to do the following: // add this to OC4J startup: -Djavax.xml.transform.TransformerFactory=org.apache.xalan.processor.TransformerFactoryImpl //to make sure that oc4j uses correct XSL processor (else it could not handle "function extensions" used to bring in MessageResources labels //place xalan.jar, xml-apis.jar, XercesImpl.jar into the applib folder of the oc4j installation TransformerFactory tFactory = TransformerFactory.newInstance(); HttpSession session = request.getSession(); ServletContext context = session.getServletContext(); File xslFile = new File( context.getRealPath("/WEB-INF/transformation/" + xslMappingFileName)); Source stylesheet = new StreamSource(xslFile); Transformer transformer = tFactory.newTransformer(stylesheet); System.out.println("This is blob " + blob); transformer.transform(new StreamSource(new StringReader(blob)), new StreamResult(outputStream)); } catch (TransformerConfigurationException tce) { tce.printStackTrace(); } catch (TransformerException te) { te.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } System.out.println("This is xml " + outputStream.toString()); historyXmlHelper.setChange(outputStream.toString()); historyXmlHelper.setDate(dateForDisplay); if (!StringUtil.isNullorNill(historyXmlHelper.getChange())) { historyXmlHelper.setChange(historyXmlHelper.getChange().trim()); } if (!StringUtil.isNullorNill(historyXmlHelper.getChange())) { list.add(historyXmlHelper); } } } } catch (Exception e) { throw new LIMSRuntimeException(e); } return list; }
From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.DefaultObjectPropertyFormGenerator.java
private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) { //Here, retrieve model from OntModel model = ModelAccess.on(session.getServletContext()).getOntModel(); //if object property if (EditConfigurationUtils.isObjectProperty(EditConfigurationUtils.getPredicateUri(vreq), vreq)) { Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq); if (objectIndividual != null) { //update existing object editConfiguration.prepareForObjPropUpdate(model); } else {/*from w ww . ja va 2s .c o m*/ //new object to be created editConfiguration.prepareForNonUpdate(model); } } else { throw new Error("DefaultObjectPropertyForm does not handle data properties."); } }
From source file:org.wso2.carbon.ui.AbstractCarbonUIAuthenticator.java
/** * /*from www.j a v a 2 s . c o m*/ * @param cookie * @param backendServerURL * @param session * @throws RemoteException */ protected void setUserInformation(String cookie, String backendServerURL, HttpSession session) throws RemoteException { try { if (session.getAttribute(ServerConstants.USER_PERMISSIONS) != null) { return; } ServletContext servletContext = session.getServletContext(); ConfigurationContext configContext = (ConfigurationContext) servletContext .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); LoggedUserInfoAdminStub stub = new LoggedUserInfoAdminStub(configContext, backendServerURL + "LoggedUserInfoAdmin"); ServiceClient client = stub._getServiceClient(); Options options = client.getOptions(); options.setManageSession(true); options.setProperty(HTTPConstants.COOKIE_STRING, cookie); org.wso2.carbon.core.commons.stub.loggeduserinfo.LoggedUserInfo userInfo = stub.getUserInfo(); String[] permissionArray = userInfo.getUIPermissionOfUser(); ArrayList<String> list = new ArrayList<String>(); for (String permission : permissionArray) { list.add(permission); } session.setAttribute(ServerConstants.USER_PERMISSIONS, list); if (userInfo.getPasswordExpiration() != null) { session.setAttribute(ServerConstants.PASSWORD_EXPIRATION, userInfo.getPasswordExpiration()); } } catch (AxisFault e) { throw e; } catch (RemoteException e) { throw e; } catch (Exception e) { throw new AxisFault("Exception occured", e); } }
From source file:edu.stanford.muse.webapp.JSPHelper.java
/** * gets the root dir for the logged in user -- this is the dir. * corresponding to /<userkey>/*from w ww .j a va 2s . c o m*/ * inside the actual webapp dir. * currently used only for attachments and save messages. the eventual goal * is to get * rid of this method because it is not secure in a multi-user environment. */ public static String getRootDir(HttpServletRequest request) { HttpSession session = request.getSession(); String userKey = (String) getSessionAttribute(session, "userKey"); ServletContext application = session.getServletContext(); String documentRootPath = application.getRealPath("/").toString(); return documentRootPath + File.separatorChar + userKey; }
From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java
/** * TODO tryggvil describe method getIWApplicationContext * * @param session// www . j a va 2s . c om * @return */ private static IWMainApplication getIWMainApplication(HttpSession session) { IWMainApplication iwma = IWMainApplication.getIWMainApplication(session.getServletContext()); return iwma; }