Java Code Examples for org.springframework.web.client.RestClientException

The following examples show how to use org.springframework.web.client.RestClientException. 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: openapi-generator   Source File: FakeApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Test serialization of outer string types
 * <p><b>200</b> - Output string
 * @param body Input string as post body (optional)
 * @return ResponseEntity&lt;String&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<String> fakeOuterStringSerializeWithHttpInfo(String body) throws RestClientException {
    Object postBody = body;
    
    String path = apiClient.expandPath("/fake/outer/string", 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();

    final String[] accepts = { 
        "*/*"
    };
    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.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 2
/**
 * Gets the Keycloak internal ID of a group.
 * @param groupId the userId as sent by the client
 * @return the Keycloak internal ID
 * @throws KeycloakGroupNotFoundException in case the group cannot be found
 * @throws RestClientException in case of technical errors
 */
protected String getKeycloakGroupID(String groupId) throws KeycloakGroupNotFoundException, RestClientException {
	String groupSearch;
	if (keycloakConfiguration.isUseGroupPathAsCamundaGroupId()) {
		groupSearch = "/group-by-path/" + groupId;
	} else {
		return groupId;
	}
	
	try {
		ResponseEntity<String> response = restTemplate.exchange(
				keycloakConfiguration.getKeycloakAdminUrl() + groupSearch, HttpMethod.GET,
				keycloakContextProvider.createApiRequestEntity(), String.class);
		return parseAsJsonObjectAndGetMemberAsString(response.getBody(), "id");
	} catch (JsonException je) {
		throw new KeycloakGroupNotFoundException(groupId + " not found - path unknown", je);
	}
}
 
Example 3
Source Project: davos   Source File: PushbulletNotifyAction.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(PostDownloadExecution execution) {

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

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

    try {

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

    } catch (RestClientException | HttpMessageConversionException e ) {
        
        LOGGER.debug("Full stacktrace", e);
        LOGGER.error("Unable to complete notification to Pushbullet. Given error: {}", e.getMessage());
    }
}
 
Example 4
Source Project: Moss   Source File: AppServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 通过访问skywalking的地址获取skywalking中的AppId
 * @param traceBaseUrl
 * @return
 */
private List<Application> findAllApplications(String traceBaseUrl) {
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);

    RequestPayload requestPayload = payloadBuilder();
    String requestJson = JSON.toJSONString(requestPayload);
    HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);

    try {
        String applicationsForSkywalkingUrl = traceBaseUrl + "/api/applications";
        String data = restTemplate.postForObject(applicationsForSkywalkingUrl,  entity, String.class);
        log.info(data);
        ApplicationsResult applicationsResult = JSON.parseObject(data, ApplicationsResult.class);
        if (applicationsResult == null) {
            log.info("call /api/applications has exception");
            throw new ApplicationException("call /api/applications has exception");
        }
        return applicationsResult.getData().getApplications();
    } catch (RestClientException e) {
        log.info("call applications has exception" + e.getMessage());
    }

    return null;
}
 
Example 5
Source Project: SkaETL   Source File: RegistryService.java    License: Apache License 2.0 6 votes vote down vote up
public void scaledown(ProcessDefinition processDefinition) {
    ConsumerState consumerState = consumerStateRepository.findByKey(processDefinition.getIdProcess());
    int nbInstance = consumerState.getNbInstance() - 1;
    //can't get less than 1 instance
    if (nbInstance >= 1) {
        ConsumerState newState = consumerState.withNbInstance(nbInstance);

        if (consumerState.getStatusProcess() == StatusProcess.ENABLE && consumerState.getRegistryWorkers().size() > nbInstance) {
            String last = Iterables.getLast(consumerState.getRegistryWorkers());
            RegistryWorker worker = workerRepository.findByKey(last);
            log.info("triggering deactivate on worker {} from {}", last, processDefinition);
            try {
                RestTemplate restTemplate = new RestTemplate();
                HttpEntity<ProcessDefinition> request = new HttpEntity<>(consumerState.getProcessDefinition());
                restTemplate.postForObject(worker.getBaseUrl() + "/manage/deactivate", request, String.class);
            } catch (RestClientException e) {
                log.error("an error occured while triggering deactivate on worker " + last + " from " + consumerState.getProcessDefinition(), e.getMessage());
            }
            newState.getRegistryWorkers().remove(last);

        }
        consumerStateRepository.save(newState);
    }
}
 
Example 6
Source Project: openapi-generator   Source File: UserApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create user
 * This can only be done by the logged in user.
 * <p><b>0</b> - successful operation
 * @param body Created user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createUserWithHttpInfo(User body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser");
    }
    
    String path = apiClient.expandPath("/user", 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();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 7
Source Project: tutorials   Source File: StoreApi.java    License: MIT License 6 votes vote down vote up
/**
 * Returns pet inventories by status
 * Returns a map of status codes to quantities
 * <p><b>200</b> - successful operation
 * @return ResponseEntity&lt;Map&lt;String, Integer&gt;&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo() throws RestClientException {
    Object postBody = null;

    String path = apiClient.expandPath("/store/inventory", 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();

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

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

    ParameterizedTypeReference<Map<String, Integer>> returnType = new ParameterizedTypeReference<Map<String, Integer>>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 8
private VaultToken createTokenUsingTlsCertAuthentication() {

		try {
			VaultResponse response = this.restOperations.postForObject(
					AuthenticationUtil.getLoginPath(this.options.getPath()), Collections.emptyMap(),
					VaultResponse.class);

			Assert.state(response.getAuth() != null, "Auth field must not be null");

			logger.debug("Login successful using TLS certificates");

			return LoginTokenUtil.from(response.getAuth());
		}
		catch (RestClientException e) {
			throw VaultLoginException.create("TLS Certificates", e);
		}
	}
 
Example 9
public List<Address> getFromLocationName(String locationName, int maxResults)
		throws IOException {
	final Map<String,String> urlVariables = new HashMap<String, String>();
	urlVariables.put("location", locationName);
	urlVariables.put("maxResults", Integer.toString(maxResults));
	
	try{
		// Nominatim does not handle the HTTP request header "Accept" according to RFC.
		// If any Accept header other than */* is sent, Nominatim responses with HTTP 406 (Not Acceptable).
		// So instead of the rather simple line:
		// final Place[] places = restTemplate.getForObject("http://nominatim.openstreetmap.org/search?q={location}&format=json&addressdetails=1&limit={maxResults}", Place[].class, urlVariables);
		// we have to manually set the Accept header and make things a bit more complicated.
		
		final HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.set("Accept", "*/*");
		final HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
		final ResponseEntity<Place[]> responseEntity = restTemplate.exchange("http://nominatim.openstreetmap.org/search?q={location}&format=json&addressdetails=1&limit={maxResults}",HttpMethod.GET, requestEntity, Place[].class, urlVariables);
		final Place[] places = responseEntity.getBody();
       	return parseResponse(places);
	}catch(RestClientException e){
		Ln.e(e);
		return new ArrayList<Address>();
	}
}
 
Example 10
Source Project: openapi-generator   Source File: UserApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates list of users with given input array
 * 
 * <p><b>0</b> - successful operation
 * @param body List of user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput");
    }
    
    String path = apiClient.expandPath("/user/createWithArray", 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();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 11
@Test
public void resetsLinkOnFailedVerification() {

	verificationTriggersDiscovery();

	doThrow(RestClientException.class).when(this.operations)
			.headForHeaders(anyString());
	this.resource.verifyOrDiscover();

	then(this.resource.getLink()).isNull();
}
 
Example 12
Source Project: onetwo   Source File: ExtRestTemplate.java    License: Apache License 2.0 5 votes vote down vote up
protected <T> ResponseEntity<T> doExecute(RequestContextData context) {
		RequestCallback rc = null;
		HttpMethod method = context.getHttpMethod();
		ResponseExtractor<ResponseEntity<T>> responseExtractor = null;
		HttpHeaders headers = context.getHeaders();
		HttpEntity<?> requestEntity = null;
		
		if(method==HttpMethod.GET) {
//				rc = super.acceptHeaderRequestCallback(context.getResponseType());
//				responseExtractor = responseEntityExtractor(context.getResponseType());
			//根据consumers 设置header,以指定messageConvertor
//			headers = new HttpHeaders();
//			context.acceptHeaderCallback(headers);
			requestEntity = new HttpEntity<>(headers);
			
			rc = super.httpEntityCallback(requestEntity, context.getResponseType());
			responseExtractor = responseEntityExtractor(context.getResponseType());
		}else if(RestUtils.isRequestBodySupportedMethod(method)){
//			headers = new HttpHeaders();
			//根据consumers 设置header,以指定messageConvertor
//			context.acceptHeaderCallback(headers);
			
//			Object requestBody = context.getRequestBodySupplier().get();
//			Object requestBody = context.getRequestBodySupplier().getRequestBody(context);
			Object requestBody = context.getRequestBody();
			logData(requestBody);
			requestEntity = new HttpEntity<>(requestBody, headers);
			
			rc = super.httpEntityCallback(requestEntity, context.getResponseType());
			responseExtractor = responseEntityExtractor(context.getResponseType());
		}else{
			throw new RestClientException("unsupported method: " + method);
		}
		if(context.hasHeaderCallback()){
			rc = wrapRequestCallback(context, rc);
		}
		return execute(context.getRequestUrl(), method, rc, responseExtractor, context.getUriVariables());
	}
 
Example 13
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * Create user
 * This can only be done by the logged in user.
 * <p><b>0</b> - successful operation
 * @param body Created user object
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void createUser(User body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser");
    }
    
    String path = UriComponentsBuilder.fromPath("/user").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>();

    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<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 14
Source Project: openapi-generator   Source File: FakeApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param query  (required)
 * @param body  (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> testBodyWithQueryParamsWithHttpInfo(String query, User body) throws RestClientException {
    Object postBody = body;
    
    // verify the required parameter 'query' is set
    if (query == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'query' when calling testBodyWithQueryParams");
    }
    
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling testBodyWithQueryParams");
    }
    
    String path = apiClient.expandPath("/fake/body-with-query-params", 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(null, "query", query));

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

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 15
Source Project: football-events   Source File: DemoApplication.java    License: MIT License 5 votes vote down vote up
private void rest(String[] line) {
    String httpMethod = line[1];
    String url = line[2];
    String body = line[3];
    body = applyParams(line, 4, body, isoFormat);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpStatus statusCode = null;

    for (int i = 0; i < 3; i++) {
        try {
            statusCode = fbApp.command(url, HttpMethod.valueOf(httpMethod), body);

            if (statusCode.is2xxSuccessful()) {
                logger.debug("{} {} {} {}", statusCode, httpMethod, url, body);
                return;
            }
            if (statusCode == HttpStatus.NOT_FOUND || statusCode == HttpStatus.UNPROCESSABLE_ENTITY) {
                logger.warn("retry {} {} {} {}", statusCode, httpMethod, url, body);
                sleep(2000);
                continue;
            }
            throw new RuntimeException(statusCode + " " + httpMethod + " " + url + " " + body);
        } catch (RestClientException e) {
            throw new RuntimeException(httpMethod + " " + url + " " + body, e);
        }
    }
    throw new RuntimeException("Response status is still " + statusCode + " " + httpMethod + " " + url
            + " " + body);
}
 
Example 16
Source Project: tutorials   Source File: UserApi.java    License: MIT License 5 votes vote down vote up
/**
 * Create user
 * This can only be done by the logged in user.
 * <p><b>0</b> - successful operation
 * @param body Created user object (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createUserWithHttpInfo(User body) throws RestClientException {
    Object postBody = body;

    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser");
    }

    String path = apiClient.expandPath("/user", 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();

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

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 17
Source Project: influx-proxy   Source File: InfluxDBService.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void deleteRetention(Long id) {
    //根据ID软删除本地信息
    ManagementInfoPo managementInfoPo = managementInfoService.deleteRetentionById(id);
    //再删除influxdb
    String deleteRetentionUrl = String.format(Constants.BASE_URL, managementInfoPo.getNodeUrl(), managementInfoPo.getDatabaseName());
    String deleteRetentionData = String.format(Constants.DELETE_RETENTION_URL, managementInfoPo.getRetentionName(), managementInfoPo.getDatabaseName());

    try {
        URI uri = getUri(deleteRetentionUrl, deleteRetentionData);
        restTemplate.postForObject(uri, null, String.class);
    } catch (RestClientException e) {
        throw new InfluxDBProxyException(e.getMessage());
    }
}
 
Example 18
@Override
public <T> T execute(URI url, HttpMethod method, @Nullable RequestCallback callback,
		@Nullable ResponseExtractor<T> extractor) throws RestClientException {

	try {
		extractor.extractData(this.responses.remove());
	}
	catch (Throwable t) {
		throw new RestClientException("Failed to invoke extractor", t);
	}
	return null;
}
 
Example 19
/**
 * Simulates an unreachable provider, which for whatever reason cannot deliver a
 * response to the API. Reasons for that could be: host went offline, connection
 * timeout, connection cannot be established (expired certificate), etc.
 */
public static FeeRateProvider buildDummyUnreachableMempoolFeeRateProvider() throws RestClientException {
    MempoolFeeRateProvider dummyProvider = new MempoolFeeRateProvider.First(env) {
        @Override
        protected FeeRate doGet() {
            throw new RestClientException("Simulating connection error when trying to reach API endpoint");
        }
    };

    // Initialize provider
    dummyProvider.start();
    dummyProvider.stop();

    return dummyProvider;
}
 
Example 20
Source Project: Refactoring-Bot   Source File: WitDataGrabber.java    License: MIT License 5 votes vote down vote up
/**
 * This method communicates with the wit-API. It returns an WitObject with the
 * input of a comment.
 * 
 * @param comment
 * @return witObject
 * @throws WitAPIException
 */
public WitObject getWitObjectFromComment(String comment) throws WitAPIException {
	// Build URI
	UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme("https").host("api.wit.ai")
			.path("/message");

	// Set API-Version
	apiUriBuilder.queryParam("v", "20190122");
	apiUriBuilder.queryParam("q", comment);

	URI witUri = apiUriBuilder.build().encode().toUri();

	RestTemplate rest = new RestTemplate();

	HttpHeaders headers = new HttpHeaders();
	headers.set("User-Agent", USER_AGENT);
	headers.set("Authorization", "Bearer " + botConfig.getWitClientToken());
	HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

	try {
		// Send request to the Wit-API
		return rest.exchange(witUri, HttpMethod.GET, entity, WitObject.class).getBody();
	} catch (RestClientException r) {
		throw new WitAPIException("Could not exchange data with wit.ai!");
	}

}
 
Example 21
Source Project: spring-cloud-sleuth   Source File: AssertingRestTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {
	try {
		return super.doExecute(url, method, requestCallback, responseExtractor);
	}
	catch (Exception e) {
		log.error("Exception occurred while sending the message to uri [" + url
				+ "]. Exception [" + e.getCause() + "]");
		throw new AssertionError(e);
	}
}
 
Example 22
Source Project: spring-vault   Source File: AwsIamAuthentication.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private VaultToken createTokenUsingAwsIam() {

	Map<String, String> login = createRequestBody(this.options);

	try {

		VaultResponse response = this.vaultRestOperations
				.postForObject(AuthenticationUtil.getLoginPath(this.options.getPath()), login, VaultResponse.class);

		Assert.state(response != null && response.getAuth() != null, "Auth field must not be null");

		if (logger.isDebugEnabled()) {

			if (response.getAuth().get("metadata") instanceof Map) {
				Map<Object, Object> metadata = (Map<Object, Object>) response.getAuth().get("metadata");
				logger.debug(String.format("Login successful using AWS-IAM authentication for user id %s, ARN %s",
						metadata.get("client_user_id"), metadata.get("canonical_arn")));
			}
			else {
				logger.debug("Login successful using AWS-IAM authentication");
			}
		}

		return LoginTokenUtil.from(response.getAuth());
	}
	catch (RestClientException e) {
		throw VaultLoginException.create("AWS-IAM", e);
	}
}
 
Example 23
Source Project: api-layer   Source File: ZosmfServiceV1Test.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = AuthenticationServiceException.class)
public void testAuthenticateException() {
    mockZosmfService("zosmf", 1433);
    when(restTemplate.exchange(
        anyString(),
        (HttpMethod) any(),
        (HttpEntity<?>) any(),
        (Class<?>) any()
    )).thenThrow(new RestClientException("any exception"));

    zosmfService.authenticate(new UsernamePasswordAuthenticationToken("user", "pass"));
}
 
Example 24
Source Project: openapi-generator   Source File: PetApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * uploads an image
 * 
 * <p><b>200</b> - successful operation
 * @param petId ID of pet to update (required)
 * @param additionalMetadata Additional data to pass to server (optional)
 * @param file file to upload (optional)
 * @return ResponseEntity&lt;ModelApiResponse&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables);

    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();

    if (additionalMetadata != null)
        formParams.add("additionalMetadata", additionalMetadata);
    if (file != null)
        formParams.add("file", new FileSystemResource(file));

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

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

    ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 25
Source Project: openapi-generator   Source 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 26
Source Project: riptide   Source File: SOAPTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldFailToWriteFault() {
    final CompletableFuture<ClientHttpResponse> future = unit.post()
            .accept(TEXT_XML)
            .body(mock(SOAPFault.class))
            .call(pass());

    final CompletionException exception = assertThrows(CompletionException.class, future::join);
    assertThat(exception.getCause(), is(instanceOf(RestClientException.class)));
}
 
Example 27
Source Project: ExamStack   Source File: ScoreCalcuService.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void postAnswerSheet(String uri, Object body) {
	try {
		restTemplate.postForLocation(uri, body);
	} catch (RestClientException e) {
		LOGGER.error("Received exception:", e);
	}
}
 
Example 28
Source Project: micro-server   Source File: RestClientTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * More complex with Spring REST Template Based NIORestTemplate
 *
 **/
@Test
public void testCRUDSpring() throws InterruptedException, ExecutionException, RestClientException, URISyntaxException{
	
	
	assertThat(rest.getForEntity(new URI("http://localhost:8080/rest-app/rest/get"),List.class).get().getBody().get(0),is("ok"));
	
	assertThat(rest.postForEntity("http://localhost:8080/rest-app/rest/post", new HttpEntity(ImmutableMap.of(1,"hello")), ImmutableSet.class).get().getBody(),is(ImmutableSet.of("hello")));
	assertThat( rest.put("http://localhost:8080/rest-app/rest/put",new HttpEntity(ImmutableMap.of(1,"hello")),ImmutableSet.class).get()
								,is(nullValue()));
	assertThat(rest.delete("http://localhost:8080/rest-app/rest/delete").get(),is(nullValue()));
}
 
Example 29
Source Project: openapi-generator   Source File: FakeApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * creates an XmlItem
 * this route creates an XmlItem
 * <p><b>200</b> - successful operation
 * @param xmlItem XmlItem Body (required)
 * @return ResponseEntity&lt;Void&gt;
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ResponseEntity<Void> createXmlItemWithHttpInfo(XmlItem xmlItem) throws RestClientException {
    Object postBody = xmlItem;
    
    // verify the required parameter 'xmlItem' is set
    if (xmlItem == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'xmlItem' when calling createXmlItem");
    }
    
    String path = apiClient.expandPath("/fake/create_xml_item", 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();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
 
Example 30
Source Project: tutorials   Source File: PetApi.java    License: MIT License 5 votes vote down vote up
/**
 * Updates a pet in the store with form data
 * 
 * <p><b>405</b> - Invalid input
 * @param petId ID of pet that needs to be updated
 * @param name Updated name of the pet
 * @param status Updated status of the pet
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void updatePetWithForm(Long petId, String name, String status) throws RestClientException {
    Object postBody = null;
    
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm");
    }
    
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString();
    
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    
    if (name != null)
        formParams.add("name", name);
    if (status != null)
        formParams.add("status", status);

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

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

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}