Example usage for org.springframework.http HttpHeaders ACCEPT

List of usage examples for org.springframework.http HttpHeaders ACCEPT

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders ACCEPT.

Prototype

String ACCEPT

To view the source code for org.springframework.http HttpHeaders ACCEPT.

Click Source Link

Document

The HTTP Accept header field name.

Usage

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetEntityType_OK() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/types/Car")).andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(withSuccess(
                    Utils.loadResource("json/getEntityTypeResponse.json"), MediaType.APPLICATION_JSON));

    EntityType entityType = ngsiClient.getEntityType("Car").get();

    assertNotNull(entityType);/*from ww w. j a  v a2 s .  c o m*/
    assertNotNull(entityType.getAttrs());
    assertEquals(entityType.getAttrs().size(), 3);
    assertEquals(entityType.getAttrs().get("pressure").getType(), "none");
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetRegistrations_Defaults() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/registrations")).andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(withSuccess(
                    Utils.loadResource("json/getRegistrationsResponse.json"), MediaType.APPLICATION_JSON));

    List<Registration> registrations = ngsiClient.getRegistrations().get();
    assertEquals(1, registrations.size());
    assertEquals("abcdefg", registrations.get(0).getId());
    assertEquals("http://weather.example.com/ngsi", registrations.get(0).getCallback().toString());
    assertEquals("PT1M", registrations.get(0).getDuration());
    assertEquals(1, registrations.get(0).getSubject().getEntities().size());
    assertEquals("Bcn_Welt", registrations.get(0).getSubject().getEntities().get(0).getId().get());
    assertEquals(1, registrations.get(0).getSubject().getAttributes().size());
    assertEquals("temperature", registrations.get(0).getSubject().getAttributes().get(0));
    assertEquals(2, registrations.get(0).getMetadata().size());
    assertTrue(registrations.get(0).getMetadata().containsKey("providingService"));
    assertTrue(registrations.get(0).getMetadata().containsKey("providingAuthority"));
}

From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java

/**
 * Make sure directory forwarding happens when all conditions are met.
 *
 * @throws IOException      on error// w  w w  .  java  2s  .  co m
 * @throws ServletException on error
 * @throws GenieException   on error
 */
@Test
public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException {
    this.jobsProperties.getForwarding().setEnabled(true);
    final String jobId = UUID.randomUUID().toString();
    final String forwardedFrom = null;
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response);

    final String jobHostName = UUID.randomUUID().toString();
    Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName);

    //Mock parts of the http request
    final String http = "http";
    Mockito.when(request.getScheme()).thenReturn(http);
    final int port = 8080;
    Mockito.when(request.getServerPort()).thenReturn(port);
    final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString();
    Mockito.when(request.getRequestURI()).thenReturn(requestURI);

    final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT);
    Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames));
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE);

    final String requestUrl = UUID.randomUUID().toString();
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl));

    //Mock parts of forward response
    final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class);
    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine);
    final int successCode = 200;
    Mockito.when(statusLine.getStatusCode()).thenReturn(successCode);
    final Header contentTypeHeader = Mockito.mock(Header.class);
    Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE);
    Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE);
    Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader });

    final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString()
            + UUID.randomUUID().toString();
    final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8));
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    Mockito.when(entity.getContent()).thenReturn(bis);
    Mockito.when(forwardResponse.getEntity()).thenReturn(entity);

    final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream();
    Mockito.when(response.getOutputStream()).thenReturn(bos);

    final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class);
    final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class);
    Mockito.when(clientHttpRequest.execute())
            .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK));
    Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders());
    Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest);
    final RestTemplate template = new RestTemplate(factory);
    final Registry registry = Mockito.mock(Registry.class);
    final Counter counter = Mockito.mock(Counter.class);
    Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter);

    final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class),
            this.jobSearchService, Mockito.mock(AttachmentService.class),
            Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class),
            Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class),
            Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class),
            Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template,
            this.genieResourceHttpRequestHandler, this.jobsProperties, registry);
    jobController.getJobOutput(jobId, forwardedFrom, request, response);

    Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text));
    Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT);
    Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId));
    Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt());
    Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response);
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetRegistration_OK() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/registrations/abcdef")).andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(withSuccess(
                    Utils.loadResource("json/getRegistrationResponse.json"), MediaType.APPLICATION_JSON));

    Registration registration = ngsiClient.getRegistration("abcdef").get();

    assertNotNull(registration);//from  ww  w. jav a 2 s.  c  o m
    assertEquals("abcdef", registration.getId());
    assertEquals("http://localhost:1234", registration.getCallback().toString());
    assertEquals("PT1M", registration.getDuration());
    assertNotNull(registration.getSubject().getEntities());
    assertEquals(1, registration.getSubject().getEntities().size());
    assertEquals("Room", registration.getSubject().getEntities().get(0).getType().get());
    assertEquals(1, registration.getSubject().getAttributes().size());
    assertEquals("humidity", registration.getSubject().getAttributes().get(0));
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetSubscriptions_Defaults() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/subscriptions")).andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(withSuccess(
                    Utils.loadResource("json/getSubscriptionsResponse.json"), MediaType.APPLICATION_JSON));

    Paginated<Subscription> subscriptions = ngsiClient.getSubscriptions(0, 0, false).get();
    assertEquals(1, subscriptions.getItems().size());
    assertNotNull(subscriptions.getItems().get(0));
    assertEquals("abcdefg", subscriptions.getItems().get(0).getId());
    assertEquals("active", subscriptions.getItems().get(0).getStatus().toString());
    assertEquals("Bcn_Welt", subscriptions.getItems().get(0).getSubject().getEntities().get(0).getId().get());
    assertTrue(subscriptions.getItems().get(0).getSubject().getCondition().getAttributes()
            .contains("temperature"));
    assertEquals("temperature>40",
            subscriptions.getItems().get(0).getSubject().getCondition().getExpression().get("q"));
    assertEquals("http://localhost:1234",
            subscriptions.getItems().get(0).getNotification().getCallback().toString());
    assertTrue(subscriptions.getItems().get(0).getNotification().getHeaders().isPresent());
    assertEquals(1, subscriptions.getItems().get(0).getNotification().getHeaders().get().size());
    assertTrue(subscriptions.getItems().get(0).getNotification().getHeaders().get().containsKey("X-MyHeader"));
    assertEquals("foo", subscriptions.getItems().get(0).getNotification().getHeaders().get().get("X-MyHeader"));
    assertTrue(subscriptions.getItems().get(0).getNotification().getQuery().isPresent());
    assertEquals(1, subscriptions.getItems().get(0).getNotification().getQuery().get().size());
    assertTrue(subscriptions.getItems().get(0).getNotification().getQuery().get().containsKey("authToken"));
    assertEquals("bar", subscriptions.getItems().get(0).getNotification().getQuery().get().get("authToken"));
    assertTrue(subscriptions.getItems().get(0).getNotification().getAttrsFormat().isPresent());
    assertEquals(Notification.Format.keyValues,
            subscriptions.getItems().get(0).getNotification().getAttrsFormat().get());
    assertEquals(2, subscriptions.getItems().get(0).getNotification().getAttributes().size());
    assertTrue(subscriptions.getItems().get(0).getNotification().getAttributes().contains("temperature"));
    assertTrue(subscriptions.getItems().get(0).getNotification().getAttributes().contains("humidity"));
    assertEquals(new Long(5), subscriptions.getItems().get(0).getNotification().getThrottling().get());
    assertEquals(12, subscriptions.getItems().get(0).getNotification().getTimesSent());

    assertEquals(0, subscriptions.getOffset());
    assertEquals(0, subscriptions.getLimit());
    assertEquals(0, subscriptions.getTotal());
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetSubscriptions_Paginated() throws Exception {

    HttpHeaders responseHeader = new HttpHeaders();
    responseHeader.add("X-Total-Count", "1");

    mockServer.expect(requestTo(baseURL + "/v2/subscriptions?offset=2&limit=10&options=count"))
            .andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE))
            .andRespond(withSuccess(Utils.loadResource("json/getSubscriptionsResponse.json"),
                    MediaType.APPLICATION_JSON).headers(responseHeader));

    Paginated<Subscription> subscriptions = ngsiClient.getSubscriptions(2, 10, true).get();

    assertEquals(2, subscriptions.getOffset());
    assertEquals(10, subscriptions.getLimit());
    assertEquals(1, subscriptions.getTotal());
}

From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java

@Test
public void testGetSubscription_OK() throws Exception {

    mockServer.expect(requestTo(baseURL + "/v2/subscriptions/abcdef")).andExpect(method(HttpMethod.GET))
            .andExpect(header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)).andRespond(withSuccess(
                    Utils.loadResource("json/getSubscriptionResponse.json"), MediaType.APPLICATION_JSON));

    Subscription subscription = ngsiClient.getSubscription("abcdef").get();
    assertEquals("abcdef", subscription.getId());
    assertEquals("active", subscription.getStatus().toString());
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTest.java

private void checkJobOutput(final int documentationId, final String id) throws Exception {
    // Check getting a directory as json
    final RestDocumentationFilter jsonResultFilter = RestAssuredRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/json/",
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the directory to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT)
                    .description(MediaType.APPLICATION_JSON_VALUE).optional()), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description(MediaType.APPLICATION_JSON_VALUE)), // Response Headers
            Snippets.OUTPUT_DIRECTORY_FIELDS);

    RestAssured.given(this.getRequestSpecification()).filter(jsonResultFilter)
            .accept(MediaType.APPLICATION_JSON_VALUE).when().port(this.port)
            .get(JOBS_API + "/{id}/output/{filePath}", id, "").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.equalToIgnoringCase(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .body("parent", Matchers.isEmptyOrNullString()).body("directories[0].name", Matchers.is("genie/"))
            .body("files[0].name", Matchers.is("config1")).body("files[1].name", Matchers.is("dep1"))
            .body("files[2].name", Matchers.is("jobsetupfile")).body("files[3].name", Matchers.is("run"))
            .body("files[4].name", Matchers.is("stderr")).body("files[5].name", Matchers.is("stdout"));

    // Check getting a directory as HTML
    final RestDocumentationFilter htmlResultFilter = RestAssuredRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/html/",
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the directory to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(
                    HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT).description(MediaType.TEXT_HTML)), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description(MediaType.TEXT_HTML)) // Response Headers
    );//from ww  w  . j  a va2  s. c  om

    RestAssured.given(this.getRequestSpecification()).filter(htmlResultFilter).accept(MediaType.TEXT_HTML_VALUE)
            .when().port(this.port).get(JOBS_API + "/{id}/output/{filePath}", id, "").then()
            .statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.containsString(MediaType.TEXT_HTML_VALUE));

    // Check getting a file
    final RestDocumentationFilter fileResultFilter = RestAssuredRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/file/",
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the file to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT)
                    .description(MediaType.ALL_VALUE).optional()), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description("The content type of the file being returned").optional()) // Response Headers
    );

    // check that the generated run file is correct
    final String runShFileName = SystemUtils.IS_OS_LINUX ? "linux-runsh.txt" : "non-linux-runsh.txt";

    final String runShFile = this.resourceLoader.getResource(BASE_DIR + runShFileName).getFile()
            .getAbsolutePath();
    final String runFileContents = new String(Files.readAllBytes(Paths.get(runShFile)), StandardCharsets.UTF_8);

    final String jobWorkingDir = this.jobDirResource.getFile().getCanonicalPath() + FILE_DELIMITER + id;
    final String expectedRunScriptContent = this.getExpectedRunContents(runFileContents, jobWorkingDir, id);

    RestAssured.given(this.getRequestSpecification()).filter(fileResultFilter).when().port(this.port)
            .get(JOBS_API + "/{id}/output/{filePath}", id, "run").then()
            .statusCode(Matchers.is(HttpStatus.OK.value())).body(Matchers.is(expectedRunScriptContent));
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTests.java

private void checkJobOutput(final int documentationId, final String id) throws Exception {
    // Check getting a directory as json
    final RestDocumentationResultHandler jsonResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/json/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the directory to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT)
                    .description(MediaType.APPLICATION_JSON_VALUE).optional()), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description(MediaType.APPLICATION_JSON_VALUE)), // Response Headers
            Snippets.OUTPUT_DIRECTORY_FIELDS);
    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, ""))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath("parent", Matchers.isEmptyOrNullString()))
            .andExpect(MockMvcResultMatchers.jsonPath("$.directories[0].name", Matchers.is("genie/")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[0].name", Matchers.is("dep1")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[1].name", Matchers.is("jobsetupfile")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[2].name", Matchers.is("run")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[3].name", Matchers.is("stderr")))
            .andExpect(MockMvcResultMatchers.jsonPath("$.files[4].name", Matchers.is("stdout")))
            .andDo(jsonResultHandler);// ww  w .j  av a 2s . c  om

    // Check getting a directory as HTML
    final RestDocumentationResultHandler htmlResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/html/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the directory to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(
                    HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT).description(MediaType.TEXT_HTML)), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description(MediaType.TEXT_HTML)) // Response Headers
    );
    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, "")
            .accept(MediaType.TEXT_HTML)).andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
            .andDo(htmlResultHandler);

    // Check getting a file

    // Check getting a directory as HTML
    final RestDocumentationResultHandler fileResultHandler = MockMvcRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJobOutput/file/",
            Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
            Preprocessors.preprocessResponse(Preprocessors.prettyPrint()),
            Snippets.ID_PATH_PARAM.and(RequestDocumentation.parameterWithName("filePath")
                    .description("The path to the file to get").optional()), // Path parameters
            HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.ACCEPT)
                    .description(MediaType.ALL_VALUE).optional()), // Request header
            HeaderDocumentation.responseHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                    .description("The content type of the file being returned").optional()) // Response Headers
    );

    // check that the generated run file is correct
    final String runShFileName = SystemUtils.IS_OS_LINUX ? "linux-runsh.txt" : "non-linux-runsh.txt";

    final String runShFile = this.resourceLoader.getResource(BASE_DIR + runShFileName).getFile()
            .getAbsolutePath();
    final String runFileContents = new String(Files.readAllBytes(Paths.get(runShFile)), "UTF-8");

    final String jobWorkingDir = this.jobDirResource.getFile().getCanonicalPath() + FILE_DELIMITER + id;
    final String expectedRunScriptContent = this.getExpectedRunContents(runFileContents, jobWorkingDir, id);

    this.mvc.perform(RestDocumentationRequestBuilders.get(JOBS_API + "/{id}/output/{filePath}", id, "run"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string(expectedRunScriptContent))
            .andDo(fileResultHandler);
}