Search in sources :

Example 11 with RequestAttributes

use of org.springframework.web.context.request.RequestAttributes in project topcom-cloud by 545314690.

the class MyWebAppConfigurer method extendMessageConverters.

/**
 * 添加返回结果缩进支持,如果存在pretty参数,则返回结果添加缩进
 * @param converters
 */
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.replaceAll(c -> {
        if (c instanceof MappingJackson2HttpMessageConverter) {
            MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper) {

                @Override
                protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
                    RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
                    if (attributes != null && attributes instanceof ServletRequestAttributes) {
                        String attribute = ((ServletRequestAttributes) attributes).getRequest().getParameter("pretty");
                        if (attribute != null) {
                            generator.setPrettyPrinter(new DefaultPrettyPrinter());
                        }
                    }
                    super.writePrefix(generator, object);
                }
            };
            return converter;
        } else {
            return c;
        }
    });
}
Also used : DefaultPrettyPrinter(com.fasterxml.jackson.core.util.DefaultPrettyPrinter) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes)

Example 12 with RequestAttributes

use of org.springframework.web.context.request.RequestAttributes in project cuba by cuba-platform.

the class WebUserSessionSource method getUserSessionFromMiddleware.

protected UserSession getUserSessionFromMiddleware(UUID sessionId) {
    UserSession userSession = null;
    HttpServletRequest request = null;
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        request = ((ServletRequestAttributes) requestAttributes).getRequest();
    }
    if (request != null) {
        userSession = (UserSession) request.getAttribute(REQUEST_ATTR);
    }
    if (userSession != null) {
        return userSession;
    }
    userSession = userSessionService.getUserSession(sessionId);
    if (request != null) {
        request.setAttribute(REQUEST_ATTR, userSession);
    }
    return userSession;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSession(com.haulmont.cuba.security.global.UserSession) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes)

Example 13 with RequestAttributes

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

the class MemberV2ApiServiceDelegator_WorksTest method testCreateBulkWorksWithBlankTitles.

@Test
public void testCreateBulkWorksWithBlankTitles() {
    RequestAttributes previousAttrs = RequestContextHolder.getRequestAttributes();
    RequestAttributes attrs = new ServletRequestAttributes(new MockHttpServletRequest());
    attrs.setAttribute(ApiVersionFilter.API_VERSION_REQUEST_ATTRIBUTE_NAME, "2.0", RequestAttributes.SCOPE_REQUEST);
    RequestContextHolder.setRequestAttributes(attrs);
    Long time = System.currentTimeMillis();
    SecurityContextTestUtils.setUpSecurityContext(ORCID, ScopePathType.READ_LIMITED, ScopePathType.ACTIVITIES_UPDATE);
    WorkBulk bulk = new WorkBulk();
    for (int i = 0; i < 5; i++) {
        Work work = new Work();
        WorkTitle title = new WorkTitle();
        title.setTitle(i == 0 ? new Title(" ") : new Title("title " + i));
        work.setWorkTitle(title);
        ExternalIDs extIds = new ExternalIDs();
        ExternalID extId = new ExternalID();
        extId.setRelationship(Relationship.SELF);
        extId.setType("doi");
        extId.setUrl(new Url("http://doi/" + i + "/" + time));
        extId.setValue("doi-" + i + "-" + time);
        extIds.getExternalIdentifier().add(extId);
        work.setWorkExternalIdentifiers(extIds);
        work.setWorkType(WorkType.BOOK);
        bulk.getBulk().add(work);
    }
    Response response = serviceDelegator.createWorks(ORCID, bulk);
    assertNotNull(response);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    bulk = (WorkBulk) response.getEntity();
    assertNotNull(bulk);
    assertEquals(5, bulk.getBulk().size());
    for (int i = 0; i < 5; i++) {
        if (i == 0) {
            assertTrue(bulk.getBulk().get(i) instanceof OrcidError);
        } else {
            assertTrue(bulk.getBulk().get(i) instanceof Work);
            serviceDelegator.deleteWork(ORCID, ((Work) bulk.getBulk().get(i)).getPutCode());
        }
    }
    RequestContextHolder.setRequestAttributes(previousAttrs);
}
Also used : OrcidError(org.orcid.jaxb.model.error_v2.OrcidError) ExternalIDs(org.orcid.jaxb.model.record_v2.ExternalIDs) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) WorkBulk(org.orcid.jaxb.model.record_v2.WorkBulk) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ExternalID(org.orcid.jaxb.model.record_v2.ExternalID) WorkTitle(org.orcid.jaxb.model.record_v2.WorkTitle) TranslatedTitle(org.orcid.jaxb.model.common_v2.TranslatedTitle) Title(org.orcid.jaxb.model.common_v2.Title) RequestAttributes(org.springframework.web.context.request.RequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) Url(org.orcid.jaxb.model.common_v2.Url) ResearcherUrl(org.orcid.jaxb.model.record_v2.ResearcherUrl) Response(javax.ws.rs.core.Response) WorkTitle(org.orcid.jaxb.model.record_v2.WorkTitle) Work(org.orcid.jaxb.model.record_v2.Work) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 14 with RequestAttributes

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

the class TokenTargetFilterTest method tokenUsedOnTheWrongUser12ApiTest.

@Test(expected = AccessControlException.class)
public void tokenUsedOnTheWrongUser12ApiTest() {
    setUpSecurityContext(ORCID1, CLIENT_ID, ScopePathType.READ_LIMITED);
    ContainerRequest request = Mockito.mock(ContainerRequest.class);
    Mockito.when(request.getPath()).thenReturn("http://api.test.orcid.org/v1.2/" + ORCID2);
    RequestAttributes sra = Mockito.mock(RequestAttributes.class);
    Mockito.when(sra.getAttribute(ApiVersionFilter.API_VERSION_REQUEST_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST)).thenReturn("1.2");
    RequestContextHolder.setRequestAttributes(sra);
    TokenTargetFilter filter = new TokenTargetFilter();
    filter.filter(request);
    fail();
}
Also used : ContainerRequest(com.sun.jersey.spi.container.ContainerRequest) RequestAttributes(org.springframework.web.context.request.RequestAttributes) Test(org.junit.Test)

Example 15 with RequestAttributes

use of org.springframework.web.context.request.RequestAttributes in project spring-integration by spring-projects.

the class HttpProxyScenarioTests method testHttpProxyScenario.

@Test
public void testHttpProxyScenario() throws Exception {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.RFC_1123_DATE_TIME;
    ZoneId GMT = ZoneId.of("GMT");
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MILLISECOND, 0);
    final long ifModifiedSince = c.getTimeInMillis();
    Instant instant = Instant.ofEpochMilli(ifModifiedSince);
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, GMT);
    String ifModifiedSinceValue = dateTimeFormatter.format(zonedDateTime);
    c.add(Calendar.DATE, -1);
    long ifUnmodifiedSince = c.getTimeInMillis();
    instant = Instant.ofEpochMilli(ifUnmodifiedSince);
    zonedDateTime = ZonedDateTime.ofInstant(instant, GMT);
    final String ifUnmodifiedSinceValue = dateTimeFormatter.format(zonedDateTime);
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
    request.setQueryString("foo=bar&FOO=BAR");
    request.addHeader("If-Modified-Since", ifModifiedSinceValue);
    request.addHeader("If-Unmodified-Since", ifUnmodifiedSinceValue);
    request.addHeader("Connection", "Keep-Alive");
    request.setContentType("text/plain");
    Object handler = this.handlerMapping.getHandler(request).getHandler();
    assertNotNull(handler);
    MockHttpServletResponse response = new MockHttpServletResponse();
    RestTemplate template = Mockito.spy(new RestTemplate());
    final String contentDispositionValue = "attachment; filename=\"test.txt\"";
    Mockito.doAnswer(invocation -> {
        URI uri = invocation.getArgument(0);
        assertEquals(new URI("http://testServer/test?foo=bar&FOO=BAR"), uri);
        HttpEntity<?> httpEntity = (HttpEntity<?>) invocation.getArguments()[2];
        HttpHeaders httpHeaders = httpEntity.getHeaders();
        assertEquals(ifModifiedSince, httpHeaders.getIfModifiedSince());
        assertEquals(ifUnmodifiedSinceValue, httpHeaders.getFirst("If-Unmodified-Since"));
        assertEquals("Keep-Alive", httpHeaders.getFirst("Connection"));
        MultiValueMap<String, String> responseHeaders = new LinkedMultiValueMap<String, String>(httpHeaders);
        responseHeaders.set("Connection", "close");
        responseHeaders.set("Content-Disposition", contentDispositionValue);
        return new ResponseEntity<>(responseHeaders, HttpStatus.OK);
    }).when(template).exchange(Mockito.any(URI.class), Mockito.any(HttpMethod.class), Mockito.any(HttpEntity.class), (Class<?>) isNull());
    PropertyAccessor dfa = new DirectFieldAccessor(this.handler);
    dfa.setPropertyValue("restTemplate", template);
    RequestAttributes attributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(attributes);
    this.handlerAdapter.handle(request, response, handler);
    assertEquals(ifModifiedSinceValue, response.getHeaderValue("If-Modified-Since"));
    assertEquals(ifUnmodifiedSinceValue, response.getHeaderValue("If-Unmodified-Since"));
    assertEquals("close", response.getHeaderValue("Connection"));
    assertEquals(contentDispositionValue, response.getHeader("Content-Disposition"));
    assertEquals("text/plain", response.getContentType());
    Message<?> message = this.checkHeadersChannel.receive(2000);
    MessageHeaders headers = message.getHeaders();
    assertEquals(ifModifiedSince, headers.get("If-Modified-Since"));
    assertEquals(ifUnmodifiedSince, headers.get("If-Unmodified-Since"));
    RequestContextHolder.resetRequestAttributes();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) URI(java.net.URI) ZonedDateTime(java.time.ZonedDateTime) MessageHeaders(org.springframework.messaging.MessageHeaders) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) PropertyAccessor(org.springframework.beans.PropertyAccessor) ZoneId(java.time.ZoneId) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Calendar(java.util.Calendar) Instant(java.time.Instant) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) RequestAttributes(org.springframework.web.context.request.RequestAttributes) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ResponseEntity(org.springframework.http.ResponseEntity) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) RestTemplate(org.springframework.web.client.RestTemplate) DateTimeFormatter(java.time.format.DateTimeFormatter) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Aggregations

RequestAttributes (org.springframework.web.context.request.RequestAttributes)76 ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)46 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)15 Test (org.junit.Test)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)3 DefaultPrettyPrinter (com.fasterxml.jackson.core.util.DefaultPrettyPrinter)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Response (javax.ws.rs.core.Response)3 XWorkRequestAttributes (org.onebusaway.presentation.impl.users.XWorkRequestAttributes)3 DBUnitTest (org.orcid.test.DBUnitTest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 ProjectService (ca.corefacility.bioinformatics.irida.service.ProjectService)2 UserService (ca.corefacility.bioinformatics.irida.service.user.UserService)2 UserSession (com.haulmont.cuba.security.global.UserSession)2 ActionContext (com.opensymphony.xwork2.ActionContext)2 RecordDefinition (com.revolsys.record.schema.RecordDefinition)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2