Example usage for org.springframework.http HttpStatus SERVICE_UNAVAILABLE

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

Introduction

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

Prototype

HttpStatus SERVICE_UNAVAILABLE

To view the source code for org.springframework.http HttpStatus SERVICE_UNAVAILABLE.

Click Source Link

Document

503 Service Unavailable .

Usage

From source file:org.bonitasoft.web.designer.studio.workspace.StudioWorkspaceResourceHandler.java

protected ResponseEntity<String> doPost(final Path filePath, WorkspaceResourceEvent actionEvent) {
    if (actionEvent == null) {
        throw new IllegalArgumentException("actionEvent is null");
    }/*from   w  w  w . j ava  2 s  . c  o  m*/
    if (restClient.isConfigured()) {
        final String url = createPostURL(actionEvent);
        RestTemplate restTemplate = restClient.getRestTemplate();
        return restTemplate.postForEntity(URI.create(url), filePath != null ? filePath.toString() : null,
                String.class);
    }
    return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
}

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

public String getToken(String user, String password) {
    LOG.debug("Get SugarCRM token");

    if (null == user || null == password || user.isEmpty() || password.isEmpty()) {
        LOG.info("User and password must be provided when creating token");
        throw new BadRequestException(ERR_MISSING_USER_PASSWORD,
                "User and password must be provided when creating token");
    }//from   ww  w . j  a v a 2s.c o  m

    String data = String.format(
            "{\"user_auth\":{\"user_name\":\"%s\",\"password\":\"%s\",\"version\":\"%s\"},\"application_name\":\"%s\"}",
            this.user, md5Hash(this.password), "1.0", "Meeter");
    //LOG.debug("Send login with data:{}", data);

    this.token = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
            LOG.debug("Sending login request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm());
        }
    }, new ResponseExtractor<String>() {
        @Override
        public String extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

            if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                SugarCRMLoginResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                        SugarCRMLoginResponse.class);
                LOG.debug("Response:{}", response);
                if (!response.hasError()) {
                    return response.getId();
                } else if (response.isInvalidCredentials()) {
                    LOG.info("SugarCRM login failed with invalid credentials",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with invalid credentials");
                } else {
                    LOG.info("SugarCRM login failed with unknown reason:{}",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with unknown reason");
                }
            } else {
                // If the SugarCRM does not respond with 200 throw http 503
                LOG.warn("SugarCRM is responding with http code:{}",
                        clientHttpResponse.getStatusCode().value());
                throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                        "SugarCRM request failed");
            }
        }
    }, "login", "json", "json", data);

    LOG.debug("Got token:{}", this.token);

    return this.token;
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }/*  w  w w  . j  av  a 2 s .co  m*/

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

@Override
public CursorPage<DmContact> getPage(int pageSize, String cursorKey) {
    LOG.debug("SugarCRM client, get contacts. Token:{}", token);

    // Check that we have a token
    if (null == this.token || null == token) {
        throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                "Token missing, app must generate token first");
    }//w  ww.  j a  v a2s  .c  o  m

    // If the cursor is null start from the beginning
    if (null == cursorKey) {
        cursorKey = "0";
    }

    // The request
    // {"session":"f9psqc1rgd2iuri76u3v17aul1","module_name":"Contacts","query":"","order_by":"","offset":1,"select_fields":["id","name"],"link_name_to_fields_array":[],"max_results":2,"deleted":0,"Favorites":0}
    String data = String.format(
            "{\"session\":\"%s\",\"module_name\":\"Contacts\",\"query\":\"\",\"order_by\":\"\",\"offset\":%s,\"select_fields\":[\"id\",\"first_name\",\"last_name\",\"email\",\"phone_work\",\"primary_address_street\",\"primary_address_city\",\"primary_address_country\",\"primary_address_postalcode\"],\"link_name_to_fields_array\":[],\"max_results\":%s,\"deleted\":0,\"Favorites\":0}",
            this.token, cursorKey.toString(), pageSize);
    LOG.debug("get contacts with data:{}", data);

    SugarCRMContactsResponse contacts = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET,
            new RequestCallback() {
                @Override
                public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                    LOG.debug("Sending get contact request with url:{}",
                            clientHttpRequest.getURI().toURL().toExternalForm());
                }
            }, new ResponseExtractor<SugarCRMContactsResponse>() {
                @Override
                public SugarCRMContactsResponse extractData(ClientHttpResponse clientHttpResponse)
                        throws IOException {
                    LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

                    if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                        SugarCRMContactsResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                                SugarCRMContactsResponse.class);
                        LOG.debug("Response:{}", response);
                        if (!response.hasError()) {
                            return response;
                        } else if (response.isTokenInvalid()) {
                            LOG.info("Get contacts failed, invalid token");
                            throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                                    "SugarCRM get contacts failed, invalid token");
                        } else {
                            LOG.info("SugarCRM get contacts failed with unknown reason:{}",
                                    new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                            throw new RestException(ERR_SUGAR_GET_CONTACTS_FAILED,
                                    HttpStatus.SERVICE_UNAVAILABLE,
                                    "SugarCRM get contacts failed with unknown reason");
                        }
                    } else {
                        // If the SugarCRM does not respond with 200 throw http 503
                        LOG.warn("SugarCRM is responding with http code:{}",
                                clientHttpResponse.getStatusCode().value());
                        throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                                "SugarCRM request failed");
                    }
                }
            }, "get_entry_list", "json", "json", data);

    LOG.debug("Got number of contacts:{}", contacts.getResult_count());

    CursorPage<DmContact> page = convertToPage(contacts, pageSize);
    return page;
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>//from w  w w. j  av a2  s .co m
 * RHEV Manager  API   .
 * </pre>
 * @param api RHEV Manager API (/api, /api/vms )
 * @param body xml contents
 * @param clazz ? Target Object Class
 * @return
 * @throws RestClientException
 * @throws Exception
 */
public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName,
        Class<T> clazz) throws RestClientException, Exception {
    Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null");
    Assert.notNull(clazz, "clazz must not be null.");

    // Multi RHEV Manager        ? ?? HostnameVerifier ??,
    // ??    ? ?.(java.io.IOException: HTTPS hostname wrong:  should be <{host}>)
    //init();

    try {
        RestTemplate rt = new RestTemplate();

        ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method,
                setHTTPEntity(body, rootElementName), clazz);

        logger.debug("[Request URL] : {}", getUrl(api));
        logger.debug("[Response] : {}", response);

        if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST)
                || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED)
                || response.getStatusCode().equals(HttpStatus.FORBIDDEN)
                || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED)
                || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE)
                || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)
                || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED)
                || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY)
                || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)
                || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) {
            throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString());
        }

        return clazz.cast(response.getBody());
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

From source file:com.erudika.scoold.ScooldServer.java

/**
 * @return Error page registry bean//from  w ww . ja v  a2  s .  c om
 */
@Bean
public ErrorPageRegistrar errorPageRegistrar() {
    return new ErrorPageRegistrar() {
        @Override
        public void registerErrorPages(ErrorPageRegistry epr) {
            epr.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/not-found"));
            epr.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"));
            epr.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401"));
            epr.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
            epr.addErrorPages(new ErrorPage(HttpStatus.SERVICE_UNAVAILABLE, "/error/503"));
            epr.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400"));
            epr.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error/405"));
            epr.addErrorPages(new ErrorPage(Exception.class, "/error/500"));
        }
    };
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

/**
 * {@inheritDoc}//  w  ww . jav  a2s  . com
 */
@Override
public void serveResource(final String jobId, final URL baseUrl, final String relativePath,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    // TODO: Metrics
    // Is the job running or not?
    final JobStatus jobStatus;
    try {
        jobStatus = this.jobPersistenceService.getJobStatus(jobId);
    } catch (final GenieNotFoundException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
        return;
    }

    // Is it V3 or V4?
    final boolean isV4;
    try {
        isV4 = this.jobPersistenceService.isV4(jobId);
    } catch (final GenieJobNotFoundException nfe) {
        // Really after the last check this shouldn't happen but just in case
        log.error(nfe.getMessage(), nfe);
        response.sendError(HttpStatus.NOT_FOUND.value(), nfe.getMessage());
        return;
    }

    // Normalize the base url. Make sure it ends in /.
    final URI baseUri;
    try {
        baseUri = new URI(baseUrl.toString() + SLASH).normalize();
    } catch (final URISyntaxException e) {
        log.error(e.getMessage(), e);
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "Unable to convert " + baseUrl + " to valid URI");
        return;
    }

    if (jobStatus.isActive() && isV4) {

        final Optional<JobDirectoryManifest> manifest = this.agentFileStreamService.getManifest(jobId);
        if (!manifest.isPresent()) {
            log.error("Manifest not found for active job: {}", jobId);
            response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(),
                    "Could not load manifest for job: " + jobId);
            return;
        }

        final URI jobDirRoot;
        try {
            jobDirRoot = new URI(AgentFileProtocolResolver.URI_SCHEME, jobId, SLASH, null);
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }

        this.handleRequest(baseUri, relativePath, request, response, manifest.get(), jobDirRoot);

    } else if (jobStatus.isActive()) {
        // Active V3 job

        // TODO: Manifest creation could be expensive
        final Resource jobDir = this.jobFileService.getJobFileAsResource(jobId, "");
        if (!jobDir.exists()) {
            log.error("Job directory {} doesn't exist. Unable to serve job contents.", jobDir);
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        final URI jobDirRoot;
        try {
            // Make sure the directory ends in a slash. Normalize will ensure only single slash
            jobDirRoot = new URI(jobDir.getURI().toString() + SLASH).normalize();
        } catch (final URISyntaxException e) {
            log.error(e.getMessage(), e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            return;
        }
        final Path jobDirPath = Paths.get(jobDirRoot);

        final JobDirectoryManifest manifest = new JobDirectoryManifest(jobDirPath, false);
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    } else {
        // Archived job
        final JobDirectoryManifest manifest;
        final URI jobDirRoot;
        try {
            final ManifestCacheValue cacheValue = this.manifestCache.get(jobId);
            manifest = cacheValue.getManifest();
            jobDirRoot = cacheValue.getJobDirectoryRoot();
        } catch (final Exception e) {
            // TODO: more fine grained exception handling
            if (e.getCause() instanceof JobNotArchivedException) {
                // will be thrown from the manifest loader
                log.error(e.getCause().getMessage(), e.getCause());
                response.sendError(HttpStatus.NOT_FOUND.value(), e.getCause().getMessage());
            } else {
                log.error(e.getMessage(), e);
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }
            return;
        }
        this.handleRequest(baseUri, relativePath, request, response, manifest, jobDirRoot);
    }
}

From source file:com.tasktop.c2c.server.common.service.tests.http.HttpProxyTest.java

@Test
public void testFailedGet() throws IOException {
    setupMock(HttpStatus.SERVICE_UNAVAILABLE);
    MockHttpServletRequest clientRequest = new MockHttpServletRequest("GET", "unused");
    MockHttpServletResponse clientResponse = new MockHttpServletResponse();

    proxy.proxyRequest("foo", clientRequest, clientResponse);

    Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE.value(), clientResponse.getStatus());

    context.assertIsSatisfied();//  w  w  w  .  j  a  va 2s  .  co m
}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
  * Executes a HTTP request using the spring framework RestTemplate
  * //  w w w.  j  a  v a2  s  . c om
  * @param url the URL
  * @param method the HTTP method (GET, POST, etc)
  * @param requestEntity the entity (headers and/or body) to write to the request, may be null
  * @param responseType the type of the return value
  * @return the response as entity
  * @throws InterruptedException
  * @throws RestClientException
  */
public <T> ResponseEntity<T> executeHttpRequest(final URI url, final HttpMethod method,
        final HttpEntity<?> requestEntity, final Class<T> responseType) {
    final RestTemplate restTemplate = new RestTemplate();

    HttpStatus statusCode = null;
    ResponseEntity<T> responseEntity = null;

    // increment the number of request attempts by 1
    this.numberOfHttpRequestAttempts++;

    try {
        // execute the HTTP request
        responseEntity = restTemplate.exchange(url, method, requestEntity, responseType);
        statusCode = responseEntity.getStatusCode();

        // catch all server HTTP error exceptions
    } catch (HttpServerErrorException exception) {
        statusCode = exception.getStatusCode();

        // if HTTP status is 503 or 504, sleep for 5 seconds and retry
        if ((statusCode.equals(HttpStatus.SERVICE_UNAVAILABLE) || statusCode.equals(HttpStatus.GATEWAY_TIMEOUT))
                && (this.numberOfHttpRequestAttempts < this.numberOfHttpRequestRetries)) {

            logger.info("Server returned an error response with status: " + statusCode
                    + ", retrying again in 5 seconds");
            logger.info("Number of attempts: " + this.numberOfHttpRequestAttempts);

            try {
                // sleep for 5 seconds and try again
                Thread.sleep(5000);

            } catch (InterruptedException interruptedException) {
                logger.error(interruptedException.getMessage(), interruptedException);
            }

            // execute HTTP request again
            this.executeHttpRequest(url, method, requestEntity, responseType);

        } else {
            // in other cases, throw back the exception
            throw exception;
        }
    }

    return responseEntity;
}