Java Code Examples for org.springframework.http.HttpMethod

The following examples show how to use org.springframework.http.HttpMethod. 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: java-technology-stack   Author: codeEngraver   File: SampleTests.java    License: MIT License 6 votes vote down vote up
@Test // SPR-14694
public void repeatedAccessToResponseViaResource() {

	Resource resource = new ClassPathResource("ludwig.json", this.getClass());

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setInterceptors(Collections.singletonList(new ContentInterceptor(resource)));

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate)
			.ignoreExpectOrder(true)
			.bufferContent()  // enable repeated reads of response body
			.build();

	mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
			.andRespond(withSuccess(resource, MediaType.APPLICATION_JSON));

	restTemplate.getForObject("/composers/{id}", Person.class, 42);

	mockServer.verify();
}
 
Example #2
Source Project: taskana   Author: Taskana   File: TaskControllerIntTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testGetAllTasksByWorkbasketIdWithinSinglePlannedTimeInterval() {

  Instant plannedFromInstant = Instant.now().minus(6, ChronoUnit.DAYS);
  Instant plannedToInstant = Instant.now().minus(3, ChronoUnit.DAYS);

  ResponseEntity<TaskanaPagedModel<TaskSummaryRepresentationModel>> response =
      TEMPLATE.exchange(
          restHelper.toUrl(Mapping.URL_TASKS)
              + "?workbasket-id=WBI:100000000000000000000000000000000001"
              + "&planned-from="
              + plannedFromInstant
              + "&planned-until="
              + plannedToInstant
              + "&sort-by=planned",
          HttpMethod.GET,
          restHelper.defaultRequest(),
          TASK_SUMMARY_PAGE_MODEL_TYPE);
  assertThat(response.getBody()).isNotNull();
  assertThat((response.getBody()).getLink(IanaLinkRelations.SELF)).isNotNull();
  assertThat(response.getBody().getContent()).hasSize(3);
}
 
Example #3
Source Project: spring-cloud-skipper   Author: spring-cloud   File: AboutController.java    License: Apache License 2.0 6 votes vote down vote up
private String getChecksum(String defaultValue, String url,
		String version) {
	String result = defaultValue;
	if (result == null && StringUtils.hasText(url)) {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLHostnameVerifier(new NoopHostnameVerifier())
				.build();
		HttpComponentsClientHttpRequestFactory requestFactory
				= new HttpComponentsClientHttpRequestFactory();
		requestFactory.setHttpClient(httpClient);
		url = constructUrl(url, version);
		try {
			ResponseEntity<String> response
					= new RestTemplate(requestFactory).exchange(
					url, HttpMethod.GET, null, String.class);
			if (response.getStatusCode().equals(HttpStatus.OK)) {
				result = response.getBody();
			}
		}
		catch (HttpClientErrorException httpException) {
			// no action necessary set result to undefined
			logger.debug("Didn't retrieve checksum because", httpException);
		}
	}
	return result;
}
 
Example #4
@Override
public Void execute(final ResourceWithMetadata resource, final Params params, final WebScriptResponse res, boolean isReadOnly)
{
    final ResourceOperation operation = resource.getMetaData().getOperation(HttpMethod.DELETE);
    final WithResponse callBack = new WithResponse(operation.getSuccessStatus(), DEFAULT_JSON_CONTENT,CACHE_NEVER);

    // MNT-20308 - allow write transactions for authentication api
    RetryingTransactionHelper transHelper = getTransactionHelper(resource.getMetaData().getApi().getName());

    transHelper.doInTransaction(
        new RetryingTransactionCallback<Void>()
        {
            @Override
            public Void execute() throws Throwable
            {
                executeAction(resource, params, callBack); //ignore return result
                return null;
            }
        }, false, true);
    setResponse(res,callBack);
    return null;

}
 
Example #5
Source Project: spring-analysis-note   Author: Vip-Augus   File: DefaultCorsProcessorTests.java    License: MIT License 6 votes vote down vote up
@Test
public void preflightRequestCredentialsWithOriginWildcard() throws Exception {
	this.request.setMethod(HttpMethod.OPTIONS.name());
	this.request.addHeader(HttpHeaders.ORIGIN, "https://domain2.com");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "Header1");
	this.conf.addAllowedOrigin("https://domain1.com");
	this.conf.addAllowedOrigin("*");
	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("https://domain2.com", this.response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
	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 #6
Source Project: spring-cloud-dataflow   Author: spring-cloud   File: DefaultContainerImageMetadataResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
private void mockBlogRestTemplateCall(String jsonResponse, String registryHost, String registryPort,
		String repository, String digest) {

	UriComponents blobUriComponents = UriComponentsBuilder.newInstance()
			.scheme("https")
			.host(registryHost)
			.port(StringUtils.hasText(registryPort) ? registryPort : null)
			.path("v2/{repository}/blobs/{digest}")
			.build().expand(repository, digest);

	when(mockRestTemplate.exchange(
			eq(blobUriComponents.toUri()),
			eq(HttpMethod.GET),
			any(HttpEntity.class),
			eq(String.class)))
			.thenReturn(new ResponseEntity<>(jsonResponse, HttpStatus.OK));
}
 
Example #7
Source Project: spring-boot-microservices   Author: rohitghatol   File: OAuthConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Define the security that applies to the proxy
 */
@Override
   public void configure(HttpSecurity http) throws Exception {
       http
       	.authorizeRequests()
       	//Allow access to all static resources without authentication
       	.antMatchers("/","/**/*.html").permitAll()
       	.anyRequest().authenticated()
       	.antMatchers(HttpMethod.GET, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')")
           .antMatchers(HttpMethod.OPTIONS, "/api/user/**","/api/task/**").access("#oauth2.hasScope('read')")
           .antMatchers(HttpMethod.POST, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.PUT, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.PATCH, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .antMatchers(HttpMethod.DELETE, "/api/user/**","/api/task/**").access("#oauth2.hasScope('write')")
           .and().csrf().csrfTokenRepository(this.getCSRFTokenRepository())
           .and().addFilterAfter(this.createCSRFHeaderFilter(), CsrfFilter.class);
   }
 
Example #8
Source Project: skywalking   Author: apache   File: SimpleQueryClient.java    License: Apache License 2.0 6 votes vote down vote up
public Endpoints endpoints(final EndpointQuery query) throws Exception {
    final URL queryFileUrl = Resources.getResource("endpoints.gql");
    final String queryString = Resources.readLines(queryFileUrl, StandardCharsets.UTF_8)
                                        .stream()
                                        .filter(it -> !it.startsWith("#"))
                                        .collect(Collectors.joining())
                                        .replace("{serviceId}", query.serviceId());
    final ResponseEntity<GQLResponse<Endpoints>> responseEntity = restTemplate.exchange(
        new RequestEntity<>(queryString, HttpMethod.POST, URI.create(endpointUrl)),
        new ParameterizedTypeReference<GQLResponse<Endpoints>>() {
        }
    );

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        throw new RuntimeException("Response status != 200, actual: " + responseEntity.getStatusCode());
    }

    return Objects.requireNonNull(responseEntity.getBody()).getData();
}
 
Example #9
Source Project: sdk-rest   Author: bullhorn   File: RestApiSession.java    License: MIT License 6 votes vote down vote up
private synchronized JSONObject getLoginInfoFromApi() {
    if (loginInfo != null) {
        return loginInfo;
    }

    Map<String, Object> parameters = Maps.newLinkedHashMap();
    parameters.put("username", restCredentials.getUsername());

    try {
        ResponseEntity<String> response = restTemplate.exchange(LOGIN_INFO_URL, HttpMethod.GET, HttpEntity.EMPTY, String.class, parameters);

        if (StringUtils.isBlank(response.getBody())) {
            throw new RestApiException("Failed to dynamically determine REST urls with username " + restCredentials.getUsername());
        }

        this.loginInfo = new JSONObject(response.getBody());

        return this.loginInfo;
    } catch(RestClientException | JSONException e) {
        log.error("Error occurred dynamically determining REST urls with username " + restCredentials.getUsername(), e);

        throw new RestApiException("Failed to dynamically determine REST urls with username " + restCredentials.getUsername());
    }
}
 
Example #10
Source Project: Qualitis   Author: WeBankFinTech   File: LinkisJobSubmitter.java    License: Apache License 2.0 6 votes vote down vote up
private Map getTaskDetail(Integer taskId, String user, String ujesAddress, String clusterName) throws TaskNotExistException, ClusterInfoNotConfigException {
    String url = getPath(ujesAddress).path(linkisConfig.getStatus()).toString();
    url = url.replace("{id}", String.valueOf(taskId));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Token-User", user);
    headers.add("Token-Code", getToken(clusterName));
    HttpEntity entity = new HttpEntity<>(headers);

    LOGGER.info("Start to get job status from linkis. url: {}, method: {}, body: {}", url, javax.ws.rs.HttpMethod.GET, entity);
    Map response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class).getBody();
    LOGGER.info("Succeed to get job status from linkis. response: {}", response);

    if (!checkResponse(response)) {
        throw new TaskNotExistException("Can not get status of task, task_id : " + taskId);
    }

    if (((Map)response.get("data")).get("task") == null) {
        throw new TaskNotExistException("Job id: " + taskId + " does not exist");
    }

    return response;
}
 
Example #11
Source Project: rdf4j   Author: eclipse   File: ConfigViewTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRender() throws Exception {

	ConfigView configView = ConfigView.getInstance();

	Model configData = new LinkedHashModelFactory().createEmptyModel();
	configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS);

	Map<Object, Object> map = new LinkedHashMap<>();
	map.put(ConfigView.HEADERS_ONLY, false);
	map.put(ConfigView.CONFIG_DATA_KEY, configData);
	map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES);

	final MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod(HttpMethod.GET.name());
	request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType());

	MockHttpServletResponse response = new MockHttpServletResponse();

	configView.render(map, request, response);

	String ntriplesData = response.getContentAsString();
	Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES);
	assertThat(renderedData).isNotEmpty();
}
 
Example #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: ResourceHandlerFunctionTests.java    License: MIT License 6 votes vote down vote up
@Test
public void options() throws ServletException, IOException {
	MockHttpServletRequest servletRequest = new MockHttpServletRequest("OPTIONS", "/");
	ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter));

	ServerResponse response = this.handlerFunction.handle(request);
	assertEquals(HttpStatus.OK, response.statusCode());
	assertEquals(EnumSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS), response.headers().getAllow());

	MockHttpServletResponse servletResponse = new MockHttpServletResponse();
	ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context);
	assertNull(mav);

	assertEquals(200, servletResponse.getStatus());
	assertEquals("GET,HEAD,OPTIONS", servletResponse.getHeader("Allow"));
	byte[] actualBytes = servletResponse.getContentAsByteArray();
	assertEquals(0, actualBytes.length);
}
 
Example #13
Source Project: flowable-engine   Author: flowable   File: FlowableAdminApplicationSecurityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void nonAdminUserShouldBeRedirectedToIdm() {
    String configsUrl = "http://localhost:" + serverPort + "/flowable-admin/app/rest/server-configs";
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.COOKIE, rememberMeCookie("user", "test-user-value"));
    HttpEntity<?> request = new HttpEntity<>(headers);
    ResponseEntity<Object> result = restTemplate.exchange(configsUrl, HttpMethod.GET, request, Object.class);

    assertThat(result.getStatusCode())
        .as("GET server-configs")
        .isEqualTo(HttpStatus.FOUND);

    assertThat(result.getHeaders().getFirst(HttpHeaders.LOCATION))
        .as("redirect location")
        .isEqualTo("http://localhost:8080/flowable-idm/#/login?redirectOnAuthSuccess=true&redirectUrl=" + configsUrl);
}
 
Example #14
Source Project: konker-platform   Author: KonkerLabs   File: IuguServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnErrorCreateIuguCustomer() {
    IuguCustomer iuguCustomer = IuguCustomer.builder()
            .email("[email protected]")
            .name("Iugu Customer")
            .zipCode("05500-100")
            .street("Avenida dos Testes")
            .city("São Paulo")
            .state("SP")
            .build();

    HttpEntity<IuguCustomer> request = new HttpEntity<>(iuguCustomer);
    ResponseEntity<IuguCustomer> responseEntity = ResponseEntity.badRequest().body(null);
    when(restTemplate.exchange("https://api.iugu.com/v1/customers?api_token=b17421313f9a8db907afa7b7047fbcd8",
            HttpMethod.POST,
            request,
            IuguCustomer.class))
            .thenReturn(responseEntity);

    ServiceResponse<IuguCustomer> response = iuguService.createIuguCustomer(iuguCustomer);

    Assert.assertThat(response, hasErrorMessage(IuguService.Validations.IUGU_CUSTOMER_CREATION_ERROR.getCode()));
}
 
Example #15
@Test
public void containerImageMetadataResolverWithActiveSSL() throws URISyntaxException {
	assertThat(containerImageMetadataResolver).isNotNull();
	Map<String, String> labels = containerImageMetadataResolver.getImageLabels("demo.goharbor.io/test/image:1.0.0");
	assertThat(labels).containsExactly(Collections.singletonMap("foo", "bar").entrySet().iterator().next());

	// Determine the OAuth2 token service entry point.
	verify(noSslVerificationContainerRestTemplate)
			.exchange(eq(new URI("https://demo.goharbor.io/v2/_catalog")), eq(HttpMethod.GET), any(), eq(Map.class));

	// Get authorization token
	verify(containerRestTemplate).exchange(
			eq(new URI("https://demo.goharbor.io/service/token?service=demo-registry2&scope=repository:test/image:pull")),
			eq(HttpMethod.GET), any(), eq(Map.class));
	// Get Manifest
	verify(containerRestTemplate).exchange(eq(new URI("https://demo.goharbor.io/v2/test/image/manifests/1.0.0")),
			eq(HttpMethod.GET), any(), eq(Map.class));
	// Get Blobs
	verify(containerRestTemplate).exchange(eq(new URI("https://demo.goharbor.io/v2/test/image/blobs/test_digest")),
			eq(HttpMethod.GET), any(), eq(String.class));
}
 
Example #16
Source Project: spring-analysis-note   Author: Vip-Augus   File: CorsConfiguration.java    License: MIT License 6 votes vote down vote up
/**
 * By default a newly created {@code CorsConfiguration} does not permit any
 * cross-origin requests and must be configured explicitly to indicate what
 * should be allowed.
 * <p>Use this method to flip the initialization model to start with open
 * defaults that permit all cross-origin requests for GET, HEAD, and POST
 * requests. Note however that this method will not override any existing
 * values already set.
 * <p>The following defaults are applied if not already set:
 * <ul>
 * <li>Allow all origins.</li>
 * <li>Allow "simple" methods {@code GET}, {@code HEAD} and {@code POST}.</li>
 * <li>Allow all headers.</li>
 * <li>Set max age to 1800 seconds (30 minutes).</li>
 * </ul>
 */
public CorsConfiguration applyPermitDefaultValues() {
	if (this.allowedOrigins == null) {
		this.allowedOrigins = DEFAULT_PERMIT_ALL;
	}
	if (this.allowedMethods == null) {
		this.allowedMethods = DEFAULT_PERMIT_METHODS;
		this.resolvedMethods = DEFAULT_PERMIT_METHODS
				.stream().map(HttpMethod::resolve).collect(Collectors.toList());
	}
	if (this.allowedHeaders == null) {
		this.allowedHeaders = DEFAULT_PERMIT_ALL;
	}
	if (this.maxAge == null) {
		this.maxAge = 1800L;
	}
	return this;
}
 
Example #17
Source Project: servicecomb-java-chassis   Author: apache   File: TestSpringMVCObjectParamType.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiLayerObjectParam_rt() {
  MultiLayerObjectParam request = new MultiLayerObjectParam("sss-1", new Date(),
      new MultiLayerObjectParam2("sss-2", 12.12, FlattenObjectRequest.createFlattenObjectRequest()));
  ResponseEntity<MultiLayerObjectParam> responseEntity = consumers.getSCBRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(request), MultiLayerObjectParam.class);
  assertEquals(request, responseEntity.getBody());
  assertEquals(200, responseEntity.getStatusCodeValue());

  responseEntity = consumers.getSCBRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(null), MultiLayerObjectParam.class);
  //  Highway will not give null return value
  Assert.assertTrue(responseEntity.getBody() == null || responseEntity.getBody().getString() == null);
  assertEquals(200, responseEntity.getStatusCodeValue());
}
 
Example #18
Source Project: spring-vault   Author: spring-projects   File: AwsIamAuthenticationUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldUsingAuthenticationSteps() {

	this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST))
			.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
			.andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists())
			.andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
					"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
							+ "}"));

	AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role")
			.credentials(new BasicAWSCredentials("foo", "bar")).build();

	AuthenticationSteps steps = AwsIamAuthentication.createAuthenticationSteps(options);
	AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor(steps, this.restTemplate);

	VaultToken login = executor.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("my-token");
	assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10));
	assertThat(((LoginToken) login).isRenewable()).isTrue();
}
 
Example #19
Source Project: Mastering-Microservices-with-Java-9-Second-Edition   Author: PacktPublishing   File: EdgeApp.java    License: MIT License 5 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    System.out.println("\n\n\n start RestTemplate client...");
    ResponseEntity<Collection<Restaurant>> exchange
            = this.restTemplate.exchange(
                    "http://restaurant-service/v1/restaurants?name=o",
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<Collection<Restaurant>>() {
            },
                    (Object) "restaurants");
    exchange.getBody().forEach((Restaurant restaurant) -> {
        System.out.println("\n\n\n[ " + restaurant.getId() + " " + restaurant.getName() + "]");
    });
}
 
Example #20
Source Project: java-technology-stack   Author: codeEngraver   File: DefaultServerRequestTests.java    License: MIT License 5 votes vote down vote up
@Test
public void cookies() {
	HttpCookie cookie = new HttpCookie("foo", "bar");
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest.method(HttpMethod.GET, "http://example.com").cookie(cookie));

	DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);

	MultiValueMap<String, HttpCookie> expected = new LinkedMultiValueMap<>();
	expected.add("foo", cookie);

	assertEquals(expected, request.cookies());

}
 
Example #21
@Override
	protected ServiceDomainResponse makeServiceCall(ServiceDomainRequest payload)
			throws UpstreamServiceTimedOutException, UpstreamServiceFailedException {
		
		MultiValueMap<String, String> urlQueryParams = new LinkedMultiValueMap<>();
		
		String endPoint = Validator.isNotNull(payload.getEndpoint()) ? payload.getEndpoint() : DossierStatisticConfig.get(DossierStatisticConstants.SERVICE_DOMAIN_ENDPOINT);
		
		//LOG.info(endPoint);
		
		// get the params for EE
		HashMap<String, String> urlPathSegments = new HashMap<>();

		// build the url
		String url = buildUrl(endPoint, urlPathSegments, urlQueryParams);

		HttpHeaders httpHeaders = new HttpHeaders();
		
		httpHeaders.add(DossierStatisticConstants.GROUP_ID, Long.toString(payload.getGroupId()));
//		if (Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY))
//				&& Validator.isNotNull(PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET))) {
//			setHttpHeadersAuthorization(httpHeaders, PropsUtil.get(ServerConfigContants.SERVER_SYNC_KEY), PropsUtil.get(ServerConfigContants.SERVER_SYNC_SECRET));
//		}
//		else {
//			httpHeaders.add("Authorization", "Basic " + DossierStatisticConfig.get(DossierStatisticConstants.OPENCPS_AUTHENCATION));
//		}
		if (Validator.isNotNull(payload.getUsername()) && Validator.isNotNull(payload.getPassword())) {
			httpHeaders.add("Authorization", "Basic " + Base64.getEncoder().encodeToString((payload.getUsername() + ":" + payload.getPassword()).getBytes()));			
			System.out.println("HTTP BASIC: " + "Basic " + Base64.getEncoder().encodeToString((payload.getUsername() + ":" + payload.getPassword()).getBytes()));
		}
		System.out.println("END POINT: " + endPoint);
		return executeGenericRestCall(url, HttpMethod.GET, httpHeaders, payload, ServiceDomainResponse.class).getBody();

	}
 
Example #22
Source Project: x-pipe   Author: ctripcorp   File: DefaultKeeperContainerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<KeeperInstanceMeta> getAllKeepers() {
    try {
        ResponseEntity<List<KeeperInstanceMeta>> result = restTemplate.exchange("http://{ip}:{port}/keepers",
                HttpMethod.GET, null, keeperInstanceMetaListType,
                keeperContainerMeta.getIp(), keeperContainerMeta.getPort());
        return result.getBody();
    } catch (HttpStatusCodeException ex) {
        throw KeeperContainerErrorParser.parseErrorFromHttpException(ex);
    }
}
 
Example #23
Source Project: java-technology-stack   Author: codeEngraver   File: ResponseEntityExceptionHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Customize the response for HttpRequestMethodNotSupportedException.
 * <p>This method logs a warning, sets the "Allow" header, and delegates to
 * {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param request the current request
 * @return a {@code ResponseEntity} instance
 */
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(
		HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

	pageNotFoundLogger.warn(ex.getMessage());

	Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods();
	if (!CollectionUtils.isEmpty(supportedMethods)) {
		headers.setAllow(supportedMethods);
	}
	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example #24
Source Project: CryptoBuddy   Author: Patchett   File: NewsService.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a GenericRestCall and returns it as an Rx observable. An observable will be fired
 * each time a susbcriber subscribes to it, and multiple subscribers can be attached to a single
 * observable.
 * @param context the context for caching
 * @return an observable returning a RestResults<News[]> object
 */
public static rx.Observable<RestResults<News[]>> getObservableNews(Context context) {
    return new GenericRestCall<>(Void.class, News[].class, String.class)
            .setUrl(BTC_NEWS_URL)
            .setContext(context.getApplicationContext())
            .isCacheEnabled(true)
            .setCacheTime(30000L)
            .setMethodToCall(HttpMethod.GET)
            .setAutomaticCacheRefresh(true)
            .setReprocessWhenRefreshing(true)
            .asObservable();
}
 
Example #25
Source Project: MicroCommunity   Author: java110   File: PrivilegeServiceSMOImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param pd
 * @return
 */
@Override
public ResponseEntity<String> listStaffPrivileges(IPageData pd) {
    Assert.hasLength(pd.getUserId(), "用户未登录请先登录");

    JSONObject privilegeInfoObj = JSONObject.parseObject(pd.getReqData());
    Assert.jsonObjectHaveKey(privilegeInfoObj, "staffId", "请求报文中未包含员工ID 节点");

    ResponseEntity<String> storeInfo = super.getStoreInfo(pd, restTemplate);

    if (storeInfo.getStatusCode() != HttpStatus.OK) {
        return storeInfo;
    }
    // 商户返回信息
    JSONObject storeInfoObj = JSONObject.parseObject(storeInfo.getBody());

    String storeId = storeInfoObj.getString("storeId");
    privilegeInfoObj.put("storeId", storeId);

    ResponseEntity<String> privilegeGroup = super.callCenterService(restTemplate, pd, "",
            ServiceConstant.SERVICE_API_URL + "/api/query.user.privilege?userId=" + privilegeInfoObj.getString("staffId") + "&domain=" + storeInfoObj.getString("storeTypeCd"), HttpMethod.GET);
    if (privilegeGroup.getStatusCode() != HttpStatus.OK) {
        return privilegeGroup;
    }
    JSONObject resultObj = JSONObject.parseObject(privilegeGroup.getBody().toString());

    JSONArray privileges = resultObj.getJSONArray("privileges");

    JSONObject resObj = new JSONObject();
    resObj.put("datas", privileges);

    return new ResponseEntity<String>(resObj.toJSONString(), HttpStatus.OK);
}
 
Example #26
Source Project: servicecomb-java-chassis   Author: apache   File: TestJAXRSObjectParamType.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiLayerObjectParam_edge() {
  MultiLayerObjectParam request = new MultiLayerObjectParam("sss-1", new Date(),
      new MultiLayerObjectParam2("sss-2", 12.12, createFlattenObjectRequest()));
  ResponseEntity<MultiLayerObjectParam> responseEntity = consumers.getEdgeRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(request), MultiLayerObjectParam.class);
  Assert.assertEquals(request, responseEntity.getBody());
  Assert.assertEquals(200, responseEntity.getStatusCodeValue());
  responseEntity = consumers.getEdgeRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(request), MultiLayerObjectParam.class);
  Assert.assertEquals(request, responseEntity.getBody());
  Assert.assertEquals(200, responseEntity.getStatusCodeValue());

  responseEntity = consumers.getEdgeRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(null), MultiLayerObjectParam.class);
  // highway will not return null object
  Assert.assertTrue(responseEntity.getBody() == null || responseEntity.getBody().getString() == null);
  Assert.assertEquals(200, responseEntity.getStatusCodeValue());
  responseEntity = consumers.getEdgeRestTemplate()
      .exchange("/testMultiLayerObjectParam", HttpMethod.PUT,
          new HttpEntity<>(null), MultiLayerObjectParam.class);
  // highway will not return null object
  Assert.assertTrue(responseEntity.getBody() == null || responseEntity.getBody().getString() == null);
  Assert.assertEquals(200, responseEntity.getStatusCodeValue());
}
 
Example #27
Source Project: Project   Author: GJXAIOU   File: RESTClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void options4Allow() {
	Set<HttpMethod> httpMethods = template.optionsForAllow(url());
	System.out.println(httpMethods.size());
	for(HttpMethod hm : httpMethods) {
		System.out.println(hm);
	}
}
 
Example #28
Source Project: openapi-generator   Author: OpenAPITools   File: PetApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds Pets by tags
 * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
 * <p><b>200</b> - successful operation
 * <p><b>400</b> - Invalid tag value
 * @param tags Tags to filter by (required)
 * @return ResponseEntity&lt;Set&lt;Pet&gt;&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
@Deprecated
public ResponseEntity<Set<Pet>> findPetsByTagsWithHttpInfo(Set<String> tags) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'tags' is set
    if (tags == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags");
    }
    
    String path = apiClient.expandPath("/pet/findByTags", Collections.<String, Object>emptyMap());

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
    final MultiValueMap formParams = new LinkedMultiValueMap();

    queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags));

    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[] { "petstore_auth" };

    ParameterizedTypeReference<Set<Pet>> returnType = new ParameterizedTypeReference<Set<Pet>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example #29
Source Project: OTX-Java-SDK   Author: AlienVault-OTX   File: HeaderSettingRequestFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
    ClientHttpRequest request = super.createRequest(uri, httpMethod);
    request.getHeaders().add("X-OTX-API-KEY",apiKey);
    request.getHeaders().add(HttpHeaders.USER_AGENT,SDK_USER_AGENT);
    return request;
}
 
Example #30
Source Project: citrus-simulator   Author: citrusframework   File: HttpRequestAnnotationMatcherTest.java    License: Apache License 2.0 5 votes vote down vote up
private HttpMessage setupHttpMessage(String path, HttpMethod method, Map<String, String> queryParams) {
    final HttpMessage httpMessage = Mockito.mock(HttpMessage.class);
    when(httpMessage.getPath()).thenReturn(path);
    when(httpMessage.getRequestMethod()).thenReturn(method);
    when(httpMessage.getQueryParams()).thenReturn(queryParams);
    return httpMessage;
}