org.springframework.http.HttpHeaders Java Examples

The following examples show how to use org.springframework.http.HttpHeaders. 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 File: WebConfigurerTest.java    From cubeai with 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 File: JaxrsClient.java    From servicecomb-java-chassis with Apache License 2.0 8 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 File: SimpleStreamingClientHttpRequest.java    From spring4-understanding with 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 File: Jira.java    From spring-data-dev-tools with 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 File: RestTemplateTests.java    From spring-analysis-note with 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 File: ContentRequestMatchers.java    From java-technology-stack with 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
Source File: MainController.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 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 #8
Source File: ApplicationMockMvcTest.java    From spring-microservice-sample with GNU General Public License v3.0 6 votes vote down vote up
@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 #9
Source File: RedisApplicationTestIT.java    From spring-cloud-zuul-ratelimit with 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 #10
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with 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 #11
Source File: CorsWebFilterTests.java    From spring-analysis-note with 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 #12
Source File: HttpClientConfigTest.java    From molgenis with 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 #13
Source File: ApiKeyAuthTest.java    From openapi-generator with 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 #14
Source File: TaggingRequestInterceptorTest.java    From multiapps-controller with 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 #15
Source File: PushbulletNotifyAction.java    From davos with 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 #16
Source File: CrossOriginTests.java    From spring-analysis-note with 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 #17
Source File: MessageService.java    From frostmourne with 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 #18
Source File: AsyncRestTemplateIntegrationTests.java    From spring4-understanding with 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 #19
Source File: RequestPartServletServerHttpRequestTests.java    From java-technology-stack with 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 #20
Source File: AbstractGenericHttpMessageConverter.java    From java-technology-stack with 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 #21
Source File: PaginationUtilUnitTest.java    From cubeai with 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 #22
Source File: MetadataController.java    From tds with 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 #23
Source File: MarshallingHttpMessageConverter.java    From lams with 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 #24
Source File: UserApi.java    From tutorials with 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 #25
Source File: UserResource.java    From 21-points with 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 #26
Source File: IpAddrControllerTest.java    From alcor with 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 #27
Source File: IngredientController.java    From spring-in-action-5-samples with 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 File: XssHttpServletRequestWrapper.java    From pig with 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 File: HeaderUtil.java    From ehcache3-samples with 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 File: SynchronossPartHttpMessageReader.java    From java-technology-stack with 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);
	}
}