List of usage examples for org.springframework.web.client RestClientException RestClientException
public RestClientException(String msg)
From source file:gateway.test.DataTests.java
/** * Test POST /data/query// w w w .j ava 2 s . c om */ @Test public void testQueryData() { // Mock DataResourceListResponse mockResponse = new DataResourceListResponse(); mockResponse.data = new ArrayList<DataResource>(); mockResponse.getData().add(mockData); mockResponse.pagination = new Pagination(1, 0, 10, "test", "asc"); when(restTemplate.postForObject(anyString(), any(), eq(DataResourceListResponse.class))) .thenReturn(mockResponse); // Test ResponseEntity<PiazzaResponse> entity = dataController.searchData(null, 0, 10, null, null, user); DataResourceListResponse response = (DataResourceListResponse) entity.getBody(); // Verify assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); assertTrue(response.getData().get(0).getDataId().equalsIgnoreCase(mockData.getDataId())); assertTrue(response.getPagination().getCount().equals(1)); // Test an Exception when(restTemplate.postForObject(anyString(), any(), eq(DataResourceListResponse.class))) .thenThrow(new RestClientException("")); entity = dataController.searchData(null, 0, 10, null, null, user); assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)); assertTrue(entity.getBody() instanceof ErrorResponse); }
From source file:gateway.test.DataTests.java
/** * Test GET /file/{dataId}// ww w . j a v a 2 s .com */ @Test public void testDownload() throws Exception { // Mock ResponseEntity<byte[]> mockResponse = new ResponseEntity<byte[]>("Content".getBytes(), HttpStatus.OK); when(restTemplate.getForEntity(anyString(), eq(byte[].class))).thenReturn(mockResponse); // Test ResponseEntity<?> entity = dataController.getFile("123456", "test.txt", user); // Verify assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); System.out.println(entity.getBody().toString()); // Test an Exception when(restTemplate.getForEntity(anyString(), eq(byte[].class))).thenThrow(new RestClientException("")); try { entity = dataController.getFile("123456", "test.txt", user); } catch (Exception exception) { assertTrue(exception.getMessage().contains("Error downloading file")); } }
From source file:org.openmrs.module.webservices.rest.resource.StockOperationResource.java
@Override public StockOperation save(StockOperation operation) { // Ensure that the current user can process the operation if (!userCanProcess(operation)) { throw new RestClientException("The current user not authorized to process this operation."); }//from w ww .j a va 2 s.c o m StockOperation result; // If the status has changed, submit the operation try { if (submitRequired) { result = operationService.submitOperation(operation); } else if (rollbackRequired) { if (!userCanRollback(operation)) { throw new RestClientException("The current user not authorized to rollback this operation."); } result = operationService.rollbackOperation(operation); } else { result = super.save(operation); } } finally { submitRequired = false; rollbackRequired = false; } return result; }
From source file:org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientBeanPostProcessor.java
@Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { final ClientRequest.Builder builder = ClientRequest.from(request); Mono<ClientResponse> exchange = Mono.defer(() -> next.exchange(builder.build())).cast(Object.class) .onErrorResume(Mono::just).zipWith(Mono.subscriberContext()).flatMap(anyAndContext -> { Object any = anyAndContext.getT1(); Span clientSpan = anyAndContext.getT2().get(CLIENT_SPAN_KEY); Mono<ClientResponse> continuation; final Tracer.SpanInScope ws = tracer().withSpanInScope(clientSpan); if (any instanceof Throwable) { continuation = Mono.error((Throwable) any); } else { continuation = Mono.just((ClientResponse) any); }/*from w w w. j av a 2 s . c o m*/ return continuation.doAfterSuccessOrError((clientResponse, throwable1) -> { Throwable throwable = throwable1; if (clientResponse == null || clientResponse.statusCode() == null) { if (log.isDebugEnabled()) { log.debug("No response was returned. Will close the span [" + clientSpan + "]"); } handleReceive(clientSpan, ws, clientResponse, throwable); return; } boolean error = clientResponse.statusCode().is4xxClientError() || clientResponse.statusCode().is5xxServerError(); if (error) { if (log.isDebugEnabled()) { log.debug( "Non positive status code was returned from the call. Will close the span [" + clientSpan + "]"); } throwable = new RestClientException("Status code of the response is [" + clientResponse.statusCode().value() + "] and the reason is [" + clientResponse.statusCode().getReasonPhrase() + "]"); } handleReceive(clientSpan, ws, clientResponse, throwable); }); }).subscriberContext(c -> { if (log.isDebugEnabled()) { log.debug("Instrumenting WebClient call"); } Span parent = c.getOrDefault(Span.class, null); Span clientSpan = handler().handleSend(injector(), builder, request, tracer().nextSpan()); if (log.isDebugEnabled()) { log.debug("Handled send of " + clientSpan); } if (parent == null) { c = c.put(Span.class, clientSpan); if (log.isDebugEnabled()) { log.debug("Reactor Context got injected with the client span " + clientSpan); } } return c.put(CLIENT_SPAN_KEY, clientSpan); }); return exchange; }
From source file:sg.ncl.MainController.java
@RequestMapping(value = "/account_settings", method = RequestMethod.GET) public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException { String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id"); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try {/*from w ww . ja v a 2s. c o m*/ if (RestUtil.isError(response.getStatusCode())) { log.error("No user to edit : {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); throw new RestClientException("[" + error.getError() + "] "); } else { User2 user2 = extractUserInfo(responseBody); // need to do this so that we can compare after submitting the form session.setAttribute(webProperties.getSessionUserAccount(), user2); model.addAttribute("editUser", user2); return "account_settings"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } }
From source file:sg.ncl.MainController.java
@RequestMapping(path = "/show_pub_keys", method = RequestMethod.GET) public String showPublicKeys(Model model, HttpSession session) throws WebServiceRuntimeException { getDeterUid(model, session);/*from w ww. j a v a2s .co m*/ SortedMap<String, Map<String, String>> keysMap; HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getPublicKeys(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("Unable to get public keys for user {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); throw new RestClientException("[" + error.getError() + "] "); } else { ObjectMapper mapper = new ObjectMapper(); keysMap = mapper.readValue(responseBody, new TypeReference<SortedMap<String, Map<String, String>>>() { }); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } model.addAttribute("keys", keysMap); return "showpubkeys"; }
From source file:sg.ncl.MainController.java
@RequestMapping(path = "/delete_pub_key/{keyId}", method = RequestMethod.GET) public String deletePublicKey(HttpSession session, @PathVariable String keyId) throws WebServiceRuntimeException { HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getPublicKeys(session.getAttribute("id").toString()) + "/" + keyId, HttpMethod.DELETE, request, String.class); String responseBody = response.getBody().toString(); try {//from w w w. j a va 2s.co m if (RestUtil.isError(response.getStatusCode())) { log.error("Unable to delete public key {} for user {}", keyId, session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); throw new RestClientException("[" + error.getError() + "] "); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } return "redirect:/show_pub_keys"; }
From source file:tds.itemrenderer.repository.impl.RemoteContentRepositoryTest.java
@Test(expected = ContentRequestException.class) public void shouldThrowForContentRequestException() { final String itemPath = "/path/to/item"; final AccLookup accLookup = new AccLookup(); final IITSDocument itsDocument = new ITSDocument(); itsDocument.setVersion(2000);/*from www .java2s.c o m*/ when(mockRestTemplate.exchange(isA(URI.class), isA(HttpMethod.class), isA(HttpEntity.class), isA(ParameterizedTypeReference.class))).thenThrow(new RestClientException("Exception")); remoteContentRepository.findItemDocument(itemPath, accLookup, "", false); }