Java Code Examples for org.springframework.http.HttpHeaders

The following examples show how to use org.springframework.http.HttpHeaders. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			int contentLength = (int) headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 2
Source Project: spring-data-dev-tools   Source File: Jira.java    License: Apache License 2.0 6 votes vote down vote up
private JiraReleaseVersions getJiraReleaseVersions(ProjectKey projectKey, HttpHeaders headers, int startAt) {

		Map<String, Object> parameters = newUrlTemplateVariables();
		parameters.put("project", projectKey.getKey());
		parameters.put("fields", "summary,status,resolution,fixVersions");
		parameters.put("startAt", startAt);

		try {
			return operations.exchange(PROJECT_VERSIONS_TEMPLATE, HttpMethod.GET, new HttpEntity<>(headers),
					JiraReleaseVersions.class, parameters).getBody();
		} catch (HttpStatusCodeException e) {

			System.out.println(e.getResponseBodyAsString());
			throw e;
		}
	}
 
Example 3
Source Project: spring-analysis-note   Source File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void postForLocation() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);
	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	URI result = template.postForLocation("https://example.com", helloWorld);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example 4
Source Project: java-technology-stack   Source File: ContentRequestMatchers.java    License: MIT License 6 votes vote down vote up
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
Example 5
@Test
@WithMockUser
public void createPostWithMockUser() throws Exception {
    Post _data = Post.builder().title("my first post").content("my content of my post").build();
    given(this.postService.createPost(any(PostForm.class)))
        .willReturn(_data);
    
    MvcResult result = this.mockMvc
        .perform(
            post("/posts")
                .content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
                .contentType(MediaType.APPLICATION_JSON)
        )
        .andExpect(status().isCreated())
        .andExpect(header().string(HttpHeaders.LOCATION, containsString("/posts")))
        .andReturn();
    
    log.debug("mvc result::" + result.getResponse().getContentAsString());
    
    verify(this.postService, times(1)).createPost(any(PostForm.class));
}
 
Example 6
@Test
public void testExceedingCapacity() {
    ResponseEntity<String> response = this.restTemplate.getForEntity("/serviceB", String.class);
    HttpHeaders headers = response.getHeaders();
    String key = "rate-limit-application_serviceB_127.0.0.1";
    assertHeaders(headers, key, false, false);
    assertEquals(OK, response.getStatusCode());

    for (int i = 0; i < 2; i++) {
        response = this.restTemplate.getForEntity("/serviceB", String.class);
    }

    assertEquals(TOO_MANY_REQUESTS, response.getStatusCode());
    assertNotEquals(RedisApplication.ServiceController.RESPONSE_BODY, response.getBody());

    await().pollDelay(2, TimeUnit.SECONDS).untilAsserted(() -> {
        final ResponseEntity<String> responseAfterReset = this.restTemplate
            .getForEntity("/serviceB", String.class);
        final HttpHeaders headersAfterReset = responseAfterReset.getHeaders();
        assertHeaders(headersAfterReset, key, false, false);
        assertEquals(OK, responseAfterReset.getStatusCode());
    });
}
 
Example 7
Source Project: java-technology-stack   Source File: DefaultCorsProcessorTests.java    License: MIT License 6 votes vote down vote up
@Test
public void preflightRequestCredentials() throws Exception {
	this.request.setMethod(HttpMethod.OPTIONS.name());
	this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1");
	this.conf.addAllowedOrigin("http://domain1.com");
	this.conf.addAllowedOrigin("http://domain2.com");
	this.conf.addAllowedOrigin("http://domain3.com");
	this.conf.addAllowedHeader("Header1");
	this.conf.setAllowCredentials(true);

	this.processor.processRequest(this.conf, this.request, this.response);
	assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("http://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(this.response.containsHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(this.response.getHeaders(HttpHeaders.VARY), contains(HttpHeaders.ORIGIN,
			HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals(HttpServletResponse.SC_OK, this.response.getStatus());
}
 
Example 8
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void validActualRequest() {
	WebFilterChain filterChain = filterExchange -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		}
		catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("https://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "https://domain2.com")
					.header("header2", "foo"));
	this.filter.filter(exchange, filterChain).block();
}
 
Example 9
Source Project: cubeai   Source File: WebConfigurerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCorsFilterOnOtherPath() throws Exception {
    props.getCors().setAllowedOrigins(Collections.singletonList("*"));
    props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    props.getCors().setAllowedHeaders(Collections.singletonList("*"));
    props.getCors().setMaxAge(1800L);
    props.getCors().setAllowCredentials(true);

    MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
        .addFilters(webConfigurer.corsFilter())
        .build();

    mockMvc.perform(
        get("/test/test-cors")
            .header(HttpHeaders.ORIGIN, "other.domain.com"))
        .andExpect(status().isOk())
        .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example 10
Source Project: tutorials   Source File: PaginationUtilUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 11
Source Project: servicecomb-java-chassis   Source File: ApolloClient.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
void refreshConfig() {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Type", "application/json;charset=UTF-8");
  headers.add("Authorization", token);
  HttpEntity<String> entity = new HttpEntity<>(headers);
  ResponseEntity<String> exchange = rest.exchange(composeAPI(), HttpMethod.GET, entity, String.class);
  if (HttpResponseStatus.OK.code() == exchange.getStatusCode().value()) {
    try {
      Map<String, Object> body = JsonUtils.OBJ_MAPPER.readValue(exchange.getBody(),
          new TypeReference<Map<String, Object>>() {
          });
      refreshConfigItems((Map<String, Object>) body.get("configurations"));
    } catch (IOException e) {
      LOGGER.error("JsonObject parse config center response error: ", e);
    }
  } else {
    LOGGER.error("fetch configuration failed, error code:{} for {}",
        exchange.getStatusCodeValue(),
        exchange.getBody());
  }
}
 
Example 12
Source Project: JuniperBot   Source File: DogApiService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
public void init() {
    String apiKey = workerProperties.getDogApi().getKey();
    if (StringUtils.isEmpty(apiKey)) {
        return;
    }
    this.restTemplate = new RestTemplateBuilder()
            .rootUri(BASE_URI)
            .setConnectTimeout(HTTP_TIMEOUT_DURATION)
            .setReadTimeout(HTTP_TIMEOUT_DURATION)
            .uriTemplateHandler(new DefaultUriBuilderFactory(BASE_URI))
            .additionalInterceptors((request, body, execution) -> {
                HttpHeaders headers = request.getHeaders();
                headers.add("x-api-key", apiKey);
                headers.add("User-Agent", "JuniperBot");
                return execution.execute(request, body);
            })
            .build();
}
 
Example 13
Source Project: java-technology-stack   Source File: MockHttpServletRequest.java    License: MIT License 6 votes vote down vote up
@Override
public String getServerName() {
	String host = getHeader(HttpHeaders.HOST);
	if (host != null) {
		host = host.trim();
		if (host.startsWith("[")) {
			host = host.substring(1, host.indexOf(']'));
		}
		else if (host.contains(":")) {
			host = host.substring(0, host.indexOf(':'));
		}
		return host;
	}

	// else
	return this.serverName;
}
 
Example 14
Source Project: servicecomb-java-chassis   Source File: JaxrsClient.java    License: Apache License 2.0 6 votes vote down vote up
private static void testExchange(RestTemplate template, String cseUrlPrefix) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Accept", MediaType.APPLICATION_JSON);
  Person person = new Person();
  person.setName("world");
  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  ResponseEntity<Person> resEntity = template.exchange(cseUrlPrefix + "/compute/sayhello",
      HttpMethod.POST,
      requestEntity,
      Person.class);
  TestMgr.check("hello world", resEntity.getBody());

  ResponseEntity<String> resEntity2 =
      template.exchange(cseUrlPrefix + "/compute/addstring?s=abc&s=def", HttpMethod.DELETE, null, String.class);
  TestMgr.check("abcdef", resEntity2.getBody());
}
 
Example 15
@Test
void testGsonSerialization() {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  headers.set("Authorization", "Basic ABCDE");

  HttpEntity<TestNegotiatorQuery> entity = new HttpEntity<>(testNegotiatorQuery, headers);
  server
      .expect(once(), requestTo("http://directory.url/request"))
      .andExpect(method(HttpMethod.POST))
      .andExpect(content().string("{\"URL\":\"url\",\"nToken\":\"ntoken\"}"))
      .andExpect(MockRestRequestMatchers.header("Authorization", "Basic ABCDE"))
      .andRespond(withCreatedEntity(URI.create("http://directory.url/request/DEF")));

  String redirectURL =
      restTemplate.postForLocation("http://directory.url/request", entity).toASCIIString();
  assertEquals("http://directory.url/request/DEF", redirectURL);

  // Verify all expectations met
  server.verify();
}
 
Example 16
Source Project: openapi-generator   Source File: ApiKeyAuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyToParamsInHeaderWithPrefix() {
    MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    HttpHeaders headerParams = new HttpHeaders();
    MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();

    ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
    auth.setApiKey("my-api-token");
    auth.setApiKeyPrefix("Token");
    auth.applyToParams(queryParams, headerParams, cookieParams);

    // no changes to query or cookie parameters
    assertEquals(0, queryParams.size());
    assertEquals(0, cookieParams.size());
    assertEquals(1, headerParams.size());
    assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN").get(0));
}
 
Example 17
@Test
public void addHeadersOnlyOnceTest() throws IOException {
    TaggingRequestInterceptor testedInterceptor = new TaggingRequestInterceptor(TEST_VERSION_VALUE, TEST_ORG_VALUE, TEST_SPACE_VALUE);
    testedInterceptor.intercept(requestStub, body, execution);
    testedInterceptor.intercept(requestStub, body, execution);
    testedInterceptor.intercept(requestStub, body, execution);
    HttpHeaders headers = requestStub.getHeaders();
    String expectedValue = testedInterceptor.getHeaderValue(TEST_VERSION_VALUE);
    long tagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_NAME)
                           .stream()
                           .filter(value -> value.equals(expectedValue))
                           .count();
    assertEquals("Main tag header occurrence is not 1", 1L, tagCount);
    long orgTagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_ORG_NAME)
                              .stream()
                              .filter(value -> value.equals(TEST_ORG_VALUE))
                              .count();
    assertEquals("Org tag header occurrence is not 1", 1L, orgTagCount);
    long spaceTagCount = headers.get(TaggingRequestInterceptor.TAG_HEADER_SPACE_NAME)
                                .stream()
                                .filter(value -> value.equals(TEST_SPACE_VALUE))
                                .count();
    assertEquals("Space tag header occurrence is not 1", 1L, spaceTagCount);
}
 
Example 18
Source Project: davos   Source File: PushbulletNotifyAction.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(PostDownloadExecution execution) {

    PushbulletRequest body = new PushbulletRequest();
    body.body = execution.fileName;
    body.title = "A new file has been downloaded";
    body.type = "note";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + apiKey);

    try {

        LOGGER.info("Sending notification to Pushbullet for {}", execution.fileName);
        LOGGER.debug("API Key: {}", apiKey);
        HttpEntity<PushbulletRequest> httpEntity = new HttpEntity<PushbulletRequest>(body, headers);
        LOGGER.debug("Sending message to Pushbullet: {}", httpEntity);
        restTemplate.exchange("https://api.pushbullet.com/v2/pushes", HttpMethod.POST, httpEntity, Object.class);

    } catch (RestClientException | HttpMessageConversionException e ) {
        
        LOGGER.debug("Full stacktrace", e);
        LOGGER.error("Unable to complete notification to Pushbullet. Given error: {}", e.getMessage());
    }
}
 
Example 19
Source Project: spring-analysis-note   Source File: CrossOriginTests.java    License: MIT License 6 votes vote down vote up
@Test
public void ambiguousProducesPreFlightRequest() throws Exception {
	this.handlerMapping.registerHandler(new MethodLevelController());
	this.request.setMethod("OPTIONS");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.setRequestURI("/ambiguous-produces");
	HandlerExecutionChain chain = this.handlerMapping.getHandler(request);
	CorsConfiguration config = getCorsConfiguration(chain, true);
	assertNotNull(config);
	assertArrayEquals(new String[] {"*"}, config.getAllowedMethods().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedOrigins().toArray());
	assertArrayEquals(new String[] {"*"}, config.getAllowedHeaders().toArray());
	assertTrue(config.getAllowCredentials());
	assertTrue(CollectionUtils.isEmpty(config.getExposedHeaders()));
	assertNull(config.getMaxAge());
}
 
Example 20
Source Project: frostmourne   Source File: MessageService.java    License: MIT License 6 votes vote down vote up
boolean sendHttpPost(String httpPostEndPoint, AlarmMessage alarmMessage) {
    try {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        Map<String, Object> data = new HashMap<>();
        data.put("recipients", alarmMessage.getRecipients());
        data.put("content", alarmMessage.getContent());
        data.put("title", alarmMessage.getTitle());
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(data, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(httpPostEndPoint, request, String.class);
        return responseEntity.getStatusCode() == HttpStatus.OK;
    } catch (Exception ex) {
        LOGGER.error("error when send http post, url: " + httpPostEndPoint, ex);
        return false;
    }
}
 
Example 21
@Test
public void postForLocationCallback() throws Exception  {
	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(new MediaType("text", "plain", Charset.forName("ISO-8859-15")));
	HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
	final URI expected = new URI(baseUrl + "/post/1");
	ListenableFuture<URI> locationFuture = template.postForLocation(baseUrl + "/{method}", entity, "post");
	locationFuture.addCallback(new ListenableFutureCallback<URI>() {
		@Override
		public void onSuccess(URI result) {
			assertEquals("Invalid location", expected, result);
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	while (!locationFuture.isDone()) {
	}
}
 
Example 22
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return headers;
		}
	};

	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
	mockRequest.setCharacterEncoding("iso-8859-1");
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example 23
/**
 * This implementation sets the default headers by calling {@link #addDefaultHeaders},
 * and then calls {@link #writeInternal}.
 */
public final void write(final T t, @Nullable final Type type, @Nullable MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

	final HttpHeaders headers = outputMessage.getHeaders();
	addDefaultHeaders(headers, t, contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> writeInternal(t, type, new HttpOutputMessage() {
			@Override
			public OutputStream getBody() {
				return outputStream;
			}
			@Override
			public HttpHeaders getHeaders() {
				return headers;
			}
		}));
	}
	else {
		writeInternal(t, type, outputMessage);
		outputMessage.getBody().flush();
	}
}
 
Example 24
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void greaterSemicolonTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test>;test";
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 2);
    String[] linksData = headerData.split(",");
    assertTrue(linksData.length == 2);
    assertTrue(linksData[0].split(">;").length == 2);
    assertTrue(linksData[1].split(">;").length == 2);
    String expectedData = "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(0L));
}
 
Example 25
@RequestMapping(value = "**")
public ResponseEntity<String> getMetadata(@Valid MetadataRequestParameterBean params, BindingResult result,
    HttpServletResponse res, HttpServletRequest req) throws Exception {

  if (result.hasErrors())
    throw new BindException(result);
  String path = TdsPathUtils.extractPath(req, "metadata");

  try (GridDataset gridDataset = TdsRequestedDataset.getGridDataset(req, res, path)) {
    if (gridDataset == null)
      return null;

    NetcdfFile ncfile = gridDataset.getNetcdfFile(); // LOOK maybe gridDataset.getFileTypeId ??
    String fileTypeS = ncfile.getFileTypeId();
    ucar.nc2.constants.DataFormatType fileFormat = ucar.nc2.constants.DataFormatType.getType(fileTypeS);
    if (fileFormat != null)
      fileTypeS = fileFormat.toString(); // canonicalize

    ThreddsMetadata.VariableGroup vars = new ThreddsMetadataExtractor().extractVariables(fileTypeS, gridDataset);

    boolean wantXML = (params.getAccept() != null) && params.getAccept().equalsIgnoreCase("XML");

    HttpHeaders responseHeaders = new HttpHeaders();
    String strResponse;
    if (wantXML) {
      strResponse = writeXML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.xml.getContentHeader());
      // responseHeaders.set(Constants.Content_Disposition, Constants.setContentDispositionValue(datasetPath,
      // ".xml"));
    } else {
      strResponse = writeHTML(vars);
      responseHeaders.set(ContentType.HEADER, ContentType.html.getContentHeader());
    }
    return new ResponseEntity<>(strResponse, responseHeaders, HttpStatus.OK);
  }

}
 
Example 26
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
	Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required");
	try {
		Object result = this.unmarshaller.unmarshal(source);
		if (!clazz.isInstance(result)) {
			throw new TypeMismatchException(result, clazz);
		}
		return result;
	}
	catch (UnmarshallingFailureException ex) {
		throw new HttpMessageNotReadableException("Could not read [" + clazz + "]", ex);
	}
}
 
Example 27
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * Logs user into the system
 * 
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid username/password supplied
 * @param username The user name for login
 * @param password The password for login in clear text
 * @return String
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public String loginUser(String username, String password) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'username' is set
    if (username == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser");
    }
    
    // verify the required parameter 'password' is set
    if (password == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser");
    }
    
    String path = UriComponentsBuilder.fromPath("/user/login").build().toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username));
    queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password));

    final String[] accepts = { 
        "application/xml", "application/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 28
Source Project: 21-points   Source File: UserResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * GET /users : get all users.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and with body all users
 */
@GetMapping("/users")
@Timed
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
    final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 29
Source Project: alcor   Source File: IpAddrControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void Test11_deactivateIpAddrStateBulkTest() throws Exception {
    IpAddrRequest ipAddrRequest1 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip2,
            UnitTestConfig.deactivated);
    IpAddrRequest ipAddrRequest2 = new IpAddrRequest(
            UnitTestConfig.ipVersion,
            UnitTestConfig.vpcId,
            UnitTestConfig.subnetId,
            UnitTestConfig.rangeId,
            UnitTestConfig.ip3,
            UnitTestConfig.deactivated);

    List<IpAddrRequest> ipAddrRequests = new ArrayList<>();
    ipAddrRequests.add(ipAddrRequest1);
    ipAddrRequests.add(ipAddrRequest2);

    IpAddrRequestBulk ipAddrRequestBulk = new IpAddrRequestBulk();
    ipAddrRequestBulk.setIpRequests(ipAddrRequests);

    ObjectMapper objectMapper = new ObjectMapper();
    String ipAddrRequestBulkJson = objectMapper.writeValueAsString(ipAddrRequestBulk);

    this.mockMvc.perform(put(UnitTestConfig.ipAddrBulkUrl)
            .content(ipAddrRequestBulkJson)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());
}
 
Example 30
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
    return ExchangeFilterFunction.ofRequestProcessor(
        clientRequest -> {
            ClientRequest authorizedRequest = ClientRequest.from(clientRequest)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue())
                .build();
            return Mono.just(authorizedRequest);
        });
}