List of usage examples for org.springframework.web.context.request ServletRequestAttributes ServletRequestAttributes
public ServletRequestAttributes(HttpServletRequest request)
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:org.bessle.neo4j.proxy.HttpRequestLoggingFilter.java
protected Map<String, Object> getTrace(HttpServletRequestWrapper wrappedRequest) { Map<String, Object> headers = new LinkedHashMap<String, Object>(); Enumeration<String> names = wrappedRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); List<String> values = Collections.list(wrappedRequest.getHeaders(name)); Object value = values;/* w ww . j a v a 2 s .c o m*/ if (values.size() == 1) { value = values.get(0); } else if (values.isEmpty()) { value = ""; } headers.put(name, value); } Map<String, Object> trace = new LinkedHashMap<String, Object>(); Map<String, Object> allHeaders = new LinkedHashMap<String, Object>(); allHeaders.put("request", headers); trace.put("method", wrappedRequest.getMethod()); trace.put("path", wrappedRequest.getRequestURI()); trace.put("headers", allHeaders); Throwable exception = (Throwable) wrappedRequest.getAttribute("javax.servlet.error.exception"); if (exception != null && this.errorAttributes != null) { RequestAttributes requestAttributes = new ServletRequestAttributes(wrappedRequest); Map<String, Object> error = this.errorAttributes.getErrorAttributes(requestAttributes, true); trace.put("error", error); } String body = "unknown"; try { //body = IOUtils.toString(wrappedRequest.getInputStream(), "UTF-8"); trace.put("body", body); InputStream wrappedInputStream = IOUtils.toInputStream(body, "UTF-8"); //wrappedRequest. } catch (IOException ioe) { trace.put("body", "untraceable"); } return trace; }
From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*//from w ww .ja v a 2 s . c om * 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 ww w. j a va 2s.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:com.sourceallies.beanoh.BeanohTestCase.java
private void loadContext() { if (context == null) { String contextLocation = defaultContextLocationBuilder.build(getClass()); context = new BeanohApplicationContext(contextLocation); try {/* w w w . j a v a 2 s. co 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();/*w ww . ja va 2 s .co 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()); }
From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java
@Test public void testExecXslt() throws Exception { final ServletContext context = _applicationContext.getBean(ServletContext.class); MockHttpServletRequest request = new MockHttpServletRequest(context, "GET", "http://localhost:8080/geonetwork/srv/eng/md.formatter"); request.getSession();//w ww .j ava 2 s . c o m request.setPathInfo("/eng/md.formatter"); final String applicationContextAttributeKey = "srv"; request.getServletContext().setAttribute(applicationContextAttributeKey, _applicationContext); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); final String formatterName = "xsl-test-formatter"; final URL testFormatterViewFile = FormatterApiIntegrationTest.class .getResource(formatterName + "/view.xsl"); final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent(); final Path formatterDir = this.dataDirectory.getFormatterDir(); Files.deleteIfExists(formatterDir.resolve("functions.xsl")); IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false); IO.copyDirectoryOrFile(testFormatter.getParent().resolve("functions.xsl"), formatterDir, true); JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(applicationContextAttributeKey); final MockHttpServletResponse response = new MockHttpServletResponse(); formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100, new ServletWebRequest(request, response)); final String viewXml = response.getContentAsString(); final Element view = Xml.loadString(viewXml, false); assertEqualsText("fromFunction", view, "*//p"); assertEqualsText("Title", view, "*//div[@class='tr']"); }
From source file:nl.surfnet.coin.teams.control.DetailTeamControllerTest.java
private RequestAttributes getRequestAttributes() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpSession session = new MockHttpSession(); Person person = new Person(); person.setId("test"); session.setAttribute(LoginInterceptor.PERSON_SESSION_KEY, person); request.setSession(session);// w ww . ja v a 2s .co m return new ServletRequestAttributes(request); }
From source file:org.cloudfoundry.identity.uaa.login.EmailChangeEmailServiceTest.java
@BeforeEach public void setUp() throws Exception { SecurityContextHolder.clearContext(); scimUserProvisioning = mock(ScimUserProvisioning.class); codeStore = mock(ExpiringCodeStore.class); clientDetailsService = mock(MultitenantClientServices.class); messageService = mock(EmailService.class); emailChangeEmailService = new EmailChangeEmailService(templateEngine, messageService, scimUserProvisioning, codeStore, clientDetailsService); request = new MockHttpServletRequest(); request.setProtocol("http"); request.setContextPath("/login"); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); }