Search in sources :

Example 6 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project dhis2-core by dhis2.

the class BulkSmsGateway method send.

private OutboundMessageResponse send(UriComponentsBuilder uriBuilder) {
    ResponseEntity<String> responseEntity = null;
    try {
        URI url = uriBuilder.build().encode("ISO-8859-1").toUri();
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
    } catch (HttpClientErrorException ex) {
        log.error("Client error " + ex.getMessage());
    } catch (HttpServerErrorException ex) {
        log.error("Server error " + ex.getMessage());
    } catch (Exception ex) {
        log.error("Error " + ex.getMessage());
    }
    return getResponse(responseEntity);
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) URI(java.net.URI) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Example 7 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project dhis2-core by dhis2.

the class SchemaController method getSchema.

@RequestMapping(value = "/{type}", method = RequestMethod.GET)
@ResponseBody
public RootNode getSchema(@PathVariable String type) {
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    if (fields.isEmpty()) {
        fields.add("*");
    }
    Schema schema = getSchemaFromType(type);
    if (schema != null) {
        linkService.generateSchemaLinks(schema);
        CollectionNode collectionNode = fieldFilterService.filter(Schema.class, Collections.singletonList(schema), fields);
        return NodeUtils.createRootNode(collectionNode.getChildren().get(0));
    }
    throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Type " + type + " does not exist.");
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Schema(org.hisp.dhis.schema.Schema) CollectionNode(org.hisp.dhis.node.types.CollectionNode) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 8 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project cas by apereo.

the class RestAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential c, final String originalPassword) throws GeneralSecurityException {
    try {
        final UsernamePasswordCredential creds = new UsernamePasswordCredential(c.getUsername(), c.getPassword());
        final ResponseEntity<SimplePrincipal> authenticationResponse = api.authenticate(creds);
        if (authenticationResponse.getStatusCode() == HttpStatus.OK) {
            final SimplePrincipal principalFromRest = authenticationResponse.getBody();
            if (principalFromRest == null || StringUtils.isBlank(principalFromRest.getId())) {
                throw new FailedLoginException("Could not determine authentication response from rest endpoint for " + c.getUsername());
            }
            final Principal principal = this.principalFactory.createPrincipal(principalFromRest.getId(), principalFromRest.getAttributes());
            return createHandlerResult(c, principal, new ArrayList<>());
        }
    } catch (final HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
            throw new AccountDisabledException("Could not authenticate forbidden account for " + c.getUsername());
        }
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            throw new FailedLoginException("Could not authenticate account for " + c.getUsername());
        }
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            throw new AccountNotFoundException("Could not locate account for " + c.getUsername());
        }
        if (e.getStatusCode() == HttpStatus.LOCKED) {
            throw new AccountLockedException("Could not authenticate locked account for " + c.getUsername());
        }
        if (e.getStatusCode() == HttpStatus.PRECONDITION_FAILED) {
            throw new AccountExpiredException("Could not authenticate expired account for " + c.getUsername());
        }
        if (e.getStatusCode() == HttpStatus.PRECONDITION_REQUIRED) {
            throw new AccountPasswordMustChangeException("Account password must change for " + c.getUsername());
        }
        throw new FailedLoginException("Rest endpoint returned an unknown status code " + e.getStatusCode() + " for " + c.getUsername());
    }
    throw new FailedLoginException("Rest endpoint returned an unknown response for " + c.getUsername());
}
Also used : AccountLockedException(javax.security.auth.login.AccountLockedException) FailedLoginException(javax.security.auth.login.FailedLoginException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) SimplePrincipal(org.apereo.cas.authentication.principal.SimplePrincipal) SimplePrincipal(org.apereo.cas.authentication.principal.SimplePrincipal) Principal(org.apereo.cas.authentication.principal.Principal) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException)

Example 9 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project cas by apereo.

the class RestfulAuthenticationPolicy method isSatisfiedBy.

@Override
public boolean isSatisfiedBy(final Authentication authentication) throws Exception {
    try {
        final HttpHeaders acceptHeaders = new HttpHeaders();
        acceptHeaders.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
        final HttpEntity<Principal> entity = new HttpEntity<>(authentication.getPrincipal(), acceptHeaders);
        LOGGER.warn("Checking authentication policy for [{}] via POST at [{}]", authentication.getPrincipal(), this.endpoint);
        final ResponseEntity<String> resp = restTemplate.exchange(this.endpoint, HttpMethod.POST, entity, String.class);
        if (resp == null) {
            LOGGER.warn("[{}] returned no responses", this.endpoint);
            throw new GeneralSecurityException("No response returned from REST endpoint to determine authentication policy");
        }
        if (resp.getStatusCode() != HttpStatus.OK) {
            final Exception ex = handleResponseStatusCode(resp.getStatusCode(), authentication.getPrincipal());
            throw new GeneralSecurityException(ex);
        }
        return true;
    } catch (final HttpClientErrorException e) {
        final Exception ex = handleResponseStatusCode(e.getStatusCode(), authentication.getPrincipal());
        throw new GeneralSecurityException(ex);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) Principal(org.apereo.cas.authentication.principal.Principal) AccountLockedException(javax.security.auth.login.AccountLockedException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) AccountExpiredException(javax.security.auth.login.AccountExpiredException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)

Example 10 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project uPortal by Jasig.

the class DefaultTinCanAPIProvider method init.

/**
 * Initialize the API. Just sends an initialization event to the LRS provider. This uses the
 * activities/state API to do the initial test.
 */
@Override
public void init() {
    loadConfig();
    if (!isEnabled()) {
        return;
    }
    try {
        String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);
        // Setup GET params...
        List<BasicNameValuePair> getParams = new ArrayList<>();
        getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId));
        getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr));
        getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId));
        Object body = null;
        if (formEncodeActivityData) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
            map.add(activitiesFormParamName, json);
            body = map;
        } else {
            // just post a simple:  {"status": "started"} record to the states API to verify
            // the service is up.
            Map<String, String> data = new HashMap<String, String>();
            data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED);
            body = data;
        }
        ResponseEntity<Object> response = sendRequest(STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body, Object.class);
        if (response.getStatusCode().series() != Series.SUCCESSFUL) {
            logger.error("LRS provider for URL " + LRSUrl + " it not configured properly, or is offline.  Disabling provider.");
        }
    // todo: Need to think through a strategy for handling errors submitting
    // to the LRS.
    } catch (HttpClientErrorException e) {
        // log some additional info in this case...
        logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization.  Disabling provider.", e);
        logger.error("  Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
        enabled = false;
    } catch (Exception e) {
        logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization.  Disabling provider", e);
        enabled = false;
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)19 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)8 RestTemplate (org.springframework.web.client.RestTemplate)6 HashMap (java.util.HashMap)4 HttpEntity (org.springframework.http.HttpEntity)4 HttpHeaders (org.springframework.http.HttpHeaders)4 HttpStatus (org.springframework.http.HttpStatus)4 ResourceAccessException (org.springframework.web.client.ResourceAccessException)4 URI (java.net.URI)3 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 AccountExpiredException (javax.security.auth.login.AccountExpiredException)2 AccountLockedException (javax.security.auth.login.AccountLockedException)2 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)2 FailedLoginException (javax.security.auth.login.FailedLoginException)2 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)2 AccountPasswordMustChangeException (org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)2 Principal (org.apereo.cas.authentication.principal.Principal)2 Configuration (org.hisp.dhis.configuration.Configuration)2 ImportSummariesResponseExtractor (org.hisp.dhis.dxf2.common.ImportSummariesResponseExtractor)2