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 check out the related API usage on the sidebar.
Example #1
Source Project: cubeai   Author: cube-ai   File: WebConfigurerTest.java    License: Apache License 2.0 8 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 #2
Source Project: servicecomb-java-chassis   Author: apache   File: JaxrsClient.java    License: Apache License 2.0 7 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 #3
Source Project: spring4-understanding   Author: langtianya   File: SimpleStreamingClientHttpRequest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #4
Source Project: spring-data-dev-tools   Author: spring-projects   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 #5
Source Project: spring-analysis-note   Author: Vip-Augus   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 #6
Source Project: java-technology-stack   Author: codeEngraver   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 #7
@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 #8
Source Project: spring-cloud-zuul-ratelimit   Author: marcosbarbero   File: RedisApplicationTestIT.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: java-technology-stack   Author: codeEngraver   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 #10
Source Project: spring-analysis-note   Author: Vip-Augus   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 #11
Source Project: molgenis   Author: molgenis   File: HttpClientConfigTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #12
Source Project: openapi-generator   Author: OpenAPITools   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 #13
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: TaggingRequestInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
Source Project: davos   Author: linuxserver   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 #15
Source Project: spring-analysis-note   Author: Vip-Augus   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 #16
Source Project: frostmourne   Author: AutohomeCorp   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 #17
Source Project: spring4-understanding   Author: langtianya   File: AsyncRestTemplateIntegrationTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 #18
Source Project: java-technology-stack   Author: codeEngraver   File: RequestPartServletServerHttpRequestTests.java    License: MIT License 6 votes vote down vote up
@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 #19
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractGenericHttpMessageConverter.java    License: MIT License 6 votes vote down vote up
/**
 * 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 #20
Source Project: cubeai   Author: cube-ai   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 #21
Source Project: tds   Author: Unidata   File: MetadataController.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #22
Source Project: lams   Author: lamsfoundation   File: MarshallingHttpMessageConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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 #23
Source Project: tutorials   Author: eugenp   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 #24
Source Project: 21-points   Author: mraible   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 #25
Source Project: alcor   Author: futurewei-cloud   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 #26
Source Project: keycloak-springsecurity5-sample   Author: hantsy   File: MainController.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
        });
}
 
Example #27
Source Project: spring-in-action-5-samples   Author: habuma   File: IngredientController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping
public ResponseEntity<Ingredient> postIngredient(@RequestBody Ingredient ingredient) {
  Ingredient saved = repo.save(ingredient);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(URI.create("http://localhost:8080/ingredients/" + ingredient.getId()));
  return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
}
 
Example #28
Source Project: pig   Author: magicgis   File: XssHttpServletRequestWrapper.java    License: MIT License 5 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
    //非json类型,直接返回
    if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
        return super.getInputStream();
    }

    //为空,直接返回
    String json = IOUtils.toString(super.getInputStream(), "utf-8");
    if (StringUtils.isBlank(json)) {
        return super.getInputStream();
    }

    //xss过滤
    json = xssEncode(json);
    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }

        @Override
        public int read() {
            return bis.read();
        }
    };
}
 
Example #29
Source Project: ehcache3-samples   Author: ehcache   File: HeaderUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
    log.error("Entity processing failed, {}", defaultMessage);
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-" + APPLICATION_NAME + "-error", defaultMessage);
    headers.add("X-" + APPLICATION_NAME + "-params", entityName);
    return headers;
}
 
Example #30
Source Project: java-technology-stack   Author: codeEngraver   File: SynchronossPartHttpMessageReader.java    License: MIT License 5 votes vote down vote up
private Part createPart(StreamStorage storage, HttpHeaders httpHeaders) {
	String filename = MultipartUtils.getFileName(httpHeaders);
	if (filename != null) {
		return new SynchronossFilePart(httpHeaders, filename, storage, this.bufferFactory);
	}
	else if (MultipartUtils.isFormField(httpHeaders, this.context)) {
		String value = MultipartUtils.readFormParameterValue(storage, httpHeaders);
		return new SynchronossFormFieldPart(httpHeaders, this.bufferFactory, value);
	}
	else {
		return new SynchronossPart(httpHeaders, storage, this.bufferFactory);
	}
}