Search in sources :

Example 21 with ServletRequestAttributes

use of org.springframework.web.context.request.ServletRequestAttributes in project spring-framework by spring-projects.

the class ServletUriComponentsBuilderTests method fromCurrentRequest.

@Test
public void fromCurrentRequest() {
    this.request.setRequestURI("/mvc-showcase/data/param");
    this.request.setQueryString("foo=123");
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request));
    try {
        String result = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
        assertEquals("http://localhost/mvc-showcase/data/param?foo=123", result);
    } finally {
        RequestContextHolder.resetRequestAttributes();
    }
}
Also used : ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) Test(org.junit.Test)

Example 22 with ServletRequestAttributes

use of org.springframework.web.context.request.ServletRequestAttributes in project spring-boot by spring-projects.

the class WebRequestTraceFilter method getTrace.

protected Map<String, Object> getTrace(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    Principal userPrincipal = request.getUserPrincipal();
    Map<String, Object> trace = new LinkedHashMap<>();
    Map<String, Object> headers = new LinkedHashMap<>();
    trace.put("method", request.getMethod());
    trace.put("path", request.getRequestURI());
    trace.put("headers", headers);
    if (isIncluded(Include.REQUEST_HEADERS)) {
        headers.put("request", getRequestHeaders(request));
    }
    add(trace, Include.PATH_INFO, "pathInfo", request.getPathInfo());
    add(trace, Include.PATH_TRANSLATED, "pathTranslated", request.getPathTranslated());
    add(trace, Include.CONTEXT_PATH, "contextPath", request.getContextPath());
    add(trace, Include.USER_PRINCIPAL, "userPrincipal", (userPrincipal == null ? null : userPrincipal.getName()));
    if (isIncluded(Include.PARAMETERS)) {
        trace.put("parameters", request.getParameterMap());
    }
    add(trace, Include.QUERY_STRING, "query", request.getQueryString());
    add(trace, Include.AUTH_TYPE, "authType", request.getAuthType());
    add(trace, Include.REMOTE_ADDRESS, "remoteAddress", request.getRemoteAddr());
    add(trace, Include.SESSION_ID, "sessionId", (session == null ? null : session.getId()));
    add(trace, Include.REMOTE_USER, "remoteUser", request.getRemoteUser());
    if (isIncluded(Include.ERRORS) && exception != null && this.errorAttributes != null) {
        trace.put("error", this.errorAttributes.getErrorAttributes(new ServletRequestAttributes(request), true));
    }
    return trace;
}
Also used : HttpSession(javax.servlet.http.HttpSession) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) Principal(java.security.Principal) LinkedHashMap(java.util.LinkedHashMap)

Example 23 with ServletRequestAttributes

use of org.springframework.web.context.request.ServletRequestAttributes in project spring-framework by spring-projects.

the class MockMvc method perform.

/**
	 * Perform a request and return a type that allows chaining further
	 * actions, such as asserting expectations, on the result.
	 *
	 * @param requestBuilder used to prepare the request to execute;
	 * see static factory methods in
	 * {@link org.springframework.test.web.servlet.request.MockMvcRequestBuilders}
	 *
	 * @return an instance of {@link ResultActions}; never {@code null}
	 *
	 * @see org.springframework.test.web.servlet.request.MockMvcRequestBuilders
	 * @see org.springframework.test.web.servlet.result.MockMvcResultMatchers
	 */
public ResultActions perform(RequestBuilder requestBuilder) throws Exception {
    if (this.defaultRequestBuilder != null) {
        if (requestBuilder instanceof Mergeable) {
            requestBuilder = (RequestBuilder) ((Mergeable) requestBuilder).merge(this.defaultRequestBuilder);
        }
    }
    MockHttpServletRequest request = requestBuilder.buildRequest(this.servletContext);
    MockHttpServletResponse response = new MockHttpServletResponse();
    if (requestBuilder instanceof SmartRequestBuilder) {
        request = ((SmartRequestBuilder) requestBuilder).postProcessRequest(request);
    }
    final MvcResult mvcResult = new DefaultMvcResult(request, response);
    request.setAttribute(MVC_RESULT_ATTRIBUTE, mvcResult);
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, response));
    MockFilterChain filterChain = new MockFilterChain(this.servlet, this.filters);
    filterChain.doFilter(request, response);
    if (DispatcherType.ASYNC.equals(request.getDispatcherType()) && request.getAsyncContext() != null & !request.isAsyncStarted()) {
        request.getAsyncContext().complete();
    }
    applyDefaultResultActions(mvcResult);
    RequestContextHolder.setRequestAttributes(previousAttributes);
    return new ResultActions() {

        @Override
        public ResultActions andExpect(ResultMatcher matcher) throws Exception {
            matcher.match(mvcResult);
            return this;
        }

        @Override
        public ResultActions andDo(ResultHandler handler) throws Exception {
            handler.handle(mvcResult);
            return this;
        }

        @Override
        public MvcResult andReturn() {
            return mvcResult;
        }
    };
}
Also used : Mergeable(org.springframework.beans.Mergeable) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes) MockFilterChain(org.springframework.mock.web.MockFilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 24 with ServletRequestAttributes

use of org.springframework.web.context.request.ServletRequestAttributes in project ORCID-Source by ORCID.

the class SourceNameCacheManagerTest method before.

@Before
public void before() {
    when(mock_clientDetailsDao.existsAndIsNotPublicClient(OLD_FORMAT_CLIENT_ID)).thenReturn(true);
    when(mock_clientDetailsDao.existsAndIsNotPublicClient(AdditionalMatchers.not(Matchers.eq(OLD_FORMAT_CLIENT_ID)))).thenReturn(false);
    when(mock_recordNameDao.getRecordName(Matchers.eq(USER_PUBLIC_NAME))).thenAnswer(new Answer<RecordNameEntity>() {

        @Override
        public RecordNameEntity answer(InvocationOnMock invocation) throws Throwable {
            String id = (String) invocation.getArguments()[0];
            RecordNameEntity recordName = new RecordNameEntity();
            recordName.setLastModified(new Date());
            recordName.setCreditName("Credit name for " + id);
            recordName.setProfile(new ProfileEntity(id));
            recordName.setVisibility(Visibility.PUBLIC);
            return recordName;
        }
    });
    when(mock_recordNameDao.getRecordName(Matchers.eq(USER_LIMITED_NAME))).thenAnswer(new Answer<RecordNameEntity>() {

        @Override
        public RecordNameEntity answer(InvocationOnMock invocation) throws Throwable {
            String id = (String) invocation.getArguments()[0];
            RecordNameEntity recordName = new RecordNameEntity();
            recordName.setLastModified(new Date());
            recordName.setCreditName("Credit name for " + id);
            recordName.setProfile(new ProfileEntity(id));
            recordName.setVisibility(Visibility.LIMITED);
            return recordName;
        }
    });
    when(mock_recordNameDao.getRecordName(Matchers.eq(USER_PRIVATE_NAME))).thenAnswer(new Answer<RecordNameEntity>() {

        @Override
        public RecordNameEntity answer(InvocationOnMock invocation) throws Throwable {
            String id = (String) invocation.getArguments()[0];
            RecordNameEntity recordName = new RecordNameEntity();
            recordName.setLastModified(new Date());
            recordName.setCreditName("Credit name for " + id);
            recordName.setProfile(new ProfileEntity(id));
            recordName.setVisibility(Visibility.PRIVATE);
            return recordName;
        }
    });
    //Set up a client with the old id format and a user in the profile table, to be sure that the name is picked from the client details table
    when(mock_recordNameDao.getRecordName(Matchers.eq(OLD_FORMAT_CLIENT_ID))).thenAnswer(new Answer<RecordNameEntity>() {

        @Override
        public RecordNameEntity answer(InvocationOnMock invocation) throws Throwable {
            String id = (String) invocation.getArguments()[0];
            RecordNameEntity recordName = new RecordNameEntity();
            recordName.setLastModified(new Date());
            recordName.setCreditName("Am a USER!!!!");
            recordName.setProfile(new ProfileEntity(id));
            recordName.setVisibility(Visibility.PUBLIC);
            return recordName;
        }
    });
    when(mock_clientDetailsDao.find(Matchers.eq(OLD_FORMAT_CLIENT_ID))).thenAnswer(new Answer<ClientDetailsEntity>() {

        @Override
        public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
            String id = (String) invocation.getArguments()[0];
            ClientDetailsEntity clientDetails = new ClientDetailsEntity();
            clientDetails.setId(id);
            clientDetails.setClientName("Am a CLIENT!!!!");
            return clientDetails;
        }
    });
    assertNotNull(sourceNameCacheManager);
    TargetProxyHelper.injectIntoProxy(sourceNameCacheManager, "recordNameDao", mock_recordNameDao);
    TargetProxyHelper.injectIntoProxy(sourceNameCacheManager, "clientDetailsDao", mock_clientDetailsDao);
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RecordNameEntity(org.orcid.persistence.jpa.entities.RecordNameEntity) Date(java.util.Date) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Before(org.junit.Before)

Example 25 with ServletRequestAttributes

use of org.springframework.web.context.request.ServletRequestAttributes in project ORCID-Source by ORCID.

the class AuthenticationManagerTest method setUpMockRequest.

@Before
public void setUpMockRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) Before(org.junit.Before)

Aggregations

ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)30 RequestAttributes (org.springframework.web.context.request.RequestAttributes)13 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 Before (org.junit.Before)6 Test (org.junit.Test)3 MockHttpSession (org.springframework.mock.web.MockHttpSession)3 Date (java.util.Date)2 HttpSession (javax.servlet.http.HttpSession)2 BeforeClass (org.junit.BeforeClass)2 RecordNameEntity (org.orcid.persistence.jpa.entities.RecordNameEntity)2 ITestBean (org.springframework.tests.sample.beans.ITestBean)2 TestBean (org.springframework.tests.sample.beans.TestBean)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 PortletRequest (javax.portlet.PortletRequest)1 ServletException (javax.servlet.ServletException)1