List of usage examples for org.springframework.web.context.request RequestContextHolder setRequestAttributes
public static void setRequestAttributes(@Nullable RequestAttributes attributes)
From source file:org.cloudfoundry.identity.uaa.login.EmailResetPasswordServiceTests.java
@Test public void testForgotPasswordWhenConflictIsReturnedByTheUaa() throws Exception { mockUaaServer.expect(requestTo("http://uaa.example.com/uaa/password_resets")).andExpect(method(POST)) .andRespond(new ResponseCreator() { @Override/*from w w w . j a va 2 s. c om*/ public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { return new MockClientHttpResponse("{\"user_id\":\"user-id-001\"}".getBytes(), CONFLICT); } }); MockHttpServletRequest request = new MockHttpServletRequest(); request.setProtocol("http"); request.setContextPath("/login"); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); emailResetPasswordService.forgotPassword("user@example.com"); mockUaaServer.verify(); Mockito.verify(messageService).sendMessage(eq("user-id-001"), eq("user@example.com"), eq(MessageType.PASSWORD_RESET), eq("Pivotal account password reset request"), contains( "Your account credentials for localhost are managed by an external service. Please contact your administrator for password recovery requests.")); }
From source file:ar.com.zauber.commons.web.uri.assets.AssetsTest.java
/** create request */ private MockHttpServletRequest createRequest(final XmlWebApplicationContext ctx) { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/organizations/zauber/projects"); request.setContextPath("/foo"); // esto se requiere para que funcione el buscar el ctx dado un request request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx); final ServletRequestAttributes attributes = new ServletRequestAttributes(request); request.setAttribute(RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES", attributes); LocaleContextHolder.setLocale(request.getLocale()); RequestContextHolder.setRequestAttributes(attributes); return request; }
From source file:grails.util.GrailsWebUtil.java
private static GrailsWebRequest bindMockWebRequest(ServletContext servletContext, MockHttpServletRequest request, MockHttpServletResponse response) { GrailsWebRequest webRequest = new GrailsWebRequest(request, response, servletContext); request.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, webRequest); RequestContextHolder.setRequestAttributes(webRequest); return webRequest; }
From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*//w ww .j a v a 2 s . co m * Resolve the locale from the request */ final Locale locale = localeResolver.resolveLocale(request); if (logger.isDebugEnabled()) { logger.debug("Resolved locale [" + locale + "]"); } /* * Store the locale in the LocaleContextHolder, making it available to * Spring. */ LocaleContextHolder.setLocale(locale); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { /* * We need to override the request to return the locale resolved by * Spring. */ super.service(new HttpServletRequestWrapper(request) { @Override public Locale getLocale() { return locale; } }, response); } finally { if (!locale.equals(LocaleContextHolder.getLocale())) { /* * The locale in LocaleContextHolder was changed during the * request, so we have to update the resolver. */ if (logger.isDebugEnabled()) { logger.debug("Locale changed, updating locale resolver"); } localeResolver.setLocale(request, response, LocaleContextHolder.getLocale()); } LocaleContextHolder.resetLocaleContext(); RequestContextHolder.resetRequestAttributes(); } }
From source file:com.mtgi.analytics.BehaviorTrackingManagerTest.java
/** test use of default SpringSessionContext when none is specified in configuration */ @Test/*from w w w .j a va 2 s .c o m*/ public void testDefaultSessionContext() throws Exception { BehaviorTrackingManagerImpl impl = new BehaviorTrackingManagerImpl(); impl.setApplication(manager.getApplication()); impl.setExecutor(executor); impl.setPersister(persister); impl.setFlushThreshold(5); impl.afterPropertiesSet(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteUser("testUser"); ServletRequestAttributes atts = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(atts); BehaviorEvent event = impl.createEvent("foo", "testEvent"); assertNotNull("event created", event); assertEquals("testBT", event.getApplication()); assertEquals("foo", event.getType()); assertEquals("testEvent", event.getName()); assertEquals("testUser", event.getUserId()); assertEquals(request.getSession().getId(), event.getSessionId()); assertNull(event.getParent()); assertTrue(event.getData().isNull()); assertNull(event.getError()); assertNull(event.getStart()); assertNull(event.getDurationNs()); assertTrue(event.isRoot()); assertFalse(event.isStarted()); assertFalse(event.isEnded()); //start the event. impl.start(event); impl.stop(event); assertEquals("all events now pending flush", 1, impl.getEventsPendingFlush()); impl.flush(); assertEquals("event queue flushed", 0, impl.getEventsPendingFlush()); }
From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeCredentialsInitializationService.java
public void initialize(PortletRequest request) { Object credentials;/*from ww w . j av a 2 s .c o m*/ PortletPreferences prefs = request.getPreferences(); // 1. Exchange Impersonation if (usesExchangeImpersonation(request)) { String exchangeImpersonationUsername = prefs.getValue(PREFS_IMPERSONATION_USERNAME, ""); String exchangeImpersonationPassword = prefs.getValue(PREFS_IMPERSONATION_PASSWORD, ""); //do not fill in the domain field else authentication fails with a 503, service not available response credentials = new NTCredentials(exchangeImpersonationUsername, exchangeImpersonationPassword, "paramDoesNotSeemToMatter", ""); logger.debug("Creating Exchange Impersonation credentials for EWS call"); } else { // Get the password from the UserInfo map. @SuppressWarnings("unchecked") Map<String, String> userInfo = (Map<String, String>) request.getAttribute(PortletRequest.USER_INFO); String password = userInfo.get(passwordAttribute); if (password == null) { throw new CalendarException( "Required user attribute password is null. Insure user-attribute password" + " is enabled in portlet.xml and CAS ClearPass is configured properly"); } // 2. If the domain is specified, return NT credentials from the username, password, and domain. String ntDomain = getNtlmDomain(request); if (StringUtils.isNotBlank(ntDomain)) { String username = userInfo.get(usernameAttribute); credentials = createNTCredentials(ntDomain, username, password); logger.debug("Creating NT credentials for {}", username); } else { // 3. Otherwise construct credentials from the email address and password for Office365 integration. String emailAddress = userInfo.get(this.mailAttribute); if (emailAddress == null) { throw new CalendarException( "Required user attribute email address is null. Insure user-attribute mail" + " is enabled in portlet.xml and populated via LDAP or other approach"); } credentials = new UsernamePasswordCredentials(emailAddress, password); logger.debug("Creating simple username/password credentials for {}", emailAddress); } } // cache the credentials object to this thread RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes == null) { requestAttributes = new PortletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); } requestAttributes.setAttribute(ExchangeWsCredentialsProvider.EXCHANGE_CREDENTIALS_ATTRIBUTE, credentials, RequestAttributes.SCOPE_SESSION); }
From source file:com.sourceallies.beanoh.BeanohTestCase.java
private void loadContext() { if (context == null) { String contextLocation = defaultContextLocationBuilder.build(getClass()); context = new BeanohApplicationContext(contextLocation); try {//from w w w . ja v a 2s. c o m context.refresh(); } catch (BeanDefinitionParsingException e) { throw e; } catch (BeanDefinitionStoreException e) { throw new MissingConfigurationException("Unable to locate " + contextLocation + ".", e); } context.getBeanFactory().registerScope("session", new SessionScope()); context.getBeanFactory().registerScope("request", new RequestScope()); MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes attributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(attributes); } }
From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java
@Test public void testExec() throws Exception { final ListFormatters.FormatterDataResponse formatters = listService.exec(null, null, schema, false, false); for (ListFormatters.FormatterData formatter : formatters.getFormatters()) { MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession();/*from w w w . ja v a 2 s.c o m*/ request.setPathInfo("/eng/blahblah"); MockHttpServletResponse response = new MockHttpServletResponse(); final String srvAppContext = "srvAppContext"; request.getServletContext().setAttribute(srvAppContext, applicationContext); JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(srvAppContext); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); formatService.exec("eng", "html", "" + id, null, formatter.getId(), "true", false, _100, new ServletWebRequest(request, response)); final String view = response.getContentAsString(); try { assertFalse(formatter.getSchema() + "/" + formatter.getId(), view.isEmpty()); } catch (Throwable e) { e.printStackTrace(); fail(formatter.getSchema() + " > " + formatter.getId()); } try { response = new MockHttpServletResponse(); formatService.exec("eng", "testpdf", "" + id, null, formatter.getId(), "true", false, _100, new ServletWebRequest(request, response)); // Files.write(Paths.get("e:/tmp/view.pdf"), response.getContentAsByteArray()); // System.exit(0); } catch (Throwable t) { t.printStackTrace(); fail(formatter.getSchema() + " > " + formatter.getId()); } } }
From source file:ezbake.security.client.EzbakeSecurityClientTest.java
@Test public void requestPrincipalFromRequestGetsPrincipalFromContext() throws TException, PKeyCryptoException { String token = generateProxyToken(); String signature = signString(token); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addHeader(EzbakeSecurityClient.EFE_USER_HEADER, token); servletRequest.addHeader(EzbakeSecurityClient.EFE_SIGNATURE_HEADER, signature); RequestAttributes requestAttributes = new ServletRequestAttributes(servletRequest); RequestContextHolder.setRequestAttributes(requestAttributes); ProxyPrincipal proxyPrincipal = client.requestPrincipalFromRequest(); client.verifyProxyUserToken(proxyPrincipal.getProxyToken(), proxyPrincipal.getSignature()); }