當前位置: 首頁>>代碼示例>>Java>>正文


Java ResourceAccessException類代碼示例

本文整理匯總了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);
}
 
開發者ID:alex-bretet,項目名稱:cloudstreetmarket.com,代碼行數:26,代碼來源:CommunityServiceImpl.java

示例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;
}
 
開發者ID:sdc1234,項目名稱:zhihu-spider,代碼行數:18,代碼來源:BaseApiController.java

示例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());
    }
}
 
開發者ID:pivio,項目名稱:pivio-client,代碼行數:23,代碼來源:Writer.java

示例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);
        }
    }
}
 
開發者ID:codeabovelab,項目名稱:haven-platform,代碼行數:22,代碼來源:Notifier.java

示例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.");
}
 
開發者ID:codeabovelab,項目名稱:haven-platform,代碼行數:22,代碼來源:SwarmProcesses.java

示例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);
}
 
開發者ID:ctripcorp,項目名稱:x-pipe,代碼行數:22,代碼來源:ClusterMetaModifiedNotifierTest.java

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

}
 
開發者ID:ctripcorp,項目名稱:x-pipe,代碼行數:21,代碼來源:RetryableRestOperationsTest.java

示例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;
}
 
開發者ID:Nephilim84,項目名稱:contestparser,代碼行數:26,代碼來源:ResourceServerTokenServicesConfiguration.java

示例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);
}
 
開發者ID:genome-nexus,項目名稱:genome-nexus,代碼行數:21,代碼來源:BaseExternalResourceFetcher.java

示例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);
}
 
開發者ID:genome-nexus,項目名稱:genome-nexus,代碼行數:17,代碼來源:CancerHotspotDataFetcher.java

示例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;
	    }
    });
}
 
開發者ID:marklogic-community,項目名稱:ml-app-deployer,代碼行數:22,代碼來源:ClusterManager.java

示例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);
}
 
開發者ID:sealuzh,項目名稱:PerformanceHat,代碼行數:24,代碼來源:RestClientImpl.java

示例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();
    }
}
 
開發者ID:bkielczewski,項目名稱:akanke,代碼行數:24,代碼來源:FacebookStatsServiceImpl.java

示例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());
    }
}
 
開發者ID:mechero,項目名稱:code-quality-game,代碼行數:29,代碼來源:SonarServerConfigurationServiceImpl.java


注:本文中的org.springframework.web.client.ResourceAccessException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。