private void tryToGetUserProfile(ModelAndView mv, String token) { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Authorization", "Bearer " + token); String endpoint = "http://localhost:8080/api/profile"; try { RequestEntity<Object> request = new RequestEntity<>( headers, HttpMethod.GET, URI.create(endpoint)); ResponseEntity<UserProfile> userProfile = restTemplate.exchange(request, UserProfile.class); if (userProfile.getStatusCode().is2xxSuccessful()) { mv.addObject("profile", userProfile.getBody()); } else { throw new RuntimeException("it was not possible to retrieve user profile"); } } catch (HttpClientErrorException e) { throw new RuntimeException("it was not possible to retrieve user profile"); } }
private String getChecksum(String defaultValue, String url, String version) { String result = defaultValue; if (result == null && StringUtils.hasText(url)) { CloseableHttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); url = constructUrl(url, version); try { ResponseEntity<String> response = new RestTemplate(requestFactory).exchange( url, HttpMethod.GET, null, String.class); if (response.getStatusCode().equals(HttpStatus.OK)) { result = response.getBody(); } } catch (HttpClientErrorException httpException) { // no action necessary set result to undefined logger.debug("Didn't retrieve checksum because", httpException); } } return result; }
/** * Complete the connection to the OAuth2 provider. * * @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory * @param request the current web request * @return a new connection to the service provider */ public Connection completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) { if (connectionFactory.supportsStateParameter()) { verifyStateParameter(request); } String code = request.getParameter("code"); try { AccessGrant accessGrant = connectionFactory.getOAuthOperations() .exchangeForAccess(code, callbackUrl(request), null); return connectionFactory.createConnection(accessGrant); } catch (HttpClientErrorException e) { log.warn("HttpClientErrorException while completing connection: " + e.getMessage()); log.warn(" Response body: " + e.getResponseBodyAsString()); throw e; } }
public Topic create(String name) { if (repository.findByName(name).isPresent()) { throw new HttpClientErrorException(HttpStatus.CONFLICT, name + " 이미 등록된 태그 입니다."); } return repository.save(new Topic(name)); }
/** * * * <p><b>200</b> - Success * @param applicationName The applicationName parameter * @return HierarchicalModel * @throws RestClientException if an error occurs while attempting to invoke the API */ public HierarchicalModel apiApplicationsByApplicationNameGet(String applicationName) throws RestClientException { Object postBody = null; // verify the required parameter 'applicationName' is set if (applicationName == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiApplicationsByApplicationNameGet"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("applicationName", applicationName); String path = UriComponentsBuilder.fromPath("/api/applications/{applicationName}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "text/plain", "application/json", "text/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
@Transactional public void attend(Meeting meeting, User user) { if (!Meeting.MeetingStatus.PUBLISHED.equals(meeting.getMeetingStatus())) { throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "참여 불가능한 모입니다."); } if (!meeting.onRegistTime()) throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "참여 가능한 시간이 아닙니다."); if (meeting.isAttendBy(user)) { throw new HttpClientErrorException(HttpStatus.CONFLICT, "이미 참여한 모임입니다."); } if (meeting.getMaxAttendees() <= 0 || meeting.getAttendees().size() >= meeting.getMaxAttendees()) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "참여 할 수 없습니다. 참여 인원을 확인하세요."); } meeting.attendBy(user); repository.save(meeting); }
private long getNamespaceId(NamespaceIdentifier namespaceIdentifier) { String appId = namespaceIdentifier.getAppId(); String clusterName = namespaceIdentifier.getClusterName(); String namespaceName = namespaceIdentifier.getNamespaceName(); Env env = namespaceIdentifier.getEnv(); NamespaceDTO namespaceDTO = null; try { namespaceDTO = namespaceAPI.loadNamespace(appId, env, clusterName, namespaceName); } catch (HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { throw new BadRequestException(String.format( "namespace not exist. appId:%s, env:%s, clusterName:%s, namespaceName:%s", appId, env, clusterName, namespaceName)); } } return namespaceDTO.getId(); }
/** * Get newsposts from the api. * * @param args [0] = source, [1] = type, [2] = clean name * @return NewsSource object containing list of articles and source information */ public NewsSource getRaw(String... args) { NewsSource newsSource = null; String url = apiUrl + "?source=" + args[0] + "&sortBy=" + args[1] + "&apiKey=" + apiKey; try { newsSource = restTemplate.getForObject(url, NewsSource.class); newsSource.setSourceName(args[2]); logger.info("received " + newsSource.getArticles().size() + " articles from " + args[0]); } catch (HttpClientErrorException ex) { logger.error("Bad Request", ex); } return newsSource; }
@Test public void testErrorsSerializedAsJsonApi() throws IOException { RestTemplate testRestTemplate = new RestTemplate(); try { testRestTemplate .getForEntity("http://localhost:" + this.port + "/doesNotExist", String.class); Assert.fail(); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.NOT_FOUND, e.getStatusCode()); String body = e.getResponseBodyAsString(); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(JacksonModule.createJacksonModule()); Document document = mapper.readerFor(Document.class).readValue(body); Assert.assertEquals(1, document.getErrors().size()); ErrorData errorData = document.getErrors().get(0); Assert.assertEquals("404", errorData.getStatus()); Assert.assertEquals("Not Found", errorData.getTitle()); Assert.assertEquals("No message available", errorData.getDetail()); } }
/** * Handle a POST method by creating a new Milkshake. * Queries appropriate fruit service to check for inventory and consume the fruit into the milkshake * * @param flavor to create * @return a newly created Milkshake */ @RequestMapping(method = RequestMethod.POST) public @ResponseBody Milkshake create(@RequestParam Flavor flavor) { try { FlavorProvider provider = getFlavorProvider(flavor); provider.getIngredients(); } catch (IngredientException e) { throw new HttpClientErrorException(HttpStatus.TOO_MANY_REQUESTS, e.getMessage()); } Milkshake milkshake = new Milkshake(); milkshake.setId(counter.incrementAndGet()); milkshake.setFlavor(flavor); return milkshake; }
private LibraryEntity getAndValidateGameStateChange(Authentication user, Long libraryId, LibraryGameData data) { LibraryEntity entity = libraryRepository.findOne(libraryId); if (entity == null) { throw new HttpClientErrorException(NOT_FOUND, format("No library game exists with id '%d'.", libraryId)); } validateLibraryIsUsers(user, entity.getOwner().getId()); if (entity.getState() == GameState.ON_LOAN) { throw new HttpClientErrorException(BAD_REQUEST, format("You can't modify '%s' while it is loaned to '%s'.", entity.getGame().getName(), entity.getBorrower().getName())); } if (data.getAttributes().getState() == GameState.ON_LOAN) { throw new HttpClientErrorException(BAD_REQUEST, format("You can't set '%s' to an on-loan state.", entity.getGame().getName())); } return entity; }
@Override protected RestResponsePage<Approval> run() throws Exception { try { ParameterizedTypeReference<RestResponsePage<Approval>> responsetype = new ParameterizedTypeReference<RestResponsePage<Approval>>() { }; ResponseEntity<RestResponsePage<Approval>> result = restTemplate .exchange(uriBuilder.build().encode().toUri(), HttpMethod.POST, new HttpEntity<>(approvalFilters), responsetype); return result.getBody(); } catch (HttpClientErrorException exception) { throw new HystrixBadRequestException(exception.getMessage(), new HttpBadRequestException(ErrorResponse.getErrorResponse(exception), exception)); } }
public ActuatorVersion getActuatorVersion(Application app) { String url = app.endpoints().env(); try { LOGGER.debug("HEAD {}", url); HttpHeaders headers = headRestTemplate.headForHeaders(new URI(url)); return ActuatorVersion.parse(headers.getContentType()); } catch (RestClientException ex) { if(ex instanceof HttpClientErrorException) { HttpClientErrorException clientEx = ((HttpClientErrorException)ex); // Spring Boot 1.3 does not allow HEAD method, so let's assume the app is up if(clientEx.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) { return ActuatorVersion.V1; } } throw RestTemplateErrorHandler.handle(app, url, ex); } catch (URISyntaxException e) { throw RestTemplateErrorHandler.handle(app, e); } }
@SuppressWarnings("unchecked") @Test(priority=14) /** again with http error */ public void getWorkOrdersHttpErrTest(){ CmsDeployment cmsDeployment = mock(CmsDeployment.class); when(cmsDeployment.getDeploymentId()).thenReturn(DPLMNT_ID); DelegateExecution delegateExecution = mock(DelegateExecution.class); when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment); //we rely on mock of restTemplate to give error answer RestTemplate httpErrorTemplate = mock(RestTemplate.class); when( httpErrorTemplate.getForObject(anyString(), any(java.lang.Class.class), anyLong(), anyInt())) .thenThrow( new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT,"mocking")); cc.setRestTemplate(httpErrorTemplate); cc.getWorkOrderIds(delegateExecution); //it would be nice to assert the exec was updated, but for now we //just let the test pass if the client swallows the http error }
@SuppressWarnings("unchecked") @Test public void updateWoStateTestHttperr(){ DelegateExecution delegateExecution = mock(DelegateExecution.class); CmsDeployment cmsDeployment = mock(CmsDeployment.class); when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment); when(delegateExecution.getId()).thenReturn("Id11"); when(delegateExecution.getVariable("error-message")).thenReturn("mocked-error"); CmsWorkOrderSimple cmsWorkOrderSimple= new CmsWorkOrderSimple(); cmsWorkOrderSimple.setDpmtRecordId(0); cmsWorkOrderSimple.setDeploymentId(66); cmsWorkOrderSimple.setComments("mockito-mock-comments"); RestTemplate httpErrorTemplate = mock(RestTemplate.class); when( httpErrorTemplate.getForObject(anyString(), any(java.lang.Class.class), anyLong(), anyInt())) .thenThrow( new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT,"mocking")); cc.setRestTemplate(httpErrorTemplate); cc.updateWoState(delegateExecution, cmsWorkOrderSimple, "failed") ; //also to do complete }
public RightHolder getRightHolder(String eppnOrEmail) { try { return apiCrousService.getRightHolder(eppnOrEmail); } catch(HttpClientErrorException clientEx) { if(HttpStatus.UNAUTHORIZED.equals(clientEx.getStatusCode())) { log.info("Auth Token of Crous API should be renew, we call an authentication"); apiCrousService.authenticate(); try { return apiCrousService.getRightHolder(eppnOrEmail); } catch(HttpClientErrorException clientEx2) { // no crouslogError in db for a getRightHolder // crousLogService.logErrorCrous(eppnOrEmail, null, clientEx2.getResponseBodyAsString()); log.warn("Exception calling api crous after reauthentication - apiCrousService.getRightHolder " + eppnOrEmail + " : \n" + clientEx2.getResponseBodyAsString(), clientEx2); throw clientEx2; } } else { // no crouslogError in db for a getRightHolder // crousLogService.logErrorCrous(eppnOrEmail, null, clientEx.getResponseBodyAsString()); log.warn("Exception calling api crous - apiCrousService.getRightHolder " + eppnOrEmail + " : \n" + clientEx.getResponseBodyAsString(), clientEx); throw clientEx; } } }
public void postOrUpdateRightHolder(String eppn) { try { apiCrousService.postOrUpdateRightHolder(eppn); } catch(HttpClientErrorException clientEx) { if(HttpStatus.UNAUTHORIZED.equals(clientEx.getStatusCode())) { log.info("Auth Token of Crous API should be renew, we call an authentication"); apiCrousService.authenticate(); try { apiCrousService.postOrUpdateRightHolder(eppn); } catch(HttpClientErrorException clientEx2) { crousLogService.logErrorCrous(eppn, null, clientEx2.getResponseBodyAsString()); log.warn("Exception calling api crous after reauthentication - apiCrousService.postOrUpdateRightHolder " + eppn + " : \n" + clientEx2.getResponseBodyAsString(), clientEx2); throw clientEx2; } } else { crousLogService.logErrorCrous(eppn, null, clientEx.getResponseBodyAsString()); log.warn("Exception calling api crous - apiCrousService.postOrUpdateRightHolder " + eppn + " : \n" + clientEx.getResponseBodyAsString(), clientEx); throw clientEx; } } }
@RequestMapping(value = "/{appId}/miss_envs", method = RequestMethod.GET) public MultiResponseEntity<Env> findMissEnvs(@PathVariable String appId) { MultiResponseEntity<Env> response = MultiResponseEntity.ok(); for (Env env : portalSettings.getActiveEnvs()) { try { appService.load(env, appId); } catch (Exception e) { if (e instanceof HttpClientErrorException && ((HttpClientErrorException) e).getStatusCode() == HttpStatus.NOT_FOUND) { response.addResponseEntity(RichResponseEntity.ok(env)); } else { response.addResponseEntity(RichResponseEntity.error(HttpStatus.INTERNAL_SERVER_ERROR, String.format("load appId:%s from env %s error.", appId, env) + e.getMessage())); } } } return response; }
public void postOrUpdateRightHolder(String eppn) { if(enable) { String url = webUrl + "/rightholders/" + eppn; HttpHeaders headers = this.getAuthHeaders(); HttpEntity entity = new HttpEntity(headers); try { ResponseEntity<RightHolder> response = restTemplate.exchange(url, HttpMethod.GET, entity, RightHolder.class); log.info("Getting RightHolder for " + eppn +" : " + response.toString()); RightHolder oldRightHolder = response.getBody(); RightHolder newRightHolder = this.computeEsupSgcRightHolder(eppn); if(!newRightHolder.fieldWoDueDateEquals(oldRightHolder) || mustUpdateDueDateCrous(oldRightHolder, eppn)) { updateRightHolder(eppn); } } catch(HttpClientErrorException clientEx) { if(HttpStatus.NOT_FOUND.equals(clientEx.getStatusCode())) { postRightHolder(eppn); return ; } else { throw clientEx; } } } }
private void postRightHolder(String eppn) { String url = webUrl + "/rightholders"; HttpHeaders headers = this.getAuthHeaders(); RightHolder rightHolder = this.computeEsupSgcRightHolder(eppn); HttpEntity entity = new HttpEntity(rightHolder, headers); log.debug("Try to post to CROUS RightHolder : " + rightHolder); try { ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); } catch(HttpClientErrorException clientEx) { if(HttpStatus.LOCKED.equals(clientEx.getStatusCode())) { if("Account is closed".equals(getErrorMessage(clientEx.getResponseBodyAsString()))) { log.info("Account " + eppn + " is closed"); return; } else { throw new CrousAccountLockException(clientEx.getResponseBodyAsString(), clientEx); } } else { throw clientEx; } } log.info(eppn + " sent in CROUS as RightHolder"); }
public void validateSmartCard(Card card) { if(enable) { String url = webUrl + "/rightholders/" + card.getEppn() + "/smartcard/" + card.getCrousSmartCard().getIdZdc(); HttpHeaders headers = this.getAuthHeaders(); HttpEntity entity = new HttpEntity(headers); try { ResponseEntity<CrousSmartCard> response = restTemplate.exchange(url, HttpMethod.GET, entity, CrousSmartCard.class); log.info("GET on " + url + " is OK : " + response.getBody() + " we revalidate this smartCard"); revalidateSmartCard(card); } catch(HttpClientErrorException clientEx) { if(HttpStatus.NOT_FOUND.equals(clientEx.getStatusCode())) { log.info("Card not found in crous - we try to send card " + card.getCsn() + " - " + card.getCrousSmartCard().getIdZdc() + " in CROUS"); validateNewSmartCard(card); return ; } else { throw clientEx; } } } }
private void validateNewSmartCard(Card card) { String url = webUrl + "/rightholders/" + card.getEppn() + "/smartcard"; HttpHeaders headers = this.getAuthHeaders(); CrousSmartCard smartCard = card.getCrousSmartCard(); HttpEntity entity = new HttpEntity(smartCard, headers); log.debug("Try to post to CROUS SmartCard for " + card.getEppn() + " : " + smartCard); try { ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); log.info("Card with csn " + card.getCsn() + " sent in CROUS as CrousSmartCard"); } catch(HttpClientErrorException clientEx) { if(HttpStatus.LOCKED.equals(clientEx.getStatusCode())) { log.info("LOCKED : " + clientEx.getResponseBodyAsString()); log.info("Card can't be added : IZLY account is locked"); return; } throw clientEx; } }
/** * Creates the. * * @param <T> the generic type * @param obj the obj * @param class1 the class 1 * @return the t * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ @SuppressWarnings("unchecked") public <T> T create(Object obj, Class<T> class1) throws JsonParseException, JsonMappingException, IOException, HttpServerErrorException { try{ String res = this.restTemplate.postForObject(getURI(class1), obj, String.class); if(res instanceof String){ ObjectMapper mapper = new ObjectMapper(); JsonNode obj2 = mapper.readValue(res, JsonNode.class); return (T) mapper.readValue(obj2.toString(), class1); }else{ return (T) obj; } }catch(HttpClientErrorException e){ System.out.println("deu erro"); System.out.println(e.getMessage()); System.out.println(e.getResponseBodyAsString()); return null; } }
@ExceptionHandler({ HttpClientErrorException.class }) public ResponseEntity<Object> handleHttpClientErrorException(final Exception ex, WebRequest request) { final String error = "Digits authorization failed" ; final ApiError apiError = new ApiError(HttpStatus.FORBIDDEN, ex.getLocalizedMessage(), error); return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.FORBIDDEN); }
@Test public void testBatchSubjectsDataConstraintViolationSubjectIdentifier() { List<BaseSubject> subjects = new ArrayList<BaseSubject>(); subjects.add(this.privilegeHelper.createSubject("marissa")); subjects.add(this.privilegeHelper.createSubject("marissa")); try { this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH, new HttpEntity<>(subjects, this.zone1Headers), ResponseEntity.class); } catch (HttpClientErrorException e) { Assert.assertEquals(e.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY); return; } this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/marissa", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); Assert.fail("Expected unprocessable entity http client error."); }
public void testCreateBatchSubjectsWithMalformedJSON() { try { String badSubject = "{\"subject\":{\"name\" : \"good-subject-brittany\"}," + "{\"subject\": bad-subject-sarah\"}"; MultiValueMap<String, String> headers = ACSTestUtil.httpHeaders(); headers.add("Content-type", "application/json"); headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name); HttpEntity<String> httpEntity = new HttpEntity<String>(badSubject, headers); this.acsAdminRestTemplate .postForEntity(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH, httpEntity, Subject[].class); } catch (HttpClientErrorException e) { Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST); return; } this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/bad-subject-sarah", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/good-subject-brittany", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); Assert.fail("testCreateBatchSubjectsWithMalformedJSON should have failed!"); }
@Test public void testBatchResourcesDataConstraintViolationResourceIdentifier() { List<BaseResource> resources = new ArrayList<BaseResource>(); resources.add(this.privilegeHelper.createResource("dupResourceIdentifier")); resources.add(this.privilegeHelper.createResource("dupResourceIdentifier")); try { // This POST causes a data constraint violation on the service bcos // of duplicate // resource_identifiers which returns a HTTP 422 error. this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH, new HttpEntity<>(resources, this.zone1Headers), ResponseEntity.class); } catch (HttpClientErrorException e) { Assert.assertEquals(e.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY); return; } this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/marissa", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); Assert.fail("Expected unprocessable entity http client error on post for 2 resources with duplicate resource" + "identifiers."); }
/** * Handles HTTP 3xx/4xx/5xx statuses */ public static ApplicationRuntimeException handle(Application app, String url, RestClientException ex) { // HTTP 5xx if(ex instanceof HttpServerErrorException) { HttpServerErrorException serverEx = ((HttpServerErrorException)ex); return new ApplicationRuntimeException(app, String.format("A server error happened while calling %s (HTTP %s)", url, serverEx.getRawStatusCode())); } // HTTP 4xx else if(ex instanceof HttpClientErrorException) { HttpClientErrorException clientEx = ((HttpClientErrorException)ex); return new ApplicationRuntimeException(app, String.format("Bad request on endpoint %s (HTTP %s)", url, clientEx.getRawStatusCode())); } // HTTP 3xx else if(ex instanceof HttpRedirectErrorException) { HttpRedirectErrorException redirectEx = ((HttpRedirectErrorException)ex); if(redirectEx.getStatusCode().series() == Series.REDIRECTION) { return new ApplicationRuntimeException(app, String.format("Endpoint %s is available but security might be enabled (HTTP %s)", url, redirectEx.getRawStatusCode() )); } } return handle(app, ex); }
public void testCreateBatchResourcesWithMalformedJSON() { try { String badResource = "{\"resource\":{\"name\" : \"Site\", \"uriTemplate\" : " + "\"/secured-by-value/sites/{site_id}\"},{\"resource\": bad-resource-form\"}"; MultiValueMap<String, String> headers = ACSTestUtil.httpHeaders(); headers.add("Content-type", "application/json"); headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name); HttpEntity<String> httpEntity = new HttpEntity<String>(badResource, headers); this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH, httpEntity, BaseResource[].class); } catch (HttpClientErrorException e) { Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST); return; } this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/bad-resource-form", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); this.acsAdminRestTemplate .exchange(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/Site", HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class); Assert.fail("testCreateBatchResourcesWithMalformedJSON should have failed!"); }
@Test(dataProvider = "endpointProvider") public void testPolicyCreationInValidPolicy(final String endpoint) throws Exception { String testPolicyName = ""; try { String policyFile = "src/test/resources/missing-policy-set-name-policy.json"; testPolicyName = this.policyHelper.setTestPolicy(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getZone1Headers(), endpoint, policyFile); } catch (HttpClientErrorException e) { this.acsTestUtil.assertExceptionResponseBody(e, "policy set name is missing"); Assert.assertEquals(e.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY); return; } this.policyHelper.deletePolicySet(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getAcsUrl(), testPolicyName, this.acsitSetUpFactory.getZone1Headers()); Assert.fail("testPolicyCreationInValidPolicy should have failed"); }
@Test(dataProvider = "endpointProvider") public void testPolicyCreationInValidWithBadPolicySetNamePolicy(final String endpoint) throws Exception { String testPolicyName = ""; try { String policyFile = "src/test/resources/policy-set-with-only-name-effect.json"; testPolicyName = this.policyHelper.setTestPolicy(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getZone1Headers(), endpoint, policyFile); } catch (HttpClientErrorException e) { this.acsTestUtil.assertExceptionResponseBody(e, "is not URI friendly"); Assert.assertEquals(e.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY); return; } this.policyHelper.deletePolicySet(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getAcsUrl(), testPolicyName, this.acsitSetUpFactory.getZone1Headers()); Assert.fail("testPolicyCreationInValidPolicy should have failed"); }
@Test public void testHttpValidationBasedOnActiveSpringProfile() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); if (!Arrays.asList(this.environment.getActiveProfiles()).contains("httpValidation")) { Assert.assertEquals(this.getMonitoringApiResponse(headers).getStatusCode(), HttpStatus.OK); return; } try { this.getMonitoringApiResponse(headers); Assert.fail("Expected an HttpMediaTypeNotAcceptableException exception to be thrown"); } catch (final HttpClientErrorException e) { Assert.assertEquals(e.getStatusCode(), HttpStatus.NOT_ACCEPTABLE); } }
@When("^client_one does a PUT on (.*?) with (.*?) in zone 1$") public void client_one_does_a_PUT_on_identifier_in_test_zone(final String api, final String identifier) throws Throwable { OAuth2RestTemplate acsTemplate = this.acsZone1Template; try { switch (api) { case "subject": this.privilegeHelper.putSubject(acsTemplate, this.subject, this.acsUrl, this.zone1Headers, this.privilegeHelper.getDefaultAttribute()); break; case "resource": this.privilegeHelper.putResource(acsTemplate, this.resource, this.acsUrl, this.zone1Headers, this.privilegeHelper.getDefaultAttribute()); break; case "policy-set": this.testPolicyName = "single-action-defined-policy-set"; this.policyHelper.createPolicySet("src/test/resources/single-action-defined-policy-set.json", acsTemplate, this.zone1Headers); break; default: Assert.fail("Api " + api + " does not match/is not yet implemented for this test code."); } } catch (HttpClientErrorException e) { Assert.fail("Unable to PUT identifier: " + identifier + " for api: " + api); } }
@Test(expected = HttpClientErrorException.class) public void testCompleteConnectionOauth2Exception() { when(oauth2Operations.exchangeForAccess(any(), any(), any())) .thenThrow(new HttpClientErrorException(HttpStatus.BAD_REQUEST)); when(oauth2ConnectionFactory.supportsStateParameter()).thenReturn(true); when(request.getParameter(eq("state"))).thenReturn("testState"); when(sessionStrategy.getAttribute(eq(request), eq("oauth2State"))).thenReturn("testState"); Connection<?> result = target.completeConnection(oauth2ConnectionFactory, request); }
public boolean isValidCustomerId(long customerId) { RestTemplate restTemplate = new RestTemplate(); try { ResponseEntity<String> entity = restTemplate.getForEntity(customerURL() + customerId, String.class); return entity.getStatusCode().is2xxSuccessful(); } catch (final HttpClientErrorException e) { if (e.getStatusCode().value() == 404) return false; else throw e; } }
@ResponseStatus(HttpStatus.FAILED_DEPENDENCY) @ExceptionHandler(HttpClientErrorException.class) public ResponseEntity<ErrorResponse> handleStatusExceptions(HttpClientErrorException e) { return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY) .contentType(MediaType.APPLICATION_JSON) .body(new ErrorResponse(e.getMessage())); }
/** * This method activates the account with a token. * * @param token Account activation token * @param uriComponentsBuilder {@link UriComponentsBuilder} * @return The ModelAndView for sign in */ @GetMapping(value = "/thanks") public ModelAndView confirmAccount( @RequestParam final String token, final UriComponentsBuilder uriComponentsBuilder ) { SSLContextHelper.disable(); final RestTemplate restTemplate = new RestTemplate(); final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders()); final UriComponents uriComponents = uriComponentsBuilder.path("/api/v1.0/register/token/{token}").buildAndExpand(token); ResponseEntity<Void> response; try { response = restTemplate .exchange(uriComponents.toUri(), HttpMethod.PUT, entity, Void.class); } catch (HttpClientErrorException e) /* IF 404 */ { return new ModelAndView("tokenNotFound"); } /* IF 200 */ return new ModelAndView("redirect:/signIn"); }
/** * * * <p><b>200</b> - Success * @param applicationName The applicationName parameter * @param environmentName The environmentName parameter * @return List<SettingReadModel> * @throws RestClientException if an error occurs while attempting to invoke the API */ public List<SettingReadModel> apiSettingsByApplicationNameByEnvironmentNameGet(String applicationName, String environmentName) throws RestClientException { Object postBody = null; // verify the required parameter 'applicationName' is set if (applicationName == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiSettingsByApplicationNameByEnvironmentNameGet"); } // verify the required parameter 'environmentName' is set if (environmentName == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiSettingsByApplicationNameByEnvironmentNameGet"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("applicationName", applicationName); uriVariables.put("environmentName", environmentName); String path = UriComponentsBuilder.fromPath("/api/settings/{applicationName}/{environmentName}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "text/plain", "application/json", "text/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<List<SettingReadModel>> returnType = new ParameterizedTypeReference<List<SettingReadModel>>() {}; return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
/** * * * <p><b>200</b> - Success * @param applicationName The applicationName parameter * @param environmentName The environmentName parameter * @param settings The settings parameter * @return Boolean * @throws RestClientException if an error occurs while attempting to invoke the API */ public Boolean apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost(String applicationName, String environmentName, SettingsWriteModel settings) throws RestClientException { Object postBody = settings; // verify the required parameter 'applicationName' is set if (applicationName == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost"); } // verify the required parameter 'environmentName' is set if (environmentName == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiSettingsCreateUpdateByApplicationNameByEnvironmentNamePost"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("applicationName", applicationName); uriVariables.put("environmentName", environmentName); String path = UriComponentsBuilder.fromPath("/api/settings/create-update/{applicationName}/{environmentName}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "text/plain", "application/json", "text/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "application/json-patch+json", "application/json", "text/json", "application/_*+json" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<Boolean> returnType = new ParameterizedTypeReference<Boolean>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }
/** * * * <p><b>200</b> - Success * @param name The name parameter * @param parentAppId The parentAppId parameter * @return HierarchicalModel * @throws RestClientException if an error occurs while attempting to invoke the API */ public HierarchicalModel apiApplicationsAddParentparentAppIdNewnamePost(String name, Integer parentAppId) throws RestClientException { Object postBody = null; // verify the required parameter 'name' is set if (name == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'name' when calling apiApplicationsAddParentparentAppIdNewnamePost"); } // verify the required parameter 'parentAppId' is set if (parentAppId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'parentAppId' when calling apiApplicationsAddParentparentAppIdNewnamePost"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("name", name); uriVariables.put("parentAppId", parentAppId); String path = UriComponentsBuilder.fromPath("/api/applications/add/parent-{parentAppId}/new-{name}").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); final String[] accepts = { "text/plain", "application/json", "text/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); }