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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #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: BonusPoller.java    From microservice-istio with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		OrderFeed feed = response.getBody();
		for (OrderFeedEntry entry : feed.getOrders()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Bonus bonus = restTemplate
						.getForEntity(entry.getLink(), Bonus.class).getBody();
				log.trace("saving bonus {}", bonus.getId());
				bonusService.calculateBonus(bonus);
			}
		}
		if (response.getHeaders().getFirst("Last-Modified") != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #23
Source File: TransferServiceListener.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
@Override
public void soService(ServiceDataFlowEvent event) {
    //获取数据上下文对象
    DataFlowContext dataFlowContext = event.getDataFlowContext();
    AppService service = event.getAppService();
    String paramIn = dataFlowContext.getReqData();
    HttpHeaders header = new HttpHeaders();
    for(String key : dataFlowContext.getRequestCurrentHeaders().keySet()){
        header.add(key,dataFlowContext.getRequestCurrentHeaders().get(key));
    }
    HttpEntity<String> httpEntity = new HttpEntity<String>(paramIn, header);
    //http://user-service/test/sayHello
    super.doRequest(dataFlowContext, service, httpEntity);
}
 
Example #24
Source File: ExecuteHandler.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Override
public void execute(final String jobName, final String jobGroup) {

    // 1. 获取数据库执行的job任务
    JobInfoMapper jobInfoMapper = ShopSpringContext.getBean(JobInfoMapper.class);
    JobInfo jobInfo = new JobInfo();
    jobInfo.setJobName(jobName);
    jobInfo.setJobStatus(JobStatusEnums.NORMAL.getCode());
    JobInfo selectJobInfo = jobInfoMapper.selectOne(new QueryWrapper<>(jobInfo));
    // 访问的资源请求地址
    if (Objects.nonNull(selectJobInfo)) {
        Map<String, String> paramMap = new ConcurrentHashMap<>();
        String url = "http://" + selectJobInfo.getServiceName() + selectJobInfo.getServiceMethod();
        if (!StringUtils.isEmpty(selectJobInfo.getParams())) {
            paramMap.putAll(JSON.parseObject(selectJobInfo.getParams(), Map.class));
        }
        OAuth2RestTemplate template = ShopSpringContext.getBean(OAuth2RestTemplate.class);
        // 得到服务鉴权访问token
        OAuth2AccessToken accessToken = template.getAccessToken();
        // 设置请求消息头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setBearerAuth(accessToken.toString());
        // 得到 RestTemplate 访问的负载均衡对象
        RestTemplate restTemplate = ShopSpringContext.getBean("restTemplate", RestTemplate.class);
        ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(paramMap, headers), Object.class);
        log.info("执行服务调用结束,返回结果 result = {}", JSON.toJSONString(responseEntity));
    } else {
        log.error("未找到执行的定时任务 jobName = {}, jobGroup = {}", jobName, jobGroup);
    }
}
 
Example #25
Source File: DefaultClientRequestBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
public BodyInserterRequest(HttpMethod method, URI url, HttpHeaders headers,
		MultiValueMap<String, String> cookies, BodyInserter<?, ? super ClientHttpRequest> body,
		Map<String, Object> attributes) {

	this.method = method;
	this.url = url;
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
	this.cookies = CollectionUtils.unmodifiableMultiValueMap(cookies);
	this.body = body;
	this.attributes = Collections.unmodifiableMap(attributes);

	Object id = attributes.computeIfAbsent(LOG_ID_ATTRIBUTE, name -> ObjectUtils.getIdentityHexString(this));
	this.logPrefix = "[" + id + "] ";
}
 
Example #26
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 #27
Source File: AsyncRestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<Set<HttpMethod>> optionsForAllow(String url, Object... uriVars)
		throws RestClientException {

	ResponseExtractor<HttpHeaders> extractor = headersExtractor();
	ListenableFuture<HttpHeaders> future = execute(url, HttpMethod.OPTIONS, null, extractor, uriVars);
	return adaptToAllowHeader(future);
}
 
Example #28
Source File: HttpBasicAuth.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
    if (username == null && password == null) {
        return;
    }
    String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
    headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8)));
}
 
Example #29
Source File: CorsAbstractHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void actualRequestWithoutCorsConfigurationProvider() throws Exception {
	this.request.setMethod(RequestMethod.GET.name());
	this.request.setRequestURI("/foo");
	this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
	assertNotNull(chain);
	assertTrue(chain.getHandler() instanceof SimpleHandler);
}
 
Example #30
Source File: MockHttpServletRequest.java    From java-technology-stack with MIT License 5 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;
}