Example usage for org.springframework.http HttpStatus toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Return a string representation of this status code.

Usage

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.RestUtilities.java

public <T> ResponseEntity<T> simpleRestExchange(RequestEntity reg, Class<T> respType) {
    HttpStatus failedCode;
    try {/*from w ww .  j av  a  2  s.com*/
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.exchange(reg, respType);
    } catch (HttpStatusCodeException e) {
        String serverResp = e.getResponseBodyAsString();
        failedCode = e.getStatusCode();
        logger.error(String.format(
                "Exception from server! " + "With status code %s! " + "Following body was responded %s",
                failedCode.toString(), serverResp), e);
    }

    //todo: think of throwing an exception instead of returning a null object
    return new ResponseEntity(null, failedCode);
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public InputStream getProject(String bootVersion, String mvnGroup, String mvnArtifact, String mvnVersion,
        String mvnName, String mvnDesc, String packaging, String pkg, String lang, String javaVersion,
        String deps) throws Exception {
    // set connection timeouts
    timeoutFromPrefs();//from   w w  w  .  ja va2s.  co  m
    // prepare parameterized url
    final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
            "http://start.spring.io");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(serviceUrl.concat("/starter.zip"))
            .queryParam("type", "maven-project").queryParam("bootVersion", bootVersion)
            .queryParam("groupId", mvnGroup).queryParam("artifactId", mvnArtifact)
            .queryParam("version", mvnVersion).queryParam("packaging", packaging).queryParam("name", mvnName)
            .queryParam("description", mvnDesc).queryParam("language", lang)
            .queryParam("javaVersion", javaVersion).queryParam("packageName", pkg)
            .queryParam("dependencies", deps);
    final URI uri = builder.build().encode().toUri();
    // setup request object
    RequestEntity<Void> req = RequestEntity.get(uri).accept(APPLICATION_OCTET_STREAM)
            .header("User-Agent", REST_USER_AGENT).build();
    // connect
    logger.info("Getting Spring Initializr project");
    logger.log(INFO, "Service URL: {0}", uri.toString());
    long start = System.currentTimeMillis();
    ResponseEntity<byte[]> respEntity = rt.exchange(req, byte[].class);
    // analyze response outcome
    final HttpStatus statusCode = respEntity.getStatusCode();
    if (statusCode == OK) {
        final ByteArrayInputStream stream = new ByteArrayInputStream(respEntity.getBody());
        logger.log(INFO, "Retrieved archived project from Spring Initializr service. Took {0} msec",
                System.currentTimeMillis() - start);
        return stream;
    } else {
        // log status code
        final String errMessage = String.format(
                "Spring initializr service connection problem. HTTP status code: %s", statusCode.toString());
        logger.severe(errMessage);
        // throw exception in order to set error message
        throw new RuntimeException(errMessage);
    }
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getMetadata() throws Exception {
    if (metadata == null) {
        // set connection timeouts
        timeoutFromPrefs();/*from  w w  w  . j a  v  a2 s .com*/
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        RequestEntity<Void> req = RequestEntity.get(new URI(serviceUrl))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr metadata from: {0}", serviceUrl);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            metadata = mapper.readTree(respEntity.getBody());
            logger.log(INFO, "Retrieved Spring Initializr service metadata. Took {0} msec",
                    System.currentTimeMillis() - start);
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(metadata));
            }
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return metadata;
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getDependencies(String bootVersion) throws Exception {
    if (!dependencyMetaMap.containsKey(bootVersion)) {
        // set connection timeouts
        timeoutFromPrefs();/*from   w  w  w.  jav a  2 s .  c om*/
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?{bootVersion}"));
        RequestEntity<Void> req = RequestEntity.get(template.expand(bootVersion))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            final JsonNode depMeta = mapper.readTree(respEntity.getBody());
            logger.log(INFO,
                    "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
                    new Object[] { bootVersion, System.currentTimeMillis() - start });
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(depMeta));
            }
            dependencyMetaMap.put(bootVersion, depMeta);
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return dependencyMetaMap.get(bootVersion);
}

From source file:net.longfalcon.newsj.service.GoogleSearchService.java

public GoogleSearchResponse search(String searchString, String referer) {
    try {/*from w w  w  .j av  a2 s  . com*/
        if (ValidatorUtil.isNull(referer)) {
            referer = "http://longfalcon.net";
        }

        String v = "1.0";
        String userip = "192.168.0.1";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Referer", referer);

        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(_SEARCH_URL).queryParam("v", v)
                .queryParam("q", searchString).queryParam("userip", userip).build();
        ResponseEntity<GoogleSearchResponse> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, GoogleSearchResponse.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }
    } catch (Exception e) {
        _log.error(e);
    }

    return null;
}

From source file:net.longfalcon.newsj.service.TmdbService.java

public TmdbFindResults findResultsByImdbId(int imdbId) {
    try {/*from w w w .j a v a  2 s  . c o m*/
        String tmdbUrlBase = config.getTmdbApiUrl();
        String apiKey = config.getDefaultSite().getTmdbKey();

        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString(tmdbUrlBase + "/find/tt" + String.format("%07d", imdbId))
                .queryParam("external_source", "imdb_id").queryParam("api_key", apiKey).build();
        ResponseEntity<TmdbFindResults> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TmdbFindResults.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:net.longfalcon.newsj.service.TraktService.java

/**
 * call ID lookup web service/*from  w w w . ja v a 2s .  c  om*/
 * @param id     id to look up that matches the id type. String to allow imdb queries "ttxxxxxx"
 * @param idType Possible values:  trakt-movie , trakt-show , trakt-episode , imdb , tmdb , tvdb , tvrage .
 * @return
 */
protected TraktResult[] searchById(String id, String idType) {
    try {
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(traktApiUrl + "/search")
                .queryParam("id_type", idType).queryParam("id", id).build();
        ResponseEntity<TraktResult[]> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktResult[].class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:net.longfalcon.newsj.service.TraktService.java

/**
 * call text search web service/*from  w  w w . j  a  v  a  2  s.co m*/
 * @param name
 * @param type  Possible values:  movie , show , episode , person , list .
 * @return
 */
protected TraktResult[] searchByName(String name, String type) {
    try {
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(traktApiUrl + "/search")
                .queryParam("query", name).queryParam("type", type).build();
        ResponseEntity<TraktResult[]> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktResult[].class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:net.longfalcon.newsj.service.TraktService.java

public TraktEpisodeResult getEpisode(long traktId, int season, int episode) {
    try {//from w w w  .  j a va 2  s .com
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString(
                        traktApiUrl + "/shows/" + traktId + "/seasons/" + season + "/episodes/" + episode)
                .queryParam("extended", "full").build();
        ResponseEntity<TraktEpisodeResult> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktEpisodeResult.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler.java

/**
 * Render the error information as an HTML view.
 * @param request the current request/*from  w  w  w  .j  av a  2  s . co m*/
 * @return a {@code Publisher} of the HTTP response
 */
protected Mono<ServerResponse> renderErrorView(ServerRequest request) {
    boolean includeStackTrace = isIncludeStackTrace(request, MediaType.TEXT_HTML);
    Map<String, Object> error = getErrorAttributes(request, includeStackTrace);
    HttpStatus errorStatus = getHttpStatus(error);
    ServerResponse.BodyBuilder responseBody = ServerResponse.status(errorStatus)
            .contentType(MediaType.TEXT_HTML);
    return Flux
            .just("error/" + errorStatus.toString(), "error/" + SERIES_VIEWS.get(errorStatus.series()),
                    "error/error")
            .flatMap((viewName) -> renderErrorView(viewName, responseBody, error))
            .switchIfEmpty(this.errorProperties.getWhitelabel().isEnabled()
                    ? renderDefaultErrorView(responseBody, error)
                    : Mono.error(getError(request)))
            .next().doOnNext((response) -> logError(request, errorStatus));
}