本文整理匯總了Java中org.springframework.web.client.ResourceAccessException類的典型用法代碼示例。如果您正苦於以下問題:Java ResourceAccessException類的具體用法?Java ResourceAccessException怎麽用?Java ResourceAccessException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ResourceAccessException類屬於org.springframework.web.client包,在下文中一共展示了ResourceAccessException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testNoDataFlowServer
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Test
@DirtiesContext
public void testNoDataFlowServer() throws Exception{
String exceptionMessage = null;
final String ERROR_MESSAGE =
"I/O error on GET request for \"http://localhost:9393\": Connection refused; nested exception is java.net.ConnectException: Connection refused";
Mockito.doThrow(new ResourceAccessException(ERROR_MESSAGE))
.when(this.taskOperations).launch(Matchers.anyString(),
(Map<String,String>) Matchers.any(),
(List<String>) Matchers.any());
TaskLauncherTasklet taskLauncherTasklet = getTaskExecutionTasklet();
ChunkContext chunkContext = chunkContext();
try {
taskLauncherTasklet.execute(null, chunkContext);
}
catch (ResourceAccessException rae) {
exceptionMessage = rae.getMessage();
}
assertEquals(ERROR_MESSAGE, exceptionMessage);
}
開發者ID:spring-cloud-task-app-starters,項目名稱:composed-task-runner,代碼行數:21,代碼來源:TaskLauncherTaskletTests.java
示例2: loadUserByUsername
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findOne(username);
Authentication auth;
if(user != null){
return user;
}
SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext != null) {
auth = securityContext.getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return (User) principal;
}
}
}
//fallback
throw new ResourceAccessException("No found user for username: "+username);
}
示例3: defaultFallback
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
protected ResponseEntity<ResultDTO> defaultFallback(Throwable e) {
String errorMsg;
String code = "300";
if (e instanceof ZhihuOptException) {
errorMsg = e.getMessage();
} else if (e instanceof ResourceAccessException) {
errorMsg = "節點連接失敗";
code = "500";
} else {
errorMsg = "服務發生錯誤";
code = "500";
}
ResponseEntity<ResultDTO> resultDto = new ResponseEntity<ResultDTO>(
new ResultDTO().result(code).errorMsg(errorMsg), HttpStatus.OK);
log.error("**** 發生異常 ****", e);
return resultDto;
}
示例4: uploadToServer
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
private void uploadToServer(String json) {
if (configuration.hasOption(SWITCH_SERVICE_URL)) {
String serviceUrl = configuration.getParameter(SWITCH_SERVICE_URL);
log.verboseOutput("Uploading to " + serviceUrl + ": " + json, configuration.isVerbose());
RestTemplate rt = new RestTemplate();
rt.setErrorHandler(new RestCallErrorHandler());
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
try {
ResponseEntity<JsonNode> responseEntity = rt.exchange(serviceUrl, HttpMethod.POST, new HttpEntity<>(json, headers), JsonNode.class);
if (responseEntity.getStatusCode() != HttpStatus.CREATED) {
handleNonCreatedStatusCode(serviceUrl, responseEntity, json);
} else {
log.verboseOutput("Upload to " + serviceUrl + " successful.", configuration.isVerbose());
}
} catch (ResourceAccessException e) {
handleConnectionRefused(serviceUrl);
}
} else {
log.verboseOutput("Not uploading to any server since no '" + SWITCH_SERVICE_URL + "' parameter was specified.", configuration.isVerbose());
}
}
示例5: send
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
private void send() {
try {
NotifierData data = dataProvider.getData();
HttpHeaders headers = new HttpHeaders();
if(secret != null) {
headers.set(NotifierData.HEADER, secret);
}
RequestEntity<NotifierData> req = new RequestEntity<>(data, headers, HttpMethod.POST, url);
ResponseEntity<String> resp = restTemplate.exchange(req, String.class);
if(log.isDebugEnabled()) {
log.debug("Send data {} to {}, with result: {}", objectMapper.writeValueAsString(data), url, resp.getStatusCode());
}
} catch (Exception e) {
if(e instanceof ResourceAccessException) {
// we reduce stack trace of some errors
log.error("Can not send to {}, due to error: {}", url, e.toString());
} else {
log.error("Can not send to {}", url, e);
}
}
}
示例6: waitProcessStart
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
private void waitProcessStart() throws Exception {
RestTemplate rt = new RestTemplate();
URI url = new URI("http", null, host, port, "/version", null, null);
final int tries = 4;
final int maxWaitOnStart = config.getMaxWaitOnStart();
final long sleepTime = (maxWaitOnStart * 1000L) / (long)tries;
int i = tries;
while(i > 0) {
try {
String res = rt.getForObject(url, String.class);
if(res != null) {
return;
}
} catch(ResourceAccessException e) {
//wait for some tome before next trie
Thread.sleep(sleepTime);
}
i--;
}
throw new Exception("Process of '" + getCluster() + "' cluster not response at " + url + " in " + maxWaitOnStart + " seconds.");
}
示例7: initMockData
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Before
public void initMockData() {
dcName = "mockedDc";
mockedDcTbl = new DcTbl().setDcName(dcName);
clusterName = "mockedClusterName";
mockedClusterMeta = new ClusterMeta().setId(clusterName).setActiveDc(dcName);
when(config.getConsoleNotifyRetryTimes()).thenReturn(retryTimes - 1);
when(config.getConsoleNotifyRetryInterval()).thenReturn(10);
when(config.getConsoleNotifyThreads()).thenReturn(20);
notifier.postConstruct();
when(metaServerConsoleServiceManagerWrapper.get(dcName)).thenReturn(mockedMetaServerConsoleService);
doThrow(new ResourceAccessException("test")).when(mockedMetaServerConsoleService).clusterAdded(clusterName,
mockedClusterMeta);
doThrow(new ResourceAccessException("test")).when(mockedMetaServerConsoleService).clusterDeleted(clusterName);
doThrow(new ResourceAccessException("test")).when(mockedMetaServerConsoleService).clusterModified(clusterName,
mockedClusterMeta);
when(clusterMetaService.getClusterMeta(dcName, clusterName)).thenReturn(mockedClusterMeta);
}
示例8: retryableRestOperationsFailTest
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Test
public void retryableRestOperationsFailTest() {
ctx.close();
int retryTimes = 10;
RetryPolicyFactory mockedRetryPolicyFactory = Mockito.mock(RetryPolicyFactory.class);
RetryPolicy mockedRetryPolicy = Mockito.mock(RetryPolicy.class);
when(mockedRetryPolicyFactory.create()).thenReturn(mockedRetryPolicy);
when(mockedRetryPolicy.retry(any(Throwable.class))).thenReturn(true);
RestOperations restOperations = RestTemplateFactory.createCommonsHttpRestTemplate(10, 100, 5000, 5000,
retryTimes, mockedRetryPolicyFactory);
try {
restOperations.getForObject(generateRequestURL("/test"), String.class);
} catch (Exception e) {
verify(mockedRetryPolicy, times(retryTimes)).retry(any(Throwable.class));
// check the type of original exception
assertTrue(e instanceof ResourceAccessException);
}
}
示例9: jwtTokenEnhancer
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
String keyValue = this.resource.getJwt().getKeyValue();
if (!StringUtils.hasText(keyValue)) {
try {
keyValue = getKeyFromServer();
}
catch (ResourceAccessException ex) {
logger.warn("Failed to fetch token key (you may need to refresh "
+ "when the auth server is back)");
}
}
if (StringUtils.hasText(keyValue) && !keyValue.startsWith("-----BEGIN")) {
converter.setSigningKey(keyValue);
}
if (keyValue != null) {
converter.setVerifierKey(keyValue);
}
AnnotationAwareOrderComparator.sort(this.configurers);
for (JwtAccessTokenConverterConfigurer configurer : this.configurers) {
configurer.configure(converter);
}
return converter;
}
示例10: fetchStringValue
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
/**
* Base implementation for a single parameter query.
* This method should be overridden if the query has more than one parameter.
*/
@Override
public String fetchStringValue(Map<String, String> queryParams)
throws HttpClientErrorException, ResourceAccessException
{
// get the value of the main (single) parameter
String paramValue = queryParams.get(this.mainQueryParam);
String uri = this.URI;
// replace the placeholder with the value in the uri
if (paramValue != null && paramValue.length() > 0) {
uri = uri.replace(this.placeholder, paramValue);
}
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(uri, String.class);
}
示例11: fetchStringValue
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Override
public String fetchStringValue(Map<String, String> queryParams)
throws HttpClientErrorException, ResourceAccessException
{
String variables = queryParams.get(MAIN_QUERY_PARAM);
String uri = this.getHotspotsUrl();
if (variables != null && variables.length() > 0)
{
// TODO partially hardcoded API URI
uri += "/byTranscript/" + variables;
}
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(uri, String.class);
}
示例12: modifyLocalCluster
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
public void modifyLocalCluster(final String payload, AdminManager adminManager) {
adminManager.invokeActionRequiringRestart(new ActionRequiringRestart() {
@Override
public boolean execute() {
try {
putPayload(manageClient, "/manage/v2/properties", payload);
} catch (ResourceAccessException rae) {
/**
* This is odd. Plenty of other Manage endpoints cause ML to restart, but this one seems to trigger
* the restart before the PUT finishes. But - the PUT still seems to update the cluster properties
* correctly. So we catch this error and figure that we can wait for ML to restart like it normally
* would.
*/
if (logger.isInfoEnabled()) {
logger.info("Ignoring somewhat expected error while updating local cluster properties: " + rae.getMessage());
}
}
return true;
}
});
}
示例13: handleErrors
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
private void handleErrors(final RestClientException exception) {
// handle 404 NOT FOUND error
if (exception instanceof ResourceAccessException) {
throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage());
}
else if (exception instanceof HttpStatusCodeException) {
final HttpStatusCodeException httpException = (HttpStatusCodeException) exception;
// handle 404 NOT FOUND error
if (httpException.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
throw new RequestException(ErrorType.FEEDBACK_HANDLER_NOT_AVAILABLE, exception.getMessage());
}
// handle other errors
final ObjectMapper mapper = new ObjectMapper();
try {
final RestRequestErrorDto error = mapper.readValue(httpException.getResponseBodyAsString(), RestRequestErrorDto.class);
throw new RequestException(error.getType(), error.getMessage());
}
catch (final IOException e) {}
}
throw new RuntimeException(READ_SERVER_ERROR_EXCEPTION, exception);
}
示例14: get
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
@Override
@Cacheable("facebook-stats")
public FacebookStats get(String documentId) {
LOGGER.debug("Getting facebook stats for document id={}", documentId);
checkArgument(documentId != null, "Document id cannot be null");
try {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.put("fields", Collections.singletonList("share"));
params.put("id", Collections.singletonList(baseUrl + documentId));
JsonNode ogObjectNode = facebookTemplate.fetchObject("/", JsonNode.class, params);
JsonNode shareNode = ogObjectNode.get("share");
if (shareNode == null) {
return new FacebookStats();
} else {
int commentCount = (shareNode.has(COMMENT_COUNT)) ? shareNode.get(COMMENT_COUNT).asInt() : 0;
int shareCount = (shareNode.has(SHARE_COUNT)) ? shareNode.get(SHARE_COUNT).asInt() : 0;
return new FacebookStats(commentCount, shareCount);
}
} catch (SocialException | ResourceAccessException e) {
LOGGER.warn("Ignoring exception while fetching stats for document id={} from Facebook", documentId, e);
return new FacebookStats();
}
}
示例15: checkServerDetails
import org.springframework.web.client.ResourceAccessException; //導入依賴的package包/類
/**
* Checks the current status of the server and the version running on it.
* It also detects if the server is not reachable.
*
* @param config The configuration for Sonar Server
* @return the response from server
*/
@Override
public SonarServerStatus checkServerDetails(final SonarServerConfiguration config) {
log.info("Trying to reach Sonar server at " + config.getUrl() + API_SYSTEM_STATUS);
try {
final HttpHeaders authHeaders = ApiHttpUtils.getHeaders(config.getUser(), config.getPassword());
HttpEntity<String> request = new HttpEntity<>(authHeaders);
final ResponseEntity<SonarServerStatus> response = restTemplate
.exchange("http://" + config.getUrl() + API_SYSTEM_STATUS,
HttpMethod.GET, request, SonarServerStatus.class);
log.info("Response received from server: " + response.getBody());
return response.getBody();
} catch (final HttpClientErrorException clientErrorException) {
if (clientErrorException.getStatusCode() == HttpStatus.UNAUTHORIZED) {
return new SonarServerStatus(SonarServerStatus.Key.UNAUTHORIZED);
} else {
return new SonarServerStatus(SonarServerStatus.Key.UNKNOWN_ERROR, clientErrorException.getMessage());
}
} catch (final ResourceAccessException resourceAccessException) {
return new SonarServerStatus(SonarServerStatus.Key.CONNECTION_ERROR, resourceAccessException.getMessage());
}
}