org.springframework.web.client.HttpStatusCodeException Java Examples

The following examples show how to use org.springframework.web.client.HttpStatusCodeException. 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: Jira.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void createReleaseVersion(ModuleIteration moduleIteration) {

	Assert.notNull(moduleIteration, "ModuleIteration must not be null.");

	Map<String, Object> parameters = newUrlTemplateVariables();
	HttpHeaders httpHeaders = newUserScopedHttpHeaders();

	Optional<JiraReleaseVersion> versionsForModuleIteration = findJiraReleaseVersion(moduleIteration);

	if (versionsForModuleIteration.isPresent() || moduleIteration.getProject() == Projects.GEMFIRE) {
		return;
	}

	JiraVersion jiraVersion = new JiraVersion(moduleIteration);
	logger.log(moduleIteration, "Creating Jira release version %s", jiraVersion);

	JiraReleaseVersion jiraReleaseVersion = JiraReleaseVersion.of(moduleIteration, jiraVersion);

	try {
		operations.exchange(VERSIONS_TEMPLATE, HttpMethod.POST, new HttpEntity<Object>(jiraReleaseVersion, httpHeaders),
				JiraReleaseVersion.class, parameters).getBody();
	} catch (HttpStatusCodeException e) {
		System.out.println(e.getResponseBodyAsString());
	}
}
 
Example #2
Source File: SecurityOfficerEventProcessor.java    From egeria with Apache License 2.0 6 votes vote down vote up
private void setSecurityTag(String guid, SecurityClassification securityClassification) {
    String securityOMASURL = getSecurityOMASURL(guid);
    String securityClassificationBody = getBody(securityClassification);

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> entity = new HttpEntity<>(securityClassificationBody, getBasicHTTPHeaders());

    try {
        ResponseEntity<SecurityOfficerOMASAPIResponse> elementEntity = restTemplate.exchange(securityOMASURL, HttpMethod.POST, entity, SecurityOfficerOMASAPIResponse.class);
        if (elementEntity.getBody() != null) {
            log.debug("result of setting the security tag: {}", elementEntity.getBody());
        }
    } catch (HttpStatusCodeException exception) {
        log.debug("Unable to set/update the security tag for schema element {}", guid);
    }
}
 
Example #3
Source File: VaultSysTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Override
public VaultInitializationResponse initialize(VaultInitializationRequest vaultInitializationRequest) {

	Assert.notNull(vaultInitializationRequest, "VaultInitialization must not be null");

	return requireResponse(this.vaultOperations.doWithVault(restOperations -> {

		try {
			ResponseEntity<VaultInitializationResponseImpl> exchange = restOperations.exchange("sys/init",
					HttpMethod.PUT, emptyNamespace(vaultInitializationRequest),
					VaultInitializationResponseImpl.class);

			Assert.state(exchange.getBody() != null, "Initialization response must not be null");

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	}));
}
 
Example #4
Source File: AbstractTwitterInboundChannelAdapter.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	while (running.get()) {
		try {
			readStream(twitter.getRestTemplate());
		}
		catch (HttpStatusCodeException sce) {
			if (sce.getStatusCode() == HttpStatus.UNAUTHORIZED) {
				logger.error("Twitter authentication failed: " + sce.getMessage());
				running.set(false);
			}
			else if (sce.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
				waitRateLimitBackoff();
			}
			else {
				waitHttpErrorBackoff();
			}
		}
		catch (Exception e) {
			logger.warn("Exception while reading stream.", e);
			waitLinearBackoff();
		}
	}
}
 
Example #5
Source File: VaultKeyValueAccessor.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a read action within a callback that gets access to a session-bound
 * {@link RestOperations} object. {@link HttpStatusCodeException} with
 * {@link HttpStatus#NOT_FOUND} are translated to a {@literal null} response.
 * @param callback must not be {@literal null}.
 * @return can be {@literal null}.
 */
@Nullable
<T> T doRead(Function<RestOperations, ResponseEntity<T>> callback) {

	return this.vaultOperations.doWithSession((restOperations) -> {

		try {
			return callback.apply(restOperations).getBody();
		}
		catch (HttpStatusCodeException e) {

			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				return null;
			}

			throw VaultResponses.buildException(e, this.path);
		}
	});
}
 
Example #6
Source File: StandardBullhornData.java    From sdk-rest with MIT License 6 votes vote down vote up
/**
 * Makes the call to the resume parser. If parse fails this method will retry RESUME_PARSE_RETRY number of times.
 *
 * @param url
 * @param requestPayLoad
 * @param uriVariables
 * @return
 */
protected ParsedResume parseResume(String url, Object requestPayLoad, Map<String, String> uriVariables) {
    ParsedResume response = null;
    for (int tryNumber = 1; tryNumber <= RESUME_PARSE_RETRY; tryNumber++) {
        try {
            response = this.performPostResumeRequest(url, requestPayLoad, uriVariables);
            break;
        } catch (HttpStatusCodeException error) {
            response = handleResumeParseError(tryNumber, error);
        } catch (Exception e) {
            log.error("error", e);
        }
    }

    return response;
}
 
Example #7
Source File: VaultWrappingTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Nullable
private <T extends VaultResponseSupport<?>> T doUnwrap(VaultToken token,
		BiFunction<RestOperations, HttpEntity<?>, T> requestFunction) {

	return this.vaultOperations.doWithVault(restOperations -> {

		try {
			return requestFunction.apply(restOperations, new HttpEntity<>(VaultHttpHeaders.from(token)));
		}
		catch (HttpStatusCodeException e) {

			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				return null;
			}

			if (e.getStatusCode() == HttpStatus.BAD_REQUEST
					&& e.getResponseBodyAsString().contains("does not exist")) {
				return null;
			}

			throw VaultResponses.buildException(e, "sys/wrapping/unwrap");
		}
	});
}
 
Example #8
Source File: VaultPkiTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private <T> T requestCertificate(String roleName, String requestPath, Map<String, Object> request,
		Class<T> responseType) {

	request.put("format", "der");

	T response = this.vaultOperations.doWithSession(restOperations -> {

		try {
			return restOperations.postForObject(requestPath, request, responseType, this.path, roleName);
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e);
		}
	});

	Assert.state(response != null, "VaultCertificateResponse must not be null");

	return response;
}
 
Example #9
Source File: RestService.java    From code-examples with MIT License 6 votes vote down vote up
public String unknownRequest() {
    try {
        String url = "https://jsonplaceholder.typicode.com/404";
        return this.restTemplate.getForObject(url, String.class);
    } catch (HttpStatusCodeException ex) {
        // raw http status code e.g `404`
        System.out.println(ex.getRawStatusCode());
        // http status code e.g. `404 NOT_FOUND`
        System.out.println(ex.getStatusCode().toString());
        // get response body
        System.out.println(ex.getResponseBodyAsString());
        // get http headers
        HttpHeaders headers = ex.getResponseHeaders();
        System.out.println(headers.get("Content-Type"));
        System.out.println(headers.get("Server"));
    }

    return null;
}
 
Example #10
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void processStatusCodeException(HttpStatusCodeException e, ServiceCallResult res, URI uri) {
    setCode(e.getStatusCode(), res);
    String msg = null;
    try {
        if(MediaType.APPLICATION_JSON.includes(e.getResponseHeaders().getContentType())) {
            objectMapper.reader().withValueToUpdate(res).readValue(e.getResponseBodyAsString());
            msg = res.getMessage();
        }
    } catch (Exception ex) {
        log.error("Can not process status code exception message.", ex);
    }
    // in some cases msg may be null on success reading value, but anyway we need to make non null value manually
    if(msg == null) {
        msg = formatHttpException(e);
        res.setMessage(msg);
    }
    // we log message as debug because consumer code must log error too, but with high level,
    // when we log it as warn then error will cause to many duplicate lines in log
    log.warn("Fail to execute '{}' due to error: {}", uri, msg);
}
 
Example #11
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private <T> T postOrNullAction(UriComponentsBuilder ub, Object cmd, Class<T> responseType) {
    String url = ub.toUriString();
    try {
        ResponseEntity<T> entity = getSlow(() -> {
            HttpEntity<?> req = null;
            if(cmd != null) {
                req = wrapEntity(cmd);
            }
            return restTemplate.postForEntity(url, req, responseType);
        });
        return entity.getBody();
    } catch (HttpStatusCodeException e) {
        log.warn("Failed to execute POST on {}, due to {}", url, formatHttpException(e));
        if(e.getStatusCode().is4xxClientError()) {
            return null;
        }
        throw e;
    }
}
 
Example #12
Source File: Card.java    From iSCAU-Android with GNU General Public License v3.0 6 votes vote down vote up
@Background( id = UIHelper.CANCEL_FLAG )
void loadData(Object... params) {
    try{

        ArrayList<String> param = (ArrayList<String>)params[0];
        CardRecordModel.RecordList records;
        if( param == null){
            records = api.getToday(AppContext.userName, app.getEncodeCardPassword());
        }else{
            records = api.getHistory(AppContext.userName, app.getEncodeCardPassword(), param.get(0), param.get(1), page);
        }
        showSuccessResult(records);
    }catch (HttpStatusCodeException e){
        showErrorResult(ctx, e.getStatusCode().value());
    }
}
 
Example #13
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 6 votes vote down vote up
@Override
public RangerSecurityServicePolicies getSecurityServicePolicies(String serviceName, Long lastKnownVersion) {
    if (serviceName == null) {
        return null;
    }
    String servicePoliciesURL = MessageFormat.format(SERVICE_POLICIES, connection.getEndpoint().getAddress(), serviceName, lastKnownVersion);

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> entity = new HttpEntity<>(getHttpHeaders());

    try {
        ResponseEntity<RangerSecurityServicePolicies> result = restTemplate.exchange(servicePoliciesURL, HttpMethod.GET, entity, RangerSecurityServicePolicies.class);
        if (result.getStatusCode().value() == HttpStatus.OK.value()) {
            return result.getBody();
        } else if (result.getStatusCode().value() == HttpStatus.NOT_MODIFIED.value()) {
            log.debug("Policies list not modified since last known version {}", lastKnownVersion);
            return null;
        }
        return result.getBody();
    } catch (HttpStatusCodeException exception) {
        log.debug("Unable to fetch the security service policies for service = {} with last known version {}", serviceName, lastKnownVersion);
    }
    return null;
}
 
Example #14
Source File: LifecycleAwareSessionManagerIntegrationTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRevokeOnDisposal() {

	final LoginToken loginToken = createLoginToken();
	TokenAuthentication tokenAuthentication = new TokenAuthentication(loginToken);

	LifecycleAwareSessionManager sessionManager = new LifecycleAwareSessionManager(tokenAuthentication,
			this.taskScheduler, prepare().getRestTemplate());

	sessionManager.getSessionToken();
	sessionManager.destroy();

	prepare().getVaultOperations().doWithSession(restOperations -> {

		try {
			restOperations.getForEntity("auth/token/lookup/{token}", Map.class, loginToken.toCharArray());
			fail("Missing HttpStatusCodeException");
		}
		catch (HttpStatusCodeException e) {
			// Compatibility across Vault versions.
			assertThat(e.getStatusCode()).isIn(HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN);
		}

		return null;
	});
}
 
Example #15
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 6 votes vote down vote up
private RangerTagDef createRangerTagDef() {
    RangerTagDef rangerTagDef = buildRangerTagDef();
    String body = getBody(rangerTagDef);

    String createRangerTagDefURL = getRangerURL(SERVICE_TAGS_TAGDEF);

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> entity = new HttpEntity<>(body, getHttpHeaders());

    try {
        ResponseEntity<RangerTagDef> result = restTemplate.exchange(createRangerTagDefURL, HttpMethod.POST, entity, RangerTagDef.class);
        return result.getBody();
    } catch (HttpStatusCodeException exception) {
        log.debug("Unable to create a security tag");
    }
    return null;
}
 
Example #16
Source File: RangerSecurityServiceConnector.java    From egeria with Apache License 2.0 6 votes vote down vote up
public List<RangerServiceResource> getExistingResources() {
    String createAssociation = getRangerURL(SERVICE_TAGS_RESOURCES);

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> entity = new HttpEntity<>(getHttpHeaders());
    try {
        ResponseEntity<List<RangerServiceResource>> response =
                restTemplate.exchange(createAssociation, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RangerServiceResource>>() {
                });

        if (response.getBody() != null) {
            return response.getBody();
        }
    } catch (HttpStatusCodeException exception) {
        log.debug("Unable to fetch the resources");
    }

    return Collections.emptyList();
}
 
Example #17
Source File: StandardBullhornData.java    From sdk-rest with MIT License 6 votes vote down vote up
/**
 * @param uriVariables
 * @param tryNumber
 * @param error
 * @throws RestApiException if tryNumber >= API_RETRY.
 */
protected boolean handleHttpStatusCodeError(Map<String, String> uriVariables, int tryNumber, HttpStatusCodeException error) {
    boolean isTooManyRequestsError = false;
    if (error.getStatusCode() == HttpStatus.UNAUTHORIZED) {
        resetBhRestToken(uriVariables);
    } else if (error.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
        isTooManyRequestsError = true;
    }
    log.error(
            "HttpStatusCodeError making api call. Try number:" + tryNumber + " out of " + API_RETRY + ". Http status code: "
                    + error.getStatusCode() + ". Response body: " + error.getResponseBodyAsString(), error);
    if (tryNumber >= API_RETRY && !isTooManyRequestsError) {
        throw new RestApiException("HttpStatusCodeError making api call with url variables " + uriVariables.toString()
                + ". Http status code: " + error.getStatusCode().toString() + ". Response body: " + error == null ? ""
                : error.getResponseBodyAsString());
    }
    return isTooManyRequestsError;
}
 
Example #18
Source File: VaultKvAccessStrategySupport.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
/**
 * @param headers must not be {@literal null}.
 * @param backend secret backend mount path, must not be {@literal null}.
 * @param key key within the key-value secret backend, must not be {@literal null}.
 * @return
 */
@Override
public String getData(HttpHeaders headers, String backend, String key) {
	try {

		String urlTemplate = String.format("%s/v1/%s/%s", this.baseUrl, backend,
				getPath());

		ResponseEntity<VaultResponse> response = this.rest.exchange(urlTemplate,
				HttpMethod.GET, new HttpEntity<>(headers), VaultResponse.class, key);
		HttpStatus status = response.getStatusCode();
		if (status == HttpStatus.OK) {
			return extractDataFromBody(response.getBody());
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return null;
		}
		throw e;
	}
	return null;
}
 
Example #19
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private ServiceCallResult stopBasedAction(String id, StopContainerArg arg, String action) {
    Assert.notNull(id, "id is null");
    UriComponentsBuilder ub = getUrlContainer(id, action);
    int time = arg.getTimeBeforeKill();
    if (time > 0) {
        ub.queryParam("t", time);
    }
    URI uri = ub.build().toUri();
    try {
        ResponseEntity<String> res = getSlow(() -> restTemplate.postForEntity(uri, null, String.class));
        return DockerUtils.getServiceCallResult(res);
    } catch (HttpStatusCodeException e) {
        log.warn("In {}, can't \"{}\" container: {}, code: {}, message: {}", getId(), action, id, e.getStatusCode(), e.getResponseBodyAsString());
        ServiceCallResult callResult = new ServiceCallResult();
        processStatusCodeException(e, callResult, uri);
        return callResult;
    }
}
 
Example #20
Source File: AbstractServiceApiPlusListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 调用下游服务
 *
 * @param context
 * @return
 */
public ResponseEntity<String> callOrderService(DataFlowContext context, JSONObject paramIn) {

    context.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, "D");
    ResponseEntity responseEntity = null;
    if (paramIn == null || paramIn.isEmpty()) {
        paramIn = context.getReqJson();
    }
    String serviceUrl = ORDER_SERVICE_URL;
    HttpEntity<String> httpEntity = null;
    HttpHeaders header = new HttpHeaders();
    for (String key : context.getRequestCurrentHeaders().keySet()) {
        if (CommonConstant.HTTP_SERVICE.toLowerCase().equals(key.toLowerCase())) {
            continue;
        }
        header.add(key, context.getRequestCurrentHeaders().get(key));
    }
    try {
        httpEntity = new HttpEntity<String>(JSONObject.toJSONString(paramIn), header);
        responseEntity = restTemplate.exchange(serviceUrl, HttpMethod.POST, httpEntity, String.class);
    } catch (HttpStatusCodeException e) { //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
        responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
    }
    return responseEntity;
}
 
Example #21
Source File: ManifestCommands.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@ShellMethod(key = "manifest get", value = "Get the manifest for a release")
public Object getManifest(
		@ShellOption(help = "release name") @NotNull String releaseName,
		@ShellOption(help = "specific release version.", defaultValue = ShellOption.NULL) Integer releaseVersion) {
	String manifest;
	try {
		if (releaseVersion == null) {
			manifest = this.skipperClient.manifest(releaseName);
		}
		else {
			manifest = this.skipperClient.manifest(releaseName, releaseVersion);
		}
	}
	catch (HttpStatusCodeException e) {
		if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
			return "Release with name '" + releaseName + "' not found";
		}
		// if something else, rethrow
		throw e;
	}
	return manifest;
}
 
Example #22
Source File: WorkbasketDefinitionControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Test
void testImportWorkbasketWithDistributionTargetsNotInSystem() {
  TaskanaPagedModel<WorkbasketDefinitionRepresentationModel> wbList =
      executeExportRequestForDomain("DOMAIN_A").getBody();

  assertThat(wbList).isNotNull();
  WorkbasketDefinitionRepresentationModel w = wbList.getContent().iterator().next();
  w.setDistributionTargets(Collections.singleton("invalidWorkbasketId"));
  ThrowingCallable httpCall =
      () -> expectStatusWhenExecutingImportRequestOfWorkbaskets(HttpStatus.BAD_REQUEST, w);
  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(e -> (HttpClientErrorException) e)
      .extracting(HttpStatusCodeException::getStatusCode)
      .isEqualTo(HttpStatus.BAD_REQUEST);

  w.getWorkbasket().setKey("anotherNewKey");

  assertThatThrownBy(httpCall)
      .isInstanceOf(HttpClientErrorException.class)
      .extracting(e -> (HttpClientErrorException) e)
      .extracting(HttpStatusCodeException::getStatusCode)
      .isEqualTo(HttpStatus.BAD_REQUEST);
}
 
Example #23
Source File: ITTracingAsyncClientHttpRequestInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override protected void get(AsyncClientHttpRequestFactory client, String path,
  BiConsumer<Integer, Throwable> callback) {
  AsyncRestTemplate restTemplate = new AsyncRestTemplate(client);
  restTemplate.setInterceptors(Collections.singletonList(interceptor));
  restTemplate.getForEntity(url(path), String.class)
    .addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
      @Override public void onFailure(Throwable throwable) {
        if (throwable instanceof HttpStatusCodeException) {
          callback.accept(((HttpStatusCodeException) throwable).getRawStatusCode(), null);
        } else {
          callback.accept(null, throwable);
        }
      }

      @Override public void onSuccess(ResponseEntity<String> entity) {
        callback.accept(entity.getStatusCodeValue(), null);
      }
    });
}
 
Example #24
Source File: TestStandardBullhornApiRestFile.java    From sdk-rest with MIT License 6 votes vote down vote up
@Repeat(1)
@Test
public void testAddFileUsingFile() throws UnsupportedEncodingException, IOException {
	File file = getFile();
	FileParams params = ParamFactory.fileParams();
	try {
		FileWrapper fileWrapper = bullhornData.addFile(Candidate.class, testEntities.getCandidateId(), file, "portfolio", params);
		assertFileWrapperIncludingFileName(fileWrapper);

		FileApiResponse fileApiResponse = bullhornData.deleteFile(Candidate.class, testEntities.getCandidateId(),
				fileWrapper.getId());

		assertFileApiResponse(fileApiResponse, fileWrapper.getId());
	} catch (HttpStatusCodeException error) {
		assertTrue(StringUtils.equals("" + error.getStatusCode().value(), "500"));
	}

}
 
Example #25
Source File: ControllerIntegrationExceptionTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
  AppDTO dto = generateSampleDTOData();

  when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));

  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  } catch (HttpStatusCodeException e) {
    @SuppressWarnings("unchecked")
    Map<String, String> attr = gson.fromJson(e.getResponseBodyAsString(), Map.class);
    Assert.assertEquals("save failed", attr.get("message"));
  }
  App savedApp = appService.findOne(dto.getAppId());
  Assert.assertNull(savedApp);
}
 
Example #26
Source File: HealthApi.java    From edison-microservice with Apache License 2.0 6 votes vote down vote up
private static void getResource(final String url, final Optional<String> mediaType) {
    final HttpHeaders headers = new HttpHeaders();
    if (mediaType.isPresent()) {
        headers.setAccept(asList(parseMediaType(mediaType.get())));
    }
    try {
        final ResponseEntity<String> responseEntity = restTemplate.exchange(
                url,
                GET,
                new HttpEntity<>("parameters", headers), String.class
        );
        content = responseEntity.getBody();
        statusCode = responseEntity.getStatusCode();
    } catch (HttpStatusCodeException e) {
        content = e.getStatusText();
        statusCode = e.getStatusCode();
    }
}
 
Example #27
Source File: VaultTokenTemplate.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private <T extends VaultResponseSupport<?>> T writeAndReturn(String path, @Nullable Object body,
		Class<T> responseType) {

	Assert.hasText(path, "Path must not be empty");

	T response = this.vaultOperations.doWithSession(restOperations -> {
		try {
			ResponseEntity<T> exchange = restOperations.exchange(path, HttpMethod.POST,
					body == null ? HttpEntity.EMPTY : new HttpEntity<>(body), responseType);

			return exchange.getBody();
		}
		catch (HttpStatusCodeException e) {
			throw VaultResponses.buildException(e, path);
		}
	});

	Assert.state(response != null, "Response must not be null");

	return response;
}
 
Example #28
Source File: TestStandardBullhornApiRestFile.java    From sdk-rest with MIT License 6 votes vote down vote up
@Repeat(1)
@Test
public void testDeleteFile() throws UnsupportedEncodingException, IOException {
	MultipartFile file = getResume();
	FileParams params = ParamFactory.fileParams();
	try {
		FileWrapper fileWrapper = bullhornData.addFile(Candidate.class, testEntities.getCandidateId(), file, "portfolio", params);

		assertFileWrapper(fileWrapper);

		FileApiResponse fileApiResponse = bullhornData.deleteFile(Candidate.class, testEntities.getCandidateId(),
				fileWrapper.getId());

		assertFileApiResponse(fileApiResponse, fileWrapper.getId());
	} catch (HttpStatusCodeException error) {
		assertTrue(StringUtils.equals("" + error.getStatusCode().value(), "500"));
	}

}
 
Example #29
Source File: ConfigControllerIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryConfigForNoAppIdPlaceHolderWithPrivateNamespace() throws Exception {

  HttpStatusCodeException httpException = null;
  try {
    ResponseEntity<ApolloConfig> response = restTemplate
        .getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}", ApolloConfig.class,
            getHostUrl(), ConfigConsts.NO_APPID_PLACEHOLDER, someCluster, ConfigConsts.NAMESPACE_APPLICATION);
  } catch (HttpStatusCodeException ex) {
    httpException = ex;
  }

  assertEquals(HttpStatus.NOT_FOUND, httpException.getStatusCode());
}
 
Example #30
Source File: VaultTemplate.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T doWithSession(RestOperationsCallback<T> sessionCallback) {

	Assert.notNull(sessionCallback, "Session callback must not be null");

	try {
		return sessionCallback.doWithRestOperations(this.sessionTemplate);
	}
	catch (HttpStatusCodeException e) {
		throw VaultResponses.buildException(e);
	}
}