org.springframework.test.context.jdbc.Sql#org.springframework.web.client.HttpStatusCodeException源码实例Demo

下面列出了org.springframework.test.context.jdbc.Sql#org.springframework.web.client.HttpStatusCodeException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


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;
    }
}
 

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);
}
 
源代码3 项目: code-examples   文件: RestService.java

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;
}
 
源代码4 项目: iSCAU-Android   文件: Card.java

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

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

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

@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;
}
 

@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;
	});
}
 

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;
}
 

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();
}
 
源代码11 项目: sdk-rest   文件: StandardBullhornData.java

/**
 * @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;
}
 

/**
 * 调用下游服务
 *
 * @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;
}
 

@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;
}
 

@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);
}
 

@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);
      }
    });
}
 

@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"));
	}

}
 
源代码17 项目: edison-microservice   文件: HealthApi.java

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();
    }
}
 
源代码18 项目: spring-data-dev-tools   文件: Jira.java

@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());
	}
}
 
源代码19 项目: spring-vault   文件: VaultTokenTemplate.java

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;
}
 

@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);
}
 
源代码21 项目: haven-platform   文件: DockerServiceImpl.java

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;
    }
}
 

/**
 * @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;
}
 

@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"));
	}

}
 
源代码24 项目: sdk-rest   文件: StandardBullhornData.java

/**
 * 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;
}
 
源代码25 项目: spring-vault   文件: VaultSysTemplate.java

@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);
		}
	}));
}
 

/**
 * 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);
		}
	});
}
 

@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");
		}
	});
}
 
源代码28 项目: spring-vault   文件: VaultPkiTemplate.java

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;
}
 

private String request(RestTemplate template) {

		// Uninitialized and sealed can cause status 500
		try {
			ResponseEntity<String> responseEntity = template.exchange(this.url, HttpMethod.GET, null, String.class);
			return responseEntity.getBody();
		}
		catch (HttpStatusCodeException e) {
			return e.getResponseBodyAsString();
		}
	}
 

@Override
public void handleError(ClientHttpResponse response) throws IOException {
    try {
        errorHandler.handleError(response);
    } catch (RestClientException e) {
        if (e instanceof HttpStatusCodeException) {
            HttpStatusCodeException ce = (HttpStatusCodeException) e;
            log.error("Echo request with error code: {}, msg:{}, body:{}", ce.getStatusCode().value(), ce.getMessage(), ce.getResponseBodyAsString());
            throw new EchoException(ce.getStatusCode().value(), ce.getMessage(), ce.getResponseBodyAsString());
        }
        throw new EchoException(ErrorCode.VENDOR_REQUEST_ERROR, e.getMessage());
    }
}