当前位置: 首页>>代码示例>>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;未经允许,请勿转载。