List of usage examples for javax.servlet.http HttpSession getServletContext
public ServletContext getServletContext();
From source file:com.jaspersoft.jasperserver.api.metadata.olap.service.impl.OlapConnectionServiceImpl.java
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public OlapModel initializeOlapModel(ExecutionContext executionContext, OlapUnit olapUnit, HttpSession sess) { RequestContext context = RequestContext.instance(); OlapModel model = createOlapModel(executionContext, olapUnit); if (model == null) { throw new JSException("jsexception.no.olap.model.created.for", new Object[] { olapUnit.getURIString() }); }/*from w w w . ja v a 2 s . com*/ model = (OlapModel) model.getTopDecorator(); model.setLocale(context.getLocale()); model.setServletContext(sess.getServletContext()); model.setID(olapUnit.getURIString()); /* ClickableExtension ext = (ClickableExtension) model.getExtension(ClickableExtension.ID); if (ext == null) { ext = new ClickableExtensionImpl(); model.addExtension(ext); } ext.setClickables(clickables); */ // stackMode OlapModelProxy omp = OlapModelProxy.instance(olapUnit.getURIString(), sess, false); /* if (queryName != null) omp.initializeAndShow(queryName, model); else */ try { initializeAndShow(omp, olapUnit.getURIString(), model, olapUnit); } catch (Exception e) { throw new JSException(e); } return omp; }
From source file:org.opencron.server.controller.HomeController.java
@RequestMapping("/login") public void login(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession, @RequestParam String username, @RequestParam String password) throws Exception { //??// w w w . ja va2s . c om int status = homeService.checkLogin(request, username, password); if (status == 500) { WebUtils.writeJson(response, "{\"msg\":\"???\"}"); return; } if (status == 200) { User user = OpencronTools.getUser(); //??? byte[] salt = Encodes.decodeHex(user.getSalt()); byte[] hashPassword = Digests.sha1(DigestUtils.md5Hex("opencron").toUpperCase().getBytes(), salt, 1024); String hashPass = Encodes.encodeHex(hashPassword); String format = "{\"status\":\"%s\",\"%s\":\"%s\"}"; if (user.getUserName().equals("opencron") && user.getPassword().equals(hashPass)) { WebUtils.writeJson(response, String.format(format, "edit", "userId", user.getUserId())); return; } if (user.getHeaderpic() != null) { String name = user.getUserId() + "_140" + user.getPicExtName(); String path = httpSession.getServletContext().getRealPath(File.separator) + "upload" + File.separator + name; IOUtils.writeFile(new File(path), user.getHeaderpic().getBinaryStream()); user.setHeaderPath(WebUtils.getWebUrlPath(request) + "/upload/" + name); } //init csrf... String csrf = OpencronTools.getCSRF(); WebUtils.writeJson(response, String.format(format, "success", "url", "/home?_csrf=" + csrf)); return; } }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ProtocolServiceTest.java
@Test public void testHandleReturnResponse() throws Exception { // setup//w w w . ja va 2 s. c om SAML2ProtocolServiceAuthIdent saml2ProtocolService = new SAML2ProtocolServiceAuthIdent(); String userId = UUID.randomUUID().toString(); String givenName = "test-given-name"; String surName = "test-sur-name"; Identity identity = new Identity(); identity.name = surName; identity.firstName = givenName; identity.gender = Gender.MALE; identity.dateOfBirth = new GregorianCalendar(); identity.nationality = "BELG"; identity.placeOfBirth = "Gent"; HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockHttpServletRequest = EasyMock.createMock(HttpServletRequest.class); HttpServletResponse mockHttpServletResponse = EasyMock.createMock(HttpServletResponse.class); ServletContext mockServletContext = EasyMock.createMock(ServletContext.class); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter); IdPIdentity idpIdentity = new IdPIdentity("test", new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { certificate })); IdentityProviderConfiguration mockConfiguration = EasyMock.createMock(IdentityProviderConfiguration.class); // expectations mockServletContext.setAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE, mockConfiguration); EasyMock.expect(mockHttpSession.getServletContext()).andReturn(mockServletContext); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.TARGET_URL_SESSION_ATTRIBUTE)) .andStubReturn("http://127.0.0.1"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.RELAY_STATE_SESSION_ATTRIBUTE)) .andStubReturn("relay-state"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.IN_RESPONSE_TO_SESSION_ATTRIBUTE)) .andStubReturn("a77a1c87-e590-47d7-a3e0-afea455ebc01"); EasyMock.expect(mockHttpSession.getAttribute(AbstractSAML2ProtocolService.ISSUER_SESSION_ATTRIBUTE)) .andStubReturn("Issuer"); EasyMock.expect(mockHttpServletRequest.getSession()).andReturn(mockHttpSession); EasyMock.expect(mockHttpSession.getServletContext()).andReturn(mockServletContext); EasyMock.expect(mockServletContext.getAttribute(AbstractSAML2ProtocolService.IDP_CONFIG_CONTEXT_ATTRIBUTE)) .andReturn(mockConfiguration); EasyMock.expect(mockConfiguration.getResponseTokenValidity()).andStubReturn(5); EasyMock.expect(mockConfiguration.findIdentity()).andStubReturn(idpIdentity); EasyMock.expect(mockConfiguration.getIdentityCertificateChain()) .andStubReturn(Collections.singletonList(certificate)); EasyMock.expect(mockConfiguration.getDefaultIssuer()).andStubReturn("TestIssuer"); // prepare EasyMock.replay(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); // operate saml2ProtocolService.init(mockServletContext, mockConfiguration); ReturnResponse returnResponse = saml2ProtocolService.handleReturnResponse(mockHttpSession, userId, new HashMap<String, Attribute>(), null, null, null, mockHttpServletRequest, mockHttpServletResponse); // verify EasyMock.verify(mockHttpServletRequest, mockHttpSession, mockServletContext, mockConfiguration); assertNotNull(returnResponse); assertEquals("http://127.0.0.1", returnResponse.getActionUrl()); List<NameValuePair> attributes = returnResponse.getAttributes(); assertNotNull(attributes); NameValuePair relayStateAttribute = null; NameValuePair samlResponseAttribute = null; for (NameValuePair attribute : attributes) { if ("RelayState".equals(attribute.getName())) { relayStateAttribute = attribute; continue; } if ("SAMLResponse".equals(attribute.getName())) { samlResponseAttribute = attribute; continue; } } assertNotNull(relayStateAttribute); assertEquals("relay-state", relayStateAttribute.getValue()); assertNotNull("no SAMLResponse attribute", samlResponseAttribute); String encodedSamlResponse = samlResponseAttribute.getValue(); assertNotNull(encodedSamlResponse); String samlResponse = new String(Base64.decodeBase64(encodedSamlResponse)); LOG.debug("SAML response: " + samlResponse); File tmpFile = File.createTempFile("saml-response-", ".xml"); FileUtils.writeStringToFile(tmpFile, samlResponse); LOG.debug("tmp file: " + tmpFile.getAbsolutePath()); }
From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java
/** * The key is the login name and the value is * com.idega.core.accesscontrol.business.LoggedOnInfo * * @return Returns empty Map if no one is logged on *///from w w w. jav a 2 s. c o m public Map<Object, Object> getLoggedOnInfoMap(HttpSession session) { ServletContext sc = session.getServletContext(); Map<Object, Object> loggedOnMap = (Map<Object, Object>) sc.getAttribute(_APPADDRESS_LOGGED_ON_LIST); if (loggedOnMap == null) { loggedOnMap = new TreeMap<Object, Object>(); sc.setAttribute(_APPADDRESS_LOGGED_ON_LIST, loggedOnMap); } return loggedOnMap; }
From source file:com.jing.common.controller.CommonController.java
@RequestMapping("push") @ResponseBody// w ww.j a v a2 s . c o m public GeneralResponse push(String title, String content, String mobile, String alert_addr, String longitude, String latitude, String licenseNumber, HttpServletRequest request, HttpSession session, Model model) { GeneralResponse message = new GeneralResponse(); ModelAndView mv = new ModelAndView(); logger.info("push push title:" + title + ",content:" + content + ",mobile:" + mobile + ",licenseNumber:" + licenseNumber); if (StringUtils.isEmpty(mobile)) { message.setCode(0); message.setMsg("?"); } else { try { String userId = userService.getUserIdByMobile(mobile); logger.info("push push userId " + userId); if (userId != null) { mv.addObject("title", title); mv.addObject("content", content); mv.addObject("userId", userId); PushPayload payload = Jiguang.buildPushObject_single_alert(content, title, userId);//Jiguang.buildPushObject_all_all_alert(); try { PushResult result = Jiguang.jPushClient.sendPush(payload); System.out.println("push location " + result.toString()); Point point = new Point(); if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) { point.setLatitude(Double.valueOf(latitude)); point.setLongitude(Double.valueOf(longitude)); point.setAlertAddr(alert_addr == null ? "" : alert_addr); } else if (!StringUtils.isEmpty(alert_addr)) { point.setAlertAddr(alert_addr); } session.getServletContext().setAttribute("location" + licenseNumber, point); System.out.println("push location session set success " + licenseNumber); logger.info("push push location session set success " + licenseNumber); message.setCode(1); message.setMsg("id??,??"); message.setRes(userId); } catch (APIConnectionException e) { e.printStackTrace(); } catch (APIRequestException e) { e.printStackTrace(); } } else { message.setCode(0); message.setMsg("?"); } } catch (Exception e) { message.setCode(0); message.setMsg(e.getMessage()); } } return message; }
From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.ManagePageGenerator.java
@Override public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq, HttpSession session) { EditConfigurationVTwo conf = new EditConfigurationVTwo(); conf.setTemplate(template);//from ww w . ja v a 2s. c o m //get editkey and url of form initBasics(conf, vreq); initPropertyParameters(vreq, session, conf); //if object uri exists, sets object URI initObjectPropForm(conf, vreq); //Depending on whether this is a new individual to be created or editing //an existing one, the var names will differ setVarNames(conf); //Set N3 required and optional setN3Required(conf); setN3Optional(conf); //Designate new resources if any exist setNewResources(conf); //Add sparql queries setSparqlQueries(conf); // In scope setUrisAndLiteralsInScope(conf, vreq); // on Form setUrisAndLiteralsOnForm(conf, vreq); //Set the fields setFields(conf); //Adding additional data, specifically edit mode addFormSpecificData(conf, vreq); //Add preprocessor conf.addEditSubmissionPreprocessor(new ManagePagePreprocessor(conf)); //Prepare: add literals/uris in scope based on sparql queries prepare(vreq, conf); //This method specifically retrieves information for edit populateExistingDataGetter(vreq, conf, session.getServletContext()); return conf; }
From source file:org.wso2.carbon.identity.sts.passive.ui.PassiveSTS.java
private void process(HttpServletRequest request, HttpServletResponse response, SessionDTO sessionDTO, AuthenticationResult authnResult) throws ServletException, IOException { HttpSession session = request.getSession(); session.removeAttribute(PassiveRequestorConstants.PASSIVE_REQ_ATTR_MAP); RequestToken reqToken = new RequestToken(); Map<ClaimMapping, String> attrMap = authnResult.getSubject().getUserAttributes(); StringBuilder buffer = null;/*from w w w. j a v a2 s . c om*/ if (MapUtils.isNotEmpty(attrMap)) { buffer = new StringBuilder(); for (Iterator<Entry<ClaimMapping, String>> iterator = attrMap.entrySet().iterator(); iterator .hasNext();) { Entry<ClaimMapping, String> entry = iterator.next(); buffer.append( "{" + entry.getKey().getRemoteClaim().getClaimUri() + "|" + entry.getValue() + "}#CODE#"); } } reqToken.setAction(sessionDTO.getAction()); if (buffer != null) { reqToken.setAttributes(buffer.toString()); } else { reqToken.setAttributes(sessionDTO.getAttributes()); } reqToken.setContext(sessionDTO.getContext()); reqToken.setReplyTo(sessionDTO.getReplyTo()); reqToken.setPseudo(sessionDTO.getPseudo()); reqToken.setRealm(sessionDTO.getRealm()); reqToken.setRequest(sessionDTO.getRequest()); reqToken.setRequestPointer(sessionDTO.getRequestPointer()); reqToken.setPolicy(sessionDTO.getPolicy()); reqToken.setPseudo(session.getId()); reqToken.setUserName(authnResult.getSubject().getAuthenticatedSubjectIdentifier()); String serverURL = CarbonUIUtil.getServerURL(session.getServletContext(), session); ConfigurationContext configContext = (ConfigurationContext) session.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); IdentityPassiveSTSClient passiveSTSClient = null; passiveSTSClient = new IdentityPassiveSTSClient(serverURL, configContext); ResponseToken respToken = passiveSTSClient.getResponse(reqToken); if (respToken != null && respToken.getResults() != null) { persistRealms(reqToken, request.getSession()); sendData(response, respToken, reqToken.getAction(), authnResult.getAuthenticatedIdPs()); } }
From source file:com.idega.core.accesscontrol.business.LoginBusinessBean.java
protected void storeLoggedOnInfoInSession(HttpSession session, LoginTable loginTable, String login, User user, LoginRecord loginRecord, String loginType) throws NotLoggedOnException, RemoteException { LoggedOnInfo lInfo = createLoggedOnInfo(); lInfo.setLoginTable(loginTable);/*w ww.j a v a 2s. c o m*/ lInfo.setLogin(login); // lInfo.setSession(iwc.getSession()); lInfo.setTimeOfLogon(IWTimestamp.RightNow()); lInfo.setUser(user); lInfo.setLoginRecord(loginRecord); if (loginType != null && !loginType.equals("")) { lInfo.setLoginType(loginType); } IWMainApplication iwma = getIWMainApplication(session); AccessController aController = iwma.getAccessController(); IWUserContext iwuc = new IWUserContextImpl(session, session.getServletContext()); lInfo.setUserRoles(aController.getAllRolesForCurrentUser(iwuc)); Map<Object, Object> m = getLoggedOnInfoMap(session); m.put(lInfo.getLogin(), lInfo); // getLoggedOnInfoList(iwc).add(lInfo); setLoggedOnInfo(lInfo, session); }
From source file:com.pararede.alfresco.security.AlfrescoContainerSecurityFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession httpSession = httpRequest.getSession(); String userName = httpRequest.getUserPrincipal().getName(); User userAuth = AuthenticationHelper.getUser(httpRequest, httpResponse); if ((userAuth == null) || !userName.equals(userAuth.getUserName())) { try {/*w w w . j a v a2s . c o m*/ TransactionService transactionService = this.registry.getTransactionService(); UserTransaction tx = transactionService.getUserTransaction(); try { tx.begin(); // remove the session invalidated flag (used to remove last username cookie by // AuthenticationFilter) httpSession.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); if (logger.isDebugEnabled()) { logger.debug("Authenticating user " + userName); } AuthenticationService authenticationService = getAuthenticationService(); authenticationService.authenticate(userName, null); PersonService personService = this.registry.getPersonService(); userAuth = new User(userName, authenticationService.getCurrentTicket(), personService.getPerson(userName)); NodeService nodeService = this.registry.getNodeService(); NodeRef homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName), ContentModel.PROP_HOMEFOLDER); if (!nodeService.exists(homeSpaceRef)) { throw new InvalidNodeRefException(homeSpaceRef); } userAuth.setHomeSpaceId(homeSpaceRef.getId()); httpSession.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, userAuth); httpSession.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, true); tx.commit(); } catch (Throwable e) { tx.rollback(); throw new ServletException(e); } } catch (SystemException e) { throw new ServletException(e); } } else { if (logger.isDebugEnabled()) { logger.debug("User " + userName + " already authenticated"); } AuthenticationStatus status = AuthenticationHelper.authenticate(httpSession.getServletContext(), httpRequest, httpResponse, false); if (status != AuthenticationStatus.Success) { throw new ServletException("User not correctly autheticated"); } } chain.doFilter(request, response); }
From source file:uk.ac.ebi.ep.controller.BrowseTaxonomyController.java
@RequestMapping(value = SEARCH_BY_TAX_ID, method = RequestMethod.GET) public String searchByTaxId(@ModelAttribute("searchModel") SearchModel searchModel, @RequestParam(value = "entryid", required = true) Long entryID, @RequestParam(value = "entryname", required = false) String entryName, Model model, HttpServletRequest request, HttpSession session, Pageable pageable, RedirectAttributes attributes) { pageable = new PageRequest(0, SEARCH_PAGESIZE, Sort.Direction.ASC, "function", "entryType"); Page<UniprotEntry> page = this.enzymePortalService.findEnzymesByTaxonomy(entryID, pageable); List<Species> species = enzymePortalService.findSpeciesByTaxId(entryID); List<Compound> compouds = enzymePortalService.findCompoundsByTaxId(entryID); List<Disease> diseases = enzymePortalService.findDiseasesByTaxId(entryID); List<EcNumber> enzymeFamilies = enzymePortalService.findEnzymeFamiliesByTaxId(entryID); SearchParams searchParams = searchModel.getSearchparams(); searchParams.setStart(0);//w w w . j av a 2s . com searchParams.setType(SearchParams.SearchType.KEYWORD); searchParams.setText(entryName); searchParams.setSize(SEARCH_PAGESIZE); searchModel.setSearchparams(searchParams); List<UniprotEntry> result = page.getContent(); int current = page.getNumber() + 1; int begin = Math.max(1, current - 5); int end = Math.min(begin + 10, page.getTotalPages()); model.addAttribute("page", page); model.addAttribute("beginIndex", begin); model.addAttribute("endIndex", end); model.addAttribute("currentIndex", current); model.addAttribute("organismName", entryName); model.addAttribute("taxId", entryID); // model.addAttribute("summaryEntries", result); SearchResults searchResults = new SearchResults(); searchResults.setTotalfound(page.getTotalElements()); SearchFilters filters = new SearchFilters(); filters.setSpecies(species); filters.setCompounds(compouds); filters.setEcNumbers(enzymeFamilies); filters.setDiseases(diseases); searchResults.setSearchfilters(filters); searchResults.setSummaryentries(result); searchModel.setSearchresults(searchResults); model.addAttribute("searchModel", searchModel); model.addAttribute("searchConfig", searchConfig); model.addAttribute("searchFilter", filters); String searchKey = getSearchKey(searchModel.getSearchparams()); cacheSearch(session.getServletContext(), searchKey, searchResults); setLastSummaries(session, searchResults.getSummaryentries()); clearHistory(session); addToHistory(session, searchModel.getSearchparams().getType(), searchKey); return RESULT; }