@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); }
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; }
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()); } }
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); } } }
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."); }
@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); }
@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); } }
@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); }
@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; }
/** * 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); }
@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); }
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; } }); }
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); }
@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(); } }
/** * 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()); } }
@ExceptionHandler(value = { Exception.class, NullPointerException.class, NoSuchRequestHandlingMethodException.class, RuntimeException.class, ResourceAccessException.class, AccessDeniedException.class, PropertyNotFoundException.class, ConstraintViolationException.class, NestedServletException.class} ) // Don't pass model object here. Seriously was creating issues here. public ModelAndView globalErrorHandler(HttpServletRequest request, Exception e) { System.out.println("comes in exception controller"); ModelAndView mdlViewObj = new ModelAndView("/common/Exception"); logger.error(e.getStackTrace()); return mdlViewObj; //return new ModelAndView("common/Exception"); // Error java.lang.IllegalStateException: No suitable resolver for argument [0] [type=org.springframework.ui.ModelMap] }
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; } }
/** * Returns weather forecast based on GPS coordinates using new weather.gov api. * * @param data * @param user * @return */ private EmailData getWeatherForecast(final EmailData data, final User user) throws ResourceAccessException{ final String uri = "https://api.weather.gov/points/" + user.getWeather().getLatitude() + "," + user.getWeather().getLongitude() + "/forecast"; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); JsonObject forecastData = jsonElement.getAsJsonObject(); JsonObject forecastProperties = forecastData.getAsJsonObject("properties"); JsonArray forecastPeriods = forecastProperties.getAsJsonArray("periods"); for(int index = 0; index < 3; index++){ JsonObject forecast = forecastPeriods.get(index).getAsJsonObject(); data.getWeatherForecast().getPeriodForecast().put(forecast.get("name").getAsString(), forecast.get("detailedForecast").getAsString()); } return data; }
@Test public void testErrorUnknownHostException() { String url = "http://nonexisting.example.com"; try { RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList( new TracingRestTemplateInterceptor(mockTracer))); restTemplate.getForEntity(url, String.class); } catch (ResourceAccessException ex) { //ok UnknownHostException } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(RestTemplateSpanDecorator.StandardTags.COMPONENT_NAME, mockSpan.tags().get(Tags.COMPONENT.getKey())); Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(url, mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(1, mockSpan.logEntries().size()); Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size()); Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event")); Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object")); }
@Test public void testTracingRequest() { try { restTemplate.getForEntity("http://nonexisting.example.com", String.class); } catch (ResourceAccessException ex) { //ok UnknownHostException } Assert.assertEquals(1, mockTracer.finishedSpans().size()); }
@Test(expected = ResourceAccessException.class) public void testPostSocketTimeoutNotRetry(){ when(serviceAddressLocator.getServiceList(any())) .thenReturn(Arrays.asList(mockService(serviceOne), mockService(serviceTwo), mockService(serviceThree))); when(restTemplate.postForEntity(serviceOne + "/" + path, request, Object.class)).thenThrow(socketTimeoutException); when(restTemplate.postForEntity(serviceTwo + "/" + path, request, Object.class)).thenReturn(entity); retryableRestTemplate.post(Env.DEV, path, request, Object.class); verify(restTemplate).postForEntity(serviceOne + "/" + path, request, Object.class); verify(restTemplate, times(0)).postForEntity(serviceTwo + "/" + path, request, Object.class); }
@ResponseStatus(HttpStatus.FAILED_DEPENDENCY) @ExceptionHandler(ConnectException.class) public ResponseEntity<ErrorResponse> handleConnectExceptions(ResourceAccessException e) { return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY) .contentType(MediaType.APPLICATION_JSON) .body(new ErrorResponse(e.getMessage())); }
@Test public void testGetAlarmFailIfAlarmNotFound() { when(restTemplate.getForObject(anyString(), eq(Alarm.class))).thenThrow(new ResourceAccessException("coucou")); try { repository.getAlarm("coucou"); fail(); } catch (CerebroException e) { assertEquals(ErrorCode.ALARM_UNKNOWN, e.getErrorCode()); } }
/** * Creates a join project request to Deterlab * Also creates a new user * * @param jsonString * @return The Deter userid (randomly generated) */ public String joinProjectNewUsers(String jsonString) { log.debug("Joining project as new user: {}", jsonString); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(jsonString, headers); ResponseEntity response; try { response = restTemplate.exchange(properties.getJoinProjectNewUsers(), HttpMethod.POST, request, String.class); } catch (ResourceAccessException rae) { log.warn("New user join project error: {}", rae); throw new AdapterConnectionException(rae.getMessage()); } catch (HttpServerErrorException hsee) { log.warn("New user join project error: Adapter DeterLab internal server error {}", hsee); throw hsee; } // Will get the following JSON: // msg: join project request new users fail // msg: no user created, uid: xxx // msg: user is created, uid: xxx // msg: user not found, uid: xxx String responseBody = response.getBody().toString(); try { String deterMessage = new JSONObject(responseBody).getString("msg"); if("user is created".equalsIgnoreCase(deterMessage)) { log.info("Join project as new user to DeterLab OK"); return responseBody; } log.warn("Join project new user error: {}", deterMessage); throw new DeterLabOperationFailedException(deterMessage); } catch (JSONException e) { log.warn("Error parsing response code new user join project: {}", responseBody); throw e; } }
/** * Creates a apply project request to Deterlab * Does not create a new user * * @param jsonString Contains uid, project name, pid, project goals, project web, project organisation, project visibility */ public String applyProject(String jsonString) { log.info("Applying project as existing user: {}", jsonString); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(jsonString, headers); ResponseEntity response; try { response = restTemplate.exchange(properties.getApplyProject(), HttpMethod.POST, request, String.class); final String responseBody = response.getBody().toString(); log.debug("Apply project as existing user : Deter response -- {}", responseBody); String deterMessage = new JSONObject(responseBody).getString("msg"); if ("apply project existing users ok".equalsIgnoreCase(deterMessage)) { log.info("Apply project as existing user : OK"); return responseBody; } log.warn("Apply project as existing user : error: {}", deterMessage); throw new DeterLabOperationFailedException(deterMessage); } catch (ResourceAccessException rae) { log.warn("Apply project as existing user : Adapter connection error {}", rae); throw new AdapterConnectionException(); } catch (HttpServerErrorException hsee) { log.warn("Apply project as existing user : Adapter internal server error {}", hsee); throw new AdapterInternalErrorException(); } catch (JSONException e) { log.warn("Apply project as existing user : error parsing response body"); throw e; } }
/** * Creates a join project request to Deterlab * Does not create a new user * * @param jsonString Contains uid, pid */ public String joinProject(String jsonString) { log.info("Joining project as existing user : {}", jsonString); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(jsonString, headers); ResponseEntity response; try { response = restTemplate.exchange(properties.getJoinProject(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); log.debug("Join project as existing user : adapter response body -- {}", responseBody); String deterMessage = new JSONObject(responseBody).getString("msg"); if ("Join project existing user ok".equalsIgnoreCase(deterMessage)) { log.info("Join project as existing user : OK"); return responseBody; } log.warn("Join project as existing user : error on DeterLab -- {}", deterMessage); throw new DeterLabOperationFailedException(deterMessage); } catch (ResourceAccessException rae) { log.warn("Join project as existing user : adapter connection error {}", rae); throw new AdapterConnectionException(); } catch (HttpServerErrorException hsee) { log.warn("Join project as existing user : adapter internal server error {}", hsee); throw new AdapterInternalErrorException(); } catch (JSONException e) { log.warn("Join project as existing user : error parsing response body"); throw e; } }
public String saveImage(String nclTeamId, String nclUserId, String nodeId, String imageName) { final String pid = getDeterProjectIdByNclTeamId(nclTeamId); final String uid = getDeterUserIdByNclUserId(nclUserId); log.info("Saving image: pid {}, uid {}, node ID {}, image name {}", pid, uid, nodeId, imageName); JSONObject json = new JSONObject(); json.put("pid", pid); json.put("uid", uid); json.put("nodeId", nodeId); json.put("imageName", imageName); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(json.toString(), headers); ResponseEntity response; try { response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); String deterMessage = new JSONObject(responseBody).getString("msg"); if ("save image OK".equals(deterMessage)) { log.info("Save image OK"); return responseBody; } else { log.warn("Save image FAIL: {}", deterMessage); throw new DeterLabOperationFailedException(deterMessage); } } catch (ResourceAccessException rae) { log.warn("Save image error: {}", rae); throw new AdapterConnectionException(rae.getMessage()); } catch (HttpServerErrorException hsee) { log.warn("Save image error: Adapter DeterLab internal server error {}", hsee); throw new AdapterInternalErrorException(); } }
public String removeUserFromTeam(String nclTeamId, String nclUserId, String nclTeamOwnerId) { final String pid = getDeterProjectIdByNclTeamId(nclTeamId); final String uid = getDeterUserIdByNclUserId(nclUserId); final String ownerUid = getDeterUserIdByNclUserId(nclTeamOwnerId); log.info("Removing user {} from team {} requested by owner {}", uid, pid, ownerUid); JSONObject json = new JSONObject(); json.put("pid", pid); json.put("uidToBeRemoved", uid); json.put("ownerUid", ownerUid); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(json.toString(), headers); ResponseEntity response; try { response = restTemplate.exchange(properties.removeUserFromTeam(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); String deterMessage = new JSONObject(responseBody).getString("msg"); if ("remove user from team ok".equals(deterMessage)) { log.info("Remove user from team OK"); return responseBody; } else { log.warn("Remove user from team FAIL"); throw new DeterLabOperationFailedException(deterMessage); } } catch (ResourceAccessException rae) { log.warn("Remove user from team: {}", rae); throw new AdapterConnectionException(rae.getMessage()); } catch (HttpServerErrorException hsee) { log.warn("Remove user from team: Adapter DeterLab internal server error {}", hsee); throw new AdapterInternalErrorException(); } }
@Test public void joinProjectNewUsersTest2(){ JSONObject myobject = new JSONObject(); exception.expect(AdapterConnectionException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))). thenThrow(new ResourceAccessException("")); adapterDeterLab.joinProjectNewUsers(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProjectNewUsers(); }
@Test public void applyProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "apply project request existing users success"); exception.expect(AdapterConnectionException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new ResourceAccessException("")); adapterDeterLab.applyProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getApplyProject(); }
@Test public void joinProjectTest2() { JSONObject myobject = new JSONObject(); myobject.put("msg", "join project existing user ok"); exception.expect(AdapterConnectionException.class); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new ResourceAccessException("")); adapterDeterLab.joinProject(myobject.toString()); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).getJoinProject(); }
@Test public void saveImageAdapterDeterLabConnectionFailed() { exception.expect(AdapterConnectionException.class); exception.expectMessage(is(equalTo("rae"))); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new ResourceAccessException("rae")); when(deterLabProjectRepository.findByNclTeamId(anyString())).thenReturn(new DeterLabProjectEntity()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); adapterDeterLab.saveImage("nclTeamId", "nclUserId", "nodeId", "imageName"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).saveImage(); }
@Test public void removeUserFromTeamAdapterConnectionException() { exception.expect(AdapterConnectionException.class); exception.expectMessage(is(equalTo("rae"))); when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new ResourceAccessException("rae")); when(deterLabProjectRepository.findByNclTeamId(anyString())).thenReturn(new DeterLabProjectEntity()); when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(new DeterLabUserEntity()); adapterDeterLab.removeUserFromTeam("teamId", "userId", "ownerId"); verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)); verify(properties,times(1)).removeUserFromTeam(); }
@Test(expected = ResourceAccessException.class) public void unauthorizedTest() { MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>(); postParams.add("name", "testgame"); postParams.add("image", "testimage"); postParams.add("description", "aweosome game"); String res = restTemplate .postForObject("/api/games", postParams, String.class); }
@Test public void testProcessCommandHandlesResourceAccessException() { final RestHttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(getLinkIndex()) { private boolean connected = true; @Override public boolean isConnected() { return connected; } @Override protected void printWarning(final String message, final Object... args) { } @Override protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType, final Map<String, ?> uriVariables) { throw new ResourceAccessException("test"); } @Override public void stop() { this.connected = false; } }; assertTrue(operationInvoker.isConnected()); final String expectedResult = String.format( "The connection to the GemFire Manager's HTTP service @ %1$s failed with: %2$s. " + "Please try reconnecting or see the GemFire Manager's log file for further details.", operationInvoker.getBaseUrl(), "test"); final String actualResult = operationInvoker.processCommand(createCommandRequest("list-libraries", Collections.<String, String>emptyMap())); assertFalse(operationInvoker.isConnected()); assertEquals(expectedResult, actualResult); }
@Test public void testProcessCommandHandlesResourceAccessException() { final SimpleHttpOperationInvoker operationInvoker = new SimpleHttpOperationInvoker() { private boolean connected = true; @Override public boolean isConnected() { return connected; } @Override protected <T> ResponseEntity<T> send(final ClientHttpRequest request, final Class<T> responseType) { throw new ResourceAccessException("test"); } @Override public void stop() { this.connected = false; } }; assertTrue(operationInvoker.isConnected()); final String expectedResult = String.format( "The connection to the GemFire Manager's HTTP service @ %1$s failed with: %2$s. " + "Please try reconnecting or see the GemFire Manager's log file for further details.", operationInvoker.getBaseUrl(), "test"); final String actualResult = operationInvoker.processCommand(createCommandRequest("get resource --id=1")); assertFalse(operationInvoker.isConnected()); assertEquals(expectedResult, actualResult); }
@ExceptionHandler(ResourceAccessException.class) public @ResponseBody ResponseBean handleCustomException(ResourceAccessException ex) { LOGGER.error("EXTERNAL SYSTEM CONNECTION EXCEPTION HANDLER ",ex); final ResponseBean responseBase = new ResponseBean(); responseBase.setStatusCode(500); responseBase.setStatusMessage("CLIENT_CONNECTION_REFUSED"); responseBase.setSuccess(false); return responseBase; }
@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); } if (!CollectionUtils.isEmpty(this.configurers)) { AnnotationAwareOrderComparator.sort(this.configurers); for (JwtAccessTokenConverterConfigurer configurer : this.configurers) { configurer.configure(converter); } } return converter; }