org.springframework.web.client.ResourceAccessException Java Examples

The following examples show how to use org.springframework.web.client.ResourceAccessException. 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: HttpFileTransferImplTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure can't get a file if the output location is a directory.
 *
 * @throws GenieException On Error
 * @throws IOException    On Error
 */
@Test(expected = ResourceAccessException.class)
public void cantGetWithDirectoryAsOutput() throws GenieException, IOException {
    this.server
        .expect(MockRestRequestMatchers.requestTo(TEST_URL))
        .andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
        .andRespond(
            MockRestResponseCreators
                .withSuccess("junk".getBytes(Charset.forName("UTF-8")), MediaType.APPLICATION_OCTET_STREAM)
        );
    try {
        this.httpFileTransfer.getFile(TEST_URL, this.temporaryFolder.getRoot().getCanonicalPath());
    } finally {
        Mockito
            .verify(this.registry, Mockito.times(1))
            .timer(
                HttpFileTransferImpl.DOWNLOAD_TIMER_NAME,
                MetricsUtils.newFailureTagsSetForException(new ResourceAccessException("test"))
            );
        Mockito
            .verify(this.downloadTimer, Mockito.times(1))
            .record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS));
    }
}
 
Example #2
Source File: AbstractZosmfService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Method handles exception from REST call to z/OSMF into internal exception. It convert original exception into
 * custom one with better messages and types for subsequent treatment.
 *
 * @param url URL of invoked REST endpoint
 * @param re original exception
 * @return translated exception
 */
protected RuntimeException handleExceptionOnCall(String url, RuntimeException re) {
    if (re instanceof ResourceAccessException) {
        apimlLog.log("org.zowe.apiml.security.serviceUnavailable", url, re.getMessage());
        return new ServiceNotAccessibleException("Could not get an access to z/OSMF service.");
    }

    if (re instanceof HttpClientErrorException.Unauthorized) {
        return new BadCredentialsException("Username or password are invalid.");
    }

    if (re instanceof RestClientException) {
        apimlLog.log("org.zowe.apiml.security.generic", re.getMessage(), url);
        return new AuthenticationServiceException("A failure occurred when authenticating.", re);
    }

    return re;
}
 
Example #3
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldThrowNewExceptionIfResourceAccessException() {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenThrow(ResourceAccessException.class);
    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(ServiceNotAccessibleException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not ServiceNotAccessibleException");
    assertEquals("Could not get an access to z/OSMF service.", exception.getMessage());
}
 
Example #4
Source File: SlackNotificationController.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/dashboards/{name}/notifications",
    method = GET,
    produces = APPLICATION_JSON_VALUE)
public ResponseEntity<?> getWebSocket(final @PathVariable("name") String name) {
    final DashboardDTO dashboard = dashboardService.getDashboard(name);

    if (dashboard == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Dashboard not found");
    }

    SlackDTO notification;
    try {
        notification = slackService.getWebSocket(
            dashboard.getSlackTeam(),
            dashboard.getSlackToken());
    } catch (ResourceAccessException e) {
        return ResponseEntity
            .status(HttpStatus.FAILED_DEPENDENCY)
            .body("Error getting slack web socket: " + e.getMessage());
    }

    return notification.isOk()
        ? ResponseEntity.ok(notification.getUrl())
        : ResponseEntity.status(HttpStatus.CONFLICT).body(notification.getError());
}
 
Example #5
Source File: GatewaySecurityService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies JWT token validity and returns JWT token data
 *
 * @param token JWT token to be validated
 * @return JWT token data as {@link QueryResponse}
 */
public QueryResponse query(String token) {
    GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties();
    String uri = String.format("%s://%s%s", gatewayConfigProperties.getScheme(),
        gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayQueryEndpoint());
    String cookie = String.format("%s=%s", authConfigurationProperties.getCookieProperties().getCookieName(), token);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.COOKIE, cookie);

    try {
        ResponseEntity<QueryResponse> response = restTemplate.exchange(
            uri,
            HttpMethod.GET,
            new HttpEntity<>(headers),
            QueryResponse.class);

        return response.getBody();
    } catch (HttpClientErrorException | ResourceAccessException | HttpServerErrorException e) {
        responseHandler.handleBadResponse(e, ErrorType.TOKEN_NOT_VALID,
            "Can not access Gateway service. Uri '{}' returned: {}", uri, e.getMessage());
    }
    return null;
}
 
Example #6
Source File: GroupService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
   * list groupStatus Of each node of NodeList
   * @param nodeIdList
   * @param groupIdList
   * @return GroupStatusInfo
   */
  public List<RspGroupStatus> listGroupStatus(List<String> nodeIdList, List<Integer> groupIdList) {
      List<RspGroupStatus> resList = new ArrayList<>(nodeIdList.size());
for (String nodeId : nodeIdList) {
	// get front
	TbFront tbFront = frontService.getByNodeId(nodeId);
	if (tbFront == null) {
		log.error("fail getGroupStatus node front not exists.");
		throw new NodeMgrException(ConstantCode.NODE_NOT_EXISTS);
	}
          Map<String, String> statusMap = new HashMap<>();
          try{
          	statusMap = getGroupStatus(tbFront, groupIdList);
	} catch (NodeMgrException | ResourceAccessException e) {
		log.error("fail getGroupStatus in frontId:{}, exception:{}",
				tbFront.getFrontId(), e.getMessage());
		// request front fail
		statusMap.put(nodeId, "FAIL");
	}
          RspGroupStatus rspGroupStatus = new RspGroupStatus(nodeId, statusMap);
          resList.add(rspGroupStatus);
      }
      return resList;
  }
 
Example #7
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReLoginIfRenewalFails() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenThrow(new ResourceAccessException("Connection refused"));

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication, times(2)).login();
}
 
Example #8
Source File: LifecycleAwareSessionManagerUnitTests.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRetainTokenAfterRenewalFailure() {

	when(this.clientAuthentication.login()).thenReturn(
			LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)),
			LoginToken.renewable("bar".toCharArray(), Duration.ofSeconds(5)));
	when(this.restOperations.postForObject(anyString(), any(), eq(VaultResponse.class)))
			.thenThrow(new ResourceAccessException("Connection refused"));
	this.sessionManager.setLeaseStrategy(LeaseStrategy.retainOnError());

	ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
	this.sessionManager.getSessionToken();
	verify(this.taskScheduler).schedule(runnableCaptor.capture(), any(Trigger.class));
	runnableCaptor.getValue().run();

	assertThat(this.sessionManager.getSessionToken())
			.isEqualTo(LoginToken.renewable("login".toCharArray(), Duration.ofSeconds(5)));

	verify(this.clientAuthentication).login();
}
 
Example #9
Source File: Notifier.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #10
Source File: SwarmProcesses.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
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.");
}
 
Example #11
Source File: DefaultKeeperManager.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
protected void doCheckShard(String clusterId, ShardMeta shardMeta) {
	String shardId = shardMeta.getId();
	List<KeeperMeta> allKeepers = shardMeta.getKeepers();
	List<KeeperMeta> aliveKeepers = currentMetaManager.getSurviveKeepers(clusterId, shardId);
	List<KeeperMeta> deadKeepers = getDeadKeepers(allKeepers, aliveKeepers);

	if (deadKeepers.size() > 0) {
		logger.info("[doCheck][dead keepers]{}", deadKeepers);
	}
	for (KeeperMeta deadKeeper : deadKeepers) {
		try {
			keeperStateController.addKeeper(new KeeperTransMeta(clusterId, shardId, deadKeeper));
		} catch (ResourceAccessException e) {
			logger.error(String.format("cluster:%s,shard:%s, keeper:%s, error:%s", clusterId, shardId,
					deadKeeper, e.getMessage()));
		} catch (Throwable th) {
			logger.error("[doCheck]", th);
		}
	}
}
 
Example #12
Source File: ClusterMetaModifiedNotifierTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #13
Source File: RetryableRestOperationsTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@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);
	}

}
 
Example #14
Source File: AboutControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testAboutWithMissingSkipper() throws Exception {

	reset(this.skipperClient);

	Mockito.when(this.skipperClient.info()).thenThrow(new ResourceAccessException("Skipper Not There"));

	ResultActions result = mockMvc.perform(get("/about").accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
	result.andExpect(jsonPath("$.featureInfo.analyticsEnabled", is(true)))
			.andExpect(jsonPath("$.versionInfo.implementation.name", is("${info.app.name}")))
			.andExpect(jsonPath("$.versionInfo.implementation.version", is("1.2.3.IMPLEMENTATION.TEST")))
			.andExpect(jsonPath("$.versionInfo.core.name", is("Spring Cloud Data Flow Core")))
			.andExpect(jsonPath("$.versionInfo.core.version", is("1.2.3.CORE.TEST")))
			.andExpect(jsonPath("$.versionInfo.dashboard.name", is("Spring Cloud Dataflow UI")))
			.andExpect(jsonPath("$.versionInfo.dashboard.version", is("1.2.3.UI.TEST")))
			.andExpect(jsonPath("$.versionInfo.shell.name", is("Spring Cloud Data Flow Shell Test")))
			.andExpect(jsonPath("$.versionInfo.shell.url", is("https://repo.spring.io/libs-milestone/org/springframework/cloud/spring-cloud-dataflow-shell/1.3.0.BUILD-SNAPSHOT/spring-cloud-dataflow-shell-1.3.0.BUILD-SNAPSHOT.jsdfasdf")))
			.andExpect(jsonPath("$.versionInfo.shell.version", is("1.2.3.SHELL.TEST")))
			.andExpect(jsonPath("$.versionInfo.shell.checksumSha1", is("ABCDEFG")))
			.andExpect(jsonPath("$.versionInfo.shell.checksumSha256").doesNotExist())
			.andExpect(jsonPath("$.securityInfo.authenticationEnabled", is(false)))
			.andExpect(jsonPath("$.securityInfo.authenticated", is(false)))
			.andExpect(jsonPath("$.securityInfo.username", isEmptyOrNullString()))
			.andExpect(jsonPath("$.runtimeEnvironment.appDeployer.deployerName", isEmptyOrNullString())); // Connection to Skipper is lost!
}
 
Example #15
Source File: CommunityServiceImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: SonarServerConfigurationServiceImpl.java    From code-quality-game with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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.getToken());
        HttpEntity<String> request = new HttpEntity<>(authHeaders);
        final ResponseEntity<SonarServerStatus> response = restTemplate
                .exchange(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) {
        log.error(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) {
        log.error(resourceAccessException);
        return new SonarServerStatus(SonarServerStatus.Key.CONNECTION_ERROR, resourceAccessException.getMessage());
    }
}
 
Example #17
Source File: PortalWSManagerImpl.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private String get(String url, boolean isAdmin) {
    if (this.restClient == null) {
        return StringUtils.EMPTY;
    }
    
    try {
        String jsonUrl =  url + "?isAdmin=" + isAdmin;
        LOGGER.info("Will try to fetch URL [" + jsonUrl + "]");
        return restClient.getJsonRequest(jsonUrl, true);
    } catch (JsonSyntaxException ex) {
        return StringUtils.EMPTY;
    } catch (IllegalArgumentException iae) {
        return StringUtils.EMPTY;
    } catch (ResourceAccessException rae) {
        return StringUtils.EMPTY;
    }
}
 
Example #18
Source File: ConsulBinderTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Return the most recent payload message a consumer received.
 * @param port http port for consumer
 * @return the most recent payload message a consumer received; may be {@code null}
 */
private String getConsumerMessagePayload(int port) {
	try {
		return this.restTemplate.getForObject(
				String.format("http://localhost:%d/message-payload", port),
				String.class);
	}
	catch (ResourceAccessException e) {
		logger.debug("getConsumerMessagePayload", e);
		return null;
	}
}
 
Example #19
Source File: MarketplaceServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Object> searchPlugins(final String type, final String keywords, final boolean showIncompatible,
                                         final long offset, final long limit)
    throws MarketplaceException {

    validate();
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .path(Paths.PLUGIN_SEARCH)
        .queryParam(Constants.PARAM_VERSION, version)
        .queryParam(Constants.PARAM_EDITION, edition)
        .queryParam(Constants.PARAM_SHOW_PENDING, showPending)
        .queryParam(Constants.PARAM_SHOW_INCOMPATIBLE, showIncompatible)
        .queryParam(Constants.PARAM_OFFSET, offset)
        .queryParam(Constants.PARAM_LIMIT, limit);

    if (StringUtils.isNotEmpty(type)) {
        builder.queryParam(Constants.PARAM_TYPE, type);
    }

    if (StringUtils.isNotEmpty(keywords)) {
        builder.queryParam(Constants.PARAM_KEYWORDS, keywords);
    }

    HttpEntity<Void> request = new HttpEntity<>(null, httpHeaders);

    try {
        ResponseEntity<Map<String, Object>> response =
            restTemplate.exchange(builder.build().toString(), HttpMethod.GET, request,
                new ParameterizedTypeReference<Map<String, Object>>() {});
        return response.getBody();
    } catch (ResourceAccessException e) {
        throw new MarketplaceUnreachableException(url, e);
    }
}
 
Example #20
Source File: ConsulBinderTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
/**
 * Return {@code true} if the producer made use of a custom partition selector.
 * @param port http port for producer
 * @return true if the producer used a custom partition selector
 */
private boolean partitionSelectorUsed(int port) {
	try {
		return this.restTemplate.getForObject(
				String.format("http://localhost:%d/partition-strategy-invoked", port),
				Boolean.class);
	}
	catch (ResourceAccessException e) {
		logger.debug("partitionSelectorUsed", e);
		return false;
	}
}
 
Example #21
Source File: GroupService.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
   * batch start group.
   *
   * @param req
   */
  public List<RspOperateResult> batchStartGroup(ReqBatchStartGroup req) {
      log.debug("start batchStartGroup:{}", req);
      Integer groupId = req.getGenerateGroupId();
      // check id
      checkGroupId(groupId);
      List<String> nodeIdList = req.getNodeList();
List<RspOperateResult> resOperateList = new ArrayList<>(nodeIdList.size());
for (String nodeId : nodeIdList) {
          // get front
          TbFront tbFront = frontService.getByNodeId(nodeId);
          if (tbFront == null) {
              log.error("fail batchStartGroup node not exists.");
              throw new NodeMgrException(ConstantCode.NODE_NOT_EXISTS);
          }
	// record generate result
	RspOperateResult operateResult = new RspOperateResult(tbFront.getFrontId(),
			OperateStatus.SUCCESS.getValue());
          // request front to start
          try{
          	frontInterface.operateGroup(tbFront.getFrontIp(), tbFront.getFrontPort(), groupId,
				OPERATE_START_GROUP);
		resOperateList.add(operateResult);
	} catch (NodeMgrException | ResourceAccessException e) {
		log.error("fail startGroup in frontId:{}, exception:{}",
				tbFront.getFrontId(), e.getMessage());
		operateResult.setCode(OperateStatus.FAIL.getValue());
		resOperateList.add(operateResult);
	}
      }
      // refresh group status
      resetGroupList();
      log.debug("end batchStartGroup.");
      return resOperateList;
  }
 
Example #22
Source File: GroupService.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
   * generate group.
   *
   * @param req info
   * @return
   */
  public List<RspOperateResult> generateGroup(ReqGenerateGroup req) {
      Integer generateGroupId = req.getGenerateGroupId();
      if (checkGroupIdExisted(generateGroupId)) {
          throw new NodeMgrException(ConstantCode.GROUP_ID_EXISTS);
      }
      List<String> nodeIdList = req.getNodeList();
List<RspOperateResult> resOperateList = new ArrayList<>(nodeIdList.size());
      for (String nodeId : nodeIdList) {
          // get front
          TbFront tbFront = frontService.getByNodeId(nodeId);
          if (tbFront == null) {
              log.error("fail generateGroup node front not exists.");
              throw new NodeMgrException(ConstantCode.NODE_NOT_EXISTS);
          }
	// record generate result
	RspOperateResult operateResult = new RspOperateResult(tbFront.getFrontId(),
			OperateStatus.SUCCESS.getValue());
          // request front to generate
          GenerateGroupInfo generateGroupInfo = new GenerateGroupInfo();
          BeanUtils.copyProperties(req, generateGroupInfo);
          try {
          	frontInterface.generateGroup(tbFront.getFrontIp(), tbFront.getFrontPort(),
				generateGroupInfo);
		resOperateList.add(operateResult);
	} catch (NodeMgrException | ResourceAccessException e) {
		log.error("fail generateGroup in frontId:{}, exception:{}",
				tbFront.getFrontId(), e.getMessage());
		// request front fail
		operateResult.setCode(OperateStatus.FAIL.getValue());
		resOperateList.add(operateResult);
	}
      }
      // save group, saved as invalid status until start
      TbGroup tbGroup = saveGroup(generateGroupId, req.getNodeList().size(),
              req.getDescription(), GroupType.MANUAL.getValue(), GroupStatus.MAINTAINING.getValue(),
              req.getTimestamp(), req.getNodeList());
      return resOperateList;
  }
 
Example #23
Source File: X509ApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResourceAccessException.class)
public void testUnauthenticatedHello() throws Exception {
    ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("/hi",
            String.class);
    assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(httpsEntity.getBody()).containsIgnoringCase("hello, world");
}
 
Example #24
Source File: CommunityServiceImplTest.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected= ResourceAccessException.class)
public void loadUserByUsername_throwsResourceAccessException(){
	when(userRepository.findOne(USER_A_NAME)).thenReturn(null);
	when(securityContext.getAuthentication()).thenReturn(authentication);
	when(authentication.getPrincipal()).thenReturn(null);
	
	communityServiceImpl.loadUserByUsername(USER_A_NAME);
	verify(securityContext, times(1)).getAuthentication();
	verify(authentication, times(1)).getPrincipal();
}
 
Example #25
Source File: RestTemplateFakeReactiveHttpClient.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ReactiveHttpResponse> executeRequest(ReactiveHttpRequest request) {

  Mono<Object> bodyMono;
  if (request.body() instanceof Mono) {
    bodyMono = ((Mono<Object>) request.body());
  } else if (request.body() instanceof Flux) {
    bodyMono = ((Flux) request.body()).collectList();
  } else {
    bodyMono = Mono.just(request.body());
  }
  bodyMono = bodyMono.switchIfEmpty(Mono.just(new byte[0]));

  return bodyMono.<ReactiveHttpResponse>flatMap(body -> {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(request.headers());
    if (acceptGzip) {
      headers.add("Accept-Encoding", "gzip");
    }

    ResponseEntity response =
            restTemplate.exchange(request.uri().toString(), HttpMethod.valueOf(request.method()),
                    new HttpEntity<>(body, headers), responseType());

    return Mono.just(new FakeReactiveHttpResponse(response, returnPublisherType));
  })
          .onErrorMap(ex -> ex instanceof ResourceAccessException
                              && ex.getCause() instanceof SocketTimeoutException,
                  ReadTimeoutException::new)
          .onErrorResume(HttpStatusCodeException.class,
                  ex -> Mono.just(new ErrorReactiveHttpResponse(ex)));
}
 
Example #26
Source File: TaskLauncherTaskletTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testNoDataFlowServer() {
	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(ArgumentMatchers.anyString(),
			ArgumentMatchers.any(),
			ArgumentMatchers.any(), ArgumentMatchers.any());
	TaskLauncherTasklet taskLauncherTasklet = getTaskExecutionTasklet();
	ChunkContext chunkContext = chunkContext();
	Throwable exception = assertThrows(ResourceAccessException.class,
			() -> execute(taskLauncherTasklet, null, chunkContext));
	Assertions.assertThat(exception.getMessage()).isEqualTo(ERROR_MESSAGE);
}
 
Example #27
Source File: RestOperationsRetryPolicy.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retry(Throwable e) {
    if (e instanceof ResourceAccessException) {
        return true;
    }
    if (e instanceof HttpServerErrorException) {
        HttpStatus statusCode = ((HttpServerErrorException) e).getStatusCode();
        if (statusCode == HttpStatus.BAD_GATEWAY) {
            return true;
        }
    }
    return false;
}
 
Example #28
Source File: MetaNotifyRetryPolicy.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retry(Throwable e) {
	if(e instanceof ResourceAccessException || e instanceof HttpServerErrorException || e instanceof TimeoutException) {
		return true;
	}
	return false;
}
 
Example #29
Source File: GatewaySecurityService.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Logs into the gateway with username and password, and retrieves valid JWT token
 *
 * @param username Username
 * @param password Password
 * @return Valid JWT token for the supplied credentials
 */
public Optional<String> login(String username, String password) {
    GatewayConfigProperties gatewayConfigProperties = gatewayClient.getGatewayConfigProperties();
    String uri = String.format("%s://%s%s", gatewayConfigProperties.getScheme(),
        gatewayConfigProperties.getHostname(), authConfigurationProperties.getGatewayLoginEndpoint());

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode loginRequest = mapper.createObjectNode();
    loginRequest.put("username", username);
    loginRequest.put("password", password);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

    try {
        ResponseEntity<String> response = restTemplate.exchange(
            uri,
            HttpMethod.POST,
            new HttpEntity<>(loginRequest, headers),
            String.class);

        return extractToken(response.getHeaders().getFirst(HttpHeaders.SET_COOKIE));
    } catch (HttpClientErrorException | ResourceAccessException | HttpServerErrorException e) {
        responseHandler.handleBadResponse(e, ErrorType.BAD_CREDENTIALS,
            "Can not access Gateway service. Uri '{}' returned: {}", uri, e.getMessage());
    }
    return Optional.empty();
}
 
Example #30
Source File: BasicHttpsSecurityApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Test(expected = ResourceAccessException.class)
public void testUnauthenticatedHello() throws Exception {
	ResponseEntity<String> httpsEntity = this.restTemplate.getForEntity("/hi",
			String.class);
	assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(httpsEntity.getBody()).containsIgnoringCase("hello, world");
}