Example usage for org.springframework.http HttpStatus series

List of usage examples for org.springframework.http HttpStatus series

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus series.

Prototype

public Series series() 

Source Link

Document

Return the HTTP status series of this status code.

Usage

From source file:org.jasig.portlet.notice.service.ssp.SSPTaskNotificationService.java

/**
 * Fetch the set of SSP tasks for the uPortal user.
 *
 * @param req The <code>PortletRequest</code>
 * @return The set of notifications for this data source.
 *//*w ww.  j a  v a2s  . c om*/
@Override
public NotificationResponse fetch(PortletRequest req) {
    PortletPreferences preferences = req.getPreferences();
    String enabled = preferences.getValue(SSP_NOTIFICATIONS_ENABLED, "false");
    if (!"true".equalsIgnoreCase(enabled)) {
        return new NotificationResponse();
    }

    String personId = getPersonId(req);
    if (personId == null) {
        // Not all students will have active SSP records,
        // so if no entry is found in SSP, just return an
        // empty response set.
        return new NotificationResponse();
    }

    String urlFragment = getActiveTaskUrl();
    SSPApiRequest<String> request = new SSPApiRequest<>(urlFragment, String.class).addUriParameter("personId",
            personId);

    ResponseEntity<String> response;
    try {
        response = sspApi.doRequest(request);
    } catch (Exception e) {
        log.error("Error reading SSP Notifications: " + e.getMessage());
        return notificationError(e.getMessage());
    }

    if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
        log.error("Error reading SSP Notifications: " + response);
        return notificationError(response.getBody());
    }

    NotificationResponse notification = mapToNotificationResponse(req, response);
    return notification;
}

From source file:springfox.documentation.swagger.readers.operation.SwaggerResponseMessageReader.java

static boolean isSuccessful(int code) {
    return HttpStatus.Series.SUCCESSFUL.equals(HttpStatus.Series.valueOf(code));
}

From source file:eu.freme.eservices.pipelines.core.PipelineService.java

private PipelineResponse execute(final SerializedRequest request, final String body)
        throws UnirestException, IOException, ServiceException {
    switch (request.getMethod()) {
    case GET://from ww w .java2  s.  c om
        throw new UnsupportedOperationException("GET is not supported at this moment.");
    default:
        HttpRequestWithBody req = Unirest.post(request.getEndpoint());
        if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
            req.headers(request.getHeaders());
        }
        if (request.getParameters() != null && !request.getParameters().isEmpty()) {
            req.queryString(request.getParameters()); // encode as POST parameters
        }

        HttpResponse<String> response;
        if (body != null) {
            response = req.body(body).asString();
        } else {
            response = req.asString();
        }
        if (!HttpStatus.Series.valueOf(response.getStatus()).equals(HttpStatus.Series.SUCCESSFUL)) {
            String errorBody = response.getBody();
            HttpStatus status = HttpStatus.valueOf(response.getStatus());
            if (errorBody == null || errorBody.isEmpty()) {
                throw new ServiceException(new PipelineResponse(
                        "The service \"" + request.getEndpoint() + "\" reported HTTP status "
                                + status.toString() + ". No further explanation given by service.",
                        RDFConstants.RDFSerialization.PLAINTEXT.contentType()), status);
            } else {
                throw new ServiceException(
                        new PipelineResponse(errorBody, response.getHeaders().getFirst("content-type")),
                        status);
            }
        }
        return new PipelineResponse(response.getBody(), response.getHeaders().getFirst("content-type"));
    }
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());

    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl
            .getSystemConfiguration(cacheRepositoryService, result);
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);//from   w ww  .  j av a 2 s .c o  m
        result.recordWarning(msg);
        return;
    }

    String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration()
            .getSms()) {
        if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null
                || StringUtils.isNotEmpty(smsConfigName)
                        && smsConfigName.equals(smsConfigurationType.getName())) {
            found = smsConfigurationType;
            break;
        }
    }

    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to "
                + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    SmsConfigurationType smsConfigurationType = found;
    String logToFile = smsConfigurationType.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }

    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (smsConfigurationType.getDefaultFrom() != null) {
        from = smsConfigurationType.getDefaultFrom();
    } else {
        from = "";
    }

    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    List<String> to = message.getTo();
    assert to.size() > 0;

    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            ExpressionVariables variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(),
                    smsGatewayConfigurationType.getUrl());
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task,
                    result);
            LOGGER.debug("Sending SMS to URL {} (method {})", url, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }

            List<String> headersList = evaluateExpressionsChecked(
                    smsGatewayConfigurationType.getHeadersExpression(), variables,
                    "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);

            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(),
                    StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables,
                    "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);

            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(),
                        formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body,
                        resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                if (username != null) {
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
                            plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                        client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url),
                        HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode()
                            + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(),
                        smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via "
                    + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}

From source file:de.blizzy.documentr.system.Downloader.java

String getTextFromUrl(String url, Charset encoding) throws IOException {
    ClientHttpResponse response = null;/*from w  w  w .  java2 s  .c  o m*/
    try {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout((int) TIMEOUT);
        requestFactory.setReadTimeout((int) TIMEOUT);
        ClientHttpRequest request = requestFactory.createRequest(URI.create(url), HttpMethod.GET);
        response = request.execute();
        HttpStatus status = response.getStatusCode();
        if (status.series() == Series.SUCCESSFUL) {
            return IOUtils.toString(response.getBody(), encoding);
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

From source file:org.ambraproject.wombat.service.remote.AbstractRemoteService.java

private static boolean isErrorStatus(int statusCode) {
    HttpStatus.Series series = HttpStatus.Series.valueOf(statusCode);
    return (series == HttpStatus.Series.CLIENT_ERROR) || (series == HttpStatus.Series.SERVER_ERROR);
}

From source file:org.cloudfoundry.identity.uaa.api.common.impl.UaaConnectionHelper.java

/**
 * Make a REST call with custom headers/*from   ww w.  ja  v  a  2s .com*/
 * 
 * @param method the Http Method (GET, POST, etc)
 * @param uri the URI of the endpoint (relative to the base URL set in the constructor)
 * @param body the request body
 * @param responseType the object type to be returned
 * @param uriVariables any uri variables
 * @return the response body
 * @see org.springframework.web.client.RestTemplate#exchange(String, HttpMethod, HttpEntity, ParameterizedTypeReference, Object...)
 */
private <RequestType, ResponseType> ResponseType exchange(HttpMethod method, HttpHeaders headers,
        RequestType body, String uri, ParameterizedTypeReference<ResponseType> responseType,
        Object... uriVariables) {
    getHeaders(headers);

    RestTemplate template = new RestTemplate();
    template.setInterceptors(LoggerInterceptor.INTERCEPTOR);

    HttpEntity<RequestType> requestEntity = null;
    if (body == null) {
        requestEntity = new HttpEntity<RequestType>(headers);
    } else {
        requestEntity = new HttpEntity<RequestType>(body, headers);
    }

    // combine url into the varargs
    List<Object> varList = new ArrayList<Object>();
    varList.add(url);
    if (uriVariables != null && uriVariables.length > 0) {
        varList.addAll(Arrays.asList(uriVariables));
    }

    ResponseEntity<ResponseType> responseEntity = template.exchange("{base}" + uri, method, requestEntity,
            responseType, varList.toArray());

    if (HttpStatus.Series.SUCCESSFUL.equals(responseEntity.getStatusCode().series())) {
        return responseEntity.getBody();
    } else {
        return null;
    }
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.RestAuthenticationManager.java

public RestAuthenticationManager() {
    RestTemplate restTemplate = new RestTemplate();
    // The default java.net client doesn't allow you to handle 4xx responses
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override/*w  w  w . j  a va2s .  c  o  m*/
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.series() == HttpStatus.Series.SERVER_ERROR;
        }
    });
    this.restTemplate = restTemplate;
}

From source file:org.cloudfoundry.identity.uaa.integration.RemoteAuthenticationEndpointTests.java

@SuppressWarnings("rawtypes")
ResponseEntity<Map> authenticate(String username, String password, Map<String, Object> additionalParams) {
    RestTemplate restTemplate = new RestTemplate();
    // The default java.net client doesn't allow you to handle 4xx responses
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    if (restTemplate instanceof OAuth2RestTemplate) {
        OAuth2RestTemplate oAuth2RestTemplate = (OAuth2RestTemplate) restTemplate;
        oAuth2RestTemplate.setErrorHandler(
                new UaaOauth2ErrorHandler(oAuth2RestTemplate.getResource(), HttpStatus.Series.SERVER_ERROR));
    } else {/*from   w  w w  .j a  v a  2 s.  com*/
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            protected boolean hasError(HttpStatus statusCode) {
                return statusCode.series() == HttpStatus.Series.SERVER_ERROR;
            }
        });
    }
    HttpHeaders headers = new HttpHeaders();
    if (additionalParams != null) {
        headers.add("Authorization", "Bearer " + getLoginReadBearerToken());
    }
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
    parameters.set("username", username);
    if (password != null) {
        parameters.set("password", password);
    }
    if (additionalParams != null) {
        parameters.setAll(additionalParams);
    }

    ResponseEntity<Map> result = restTemplate.exchange(serverRunning.getUrl("/authenticate"), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, Object>>(parameters, headers), Map.class);
    return result;
}