Example usage for org.springframework.http ResponseEntity getStatusCode

List of usage examples for org.springframework.http ResponseEntity getStatusCode

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity getStatusCode.

Prototype

public HttpStatus getStatusCode() 

Source Link

Document

Return the HTTP status code of the response.

Usage

From source file:com.apress.prospringintegration.web.MultipartHttpClient.java

public static void main(String[] args) {
    RestTemplate template = new RestTemplate();
    String uri = "http://localhost:8080/http-adapter-1.0.0/inboundMultipartAdapter.html";
    Resource picture = new ClassPathResource("com/apress/prospringintegration/web/test.png");
    MultiValueMap map = new LinkedMultiValueMap();
    map.add("name", "John Smith");
    map.add("picture", picture);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(new MediaType("multipart", "form-data"));
    HttpEntity request = new HttpEntity(map, headers);
    ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, null);
    System.out.println("Status: " + httpResponse.getStatusCode().name());
}

From source file:com.example.user.UserEndpoint.java

public static void main(String[] args) {
    final ObjectMapper objectMapper = new ObjectMapper().registerModule(new Jackson2HalModule())
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
    converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
    final RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));
    final ResponseEntity<PagedResources<Resource<UserEntity>>> entity = restTemplate.exchange(
            "http://localhost:5000/db-app/users", HttpMethod.GET, null,
            new ParameterizedTypeReference<PagedResources<Resource<UserEntity>>>() {
            });//from www.j av  a 2 s . co m
    System.out.println(entity.getStatusCode());
    final PagedResources<Resource<UserEntity>> body = entity.getBody();
    System.out.println(body);
    final Collection<Resource<UserEntity>> contents = body.getContent();
    final List<UserEntity> userEntities = contents.stream().map(Resource::getContent).collect(toList());
}

From source file:edu.infsci2560.LoginHelper.java

private static HttpHeaders getHeaders(TestRestTemplate template, String route) {
    // todo : write getHeaders test
    HttpHeaders headers = new HttpHeaders();
    ResponseEntity<String> page = template.getForEntity(route, String.class);
    assertThat(page.getStatusCode()).isEqualTo(HttpStatus.OK);

    String cookie = page.getHeaders().getFirst("Set-Cookie");
    headers.set("Cookie", cookie);

    Pattern pattern = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*");
    Matcher matcher = pattern.matcher(page.getBody());
    assertThat(matcher.matches()).as(page.getBody()).isTrue();
    headers.set("X-CSRF-TOKEN", matcher.group(1));
    return headers;
}

From source file:cn.org.once.cstack.utils.RestUtils.java

public static String sendGetCommand(String url) {

    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<?> result = restTemplate.getForEntity(url, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    logger.info("REST PUT COMMAND " + contentType + " " + statusCode);
    return body;/*from  w  w w . j a va2  s.  c  o  m*/
}

From source file:de.zib.gndms.taskflows.interslicetransfer.server.logic.InterSliceTransferQuoteCalculator.java

/**
 * Prepares the source url//from ww w.  ja v  a  2s. c  om
 *
 * If the url is present in the order this does nothing else
 * it fetches the GridFTP-url for source slice.
 *
 * @param order An order delegate with the interSlice transfer order.
 * @param sliceClient A slice-client with a valid rest template instance.
 */
public static void prepareSourceUrl(DelegatingOrder<InterSliceTransferOrder> order, SliceClient sliceClient) {

    InterSliceTransferOrder ist = order.getOrderBean();
    if (ist.getSourceURI() == null) {
        try {
            final ResponseEntity<String> responseEntity = sliceClient.getGridFtpUrl(ist.getSourceSlice(),
                    order.getDNFromContext());
            if (HttpStatus.OK.equals(responseEntity.getStatusCode()))
                ist.setSourceURI(responseEntity.getBody());
            else
                throw new UnsatisfiableOrderException("Invalid source slice specifier");
        } catch (ResourceAccessException e) {
            throw new UnsatisfiableOrderException("Could not connect to source slice specifier");
        }
    }
}

From source file:org.mythtv.service.guide.v25.ProgramGuideHelperV25.java

private static void downloadProgramGuide(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadProgramGuide : enter");

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ProgramHelperV25.getInstance().deletePrograms(context, locationProfile, ops,
            ProgramConstants.CONTENT_URI_GUIDE, ProgramConstants.TABLE_NAME_GUIDE);
    RecordingHelperV25.getInstance().deleteRecordings(context, locationProfile, ops, ContentDetails.GUIDE);

    DateTime startDownloading = new DateTime();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int downloadDays = Integer.parseInt(sp.getString("preference_program_guide_days", "14"));
    Log.v(TAG, "downloadProgramGuide : downloadDays=" + downloadDays);

    DateTime start = new DateTime(DateTimeZone.getDefault()).withTimeAtStartOfDay();
    DateTime end = start.plusHours(3);/*from   w  ww.j av a2  s  . com*/
    for (int i = 0; i < ((downloadDays * 24) / 3); i++) {
        Log.i(TAG,
                "downloadProgramGuide : starting download for [" + (i + 1) + " of " + ((downloadDays * 24) / 3)
                        + "] "
                        + DateUtils.getDateTimeUsingLocaleFormattingPretty(start,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType())
                        + ", end time=" + DateUtils.getDateTimeUsingLocaleFormattingPretty(end,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType()));

        EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
                "GetProgramGuide", String.valueOf(i));
        Log.d(TAG, "downloadProgramGuide : etag=" + etag.getValue());

        if (null == etag.getDate() || start.isAfter(etag.getDate())) {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has passed");

            ResponseEntity<ProgramGuide> responseEntity = mMythServicesTemplate.guideOperations()
                    .getProgramGuide(start, end, 1, null, false, etag);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 200 OK");
                ProgramGuide programGuide = responseEntity.getBody();

                if (null != programGuide) {

                    if (null != programGuide) {
                        load(context, locationProfile, programGuide);
                    }

                }

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setEndpoint("GetProgramGuide");
                    etag.setDataId(i);
                    etag.setDate(locationProfile.getNextMythFillDatabase());
                    etag.setMasterHostname(locationProfile.getHostname());
                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 304 Not Modified");

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            start = end;
            end = end.plusHours(3);

        } else {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has NOT passed!");
        }

    }

    Log.i(TAG, "downloadProgramGuide : interval=" + new Interval(startDownloading, new DateTime()).toString());

    Log.v(TAG, "downloadProgramGuide : exit");
}

From source file:org.mythtv.service.guide.v26.ProgramGuideHelperV26.java

private static void downloadProgramGuide(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadProgramGuide : enter");

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ProgramHelperV26.getInstance().deletePrograms(context, locationProfile, ops,
            ProgramConstants.CONTENT_URI_GUIDE, ProgramConstants.TABLE_NAME_GUIDE);
    RecordingHelperV26.getInstance().deleteRecordings(context, locationProfile, ops, ContentDetails.GUIDE);

    DateTime startDownloading = new DateTime();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int downloadDays = Integer.parseInt(sp.getString("preference_program_guide_days", "14"));
    Log.v(TAG, "downloadProgramGuide : downloadDays=" + downloadDays);

    DateTime start = new DateTime(DateTimeZone.getDefault()).withTimeAtStartOfDay();
    DateTime end = start.plusHours(3);/*  w  w  w. ja v  a2s  . com*/
    for (int i = 0; i < ((downloadDays * 24) / 3); i++) {
        Log.i(TAG,
                "downloadProgramGuide : starting download for [" + (i + 1) + " of " + ((downloadDays * 24) / 3)
                        + "] "
                        + DateUtils.getDateTimeUsingLocaleFormattingPretty(start,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType())
                        + ", end time=" + DateUtils.getDateTimeUsingLocaleFormattingPretty(end,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType()));

        EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
                "GetProgramGuide", String.valueOf(i));
        Log.d(TAG, "downloadProgramGuide : etag=" + etag.getValue());

        if (null == etag.getDate() || start.isAfter(etag.getDate())) {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has passed");

            ResponseEntity<ProgramGuide> responseEntity = mMythServicesTemplate.guideOperations()
                    .getProgramGuide(start, end, 1, null, false, etag);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 200 OK");
                ProgramGuide programGuide = responseEntity.getBody();

                if (null != programGuide) {

                    if (null != programGuide) {
                        load(context, locationProfile, programGuide);
                    }

                }

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setEndpoint("GetProgramGuide");
                    etag.setDataId(i);
                    etag.setDate(locationProfile.getNextMythFillDatabase());
                    etag.setMasterHostname(locationProfile.getHostname());
                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 304 Not Modified");

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            start = end;
            end = end.plusHours(3);

        } else {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has NOT passed!");
        }

    }

    Log.i(TAG, "downloadProgramGuide : interval=" + new Interval(startDownloading, new DateTime()).toString());

    Log.v(TAG, "downloadProgramGuide : exit");
}

From source file:org.mythtv.service.guide.v27.ProgramGuideHelperV27.java

private static void downloadProgramGuide(final Context context, final LocationProfile locationProfile)
        throws MythServiceApiRuntimeException, RemoteException, OperationApplicationException {
    Log.v(TAG, "downloadProgramGuide : enter");

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ProgramHelperV27.getInstance().deletePrograms(context, locationProfile, ops,
            ProgramConstants.CONTENT_URI_GUIDE, ProgramConstants.TABLE_NAME_GUIDE);
    RecordingHelperV27.getInstance().deleteRecordings(context, locationProfile, ops, ContentDetails.GUIDE);

    DateTime startDownloading = new DateTime();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    int downloadDays = Integer.parseInt(sp.getString("preference_program_guide_days", "14"));
    Log.v(TAG, "downloadProgramGuide : downloadDays=" + downloadDays);

    DateTime start = new DateTime(DateTimeZone.getDefault()).withTimeAtStartOfDay();
    DateTime end = start.plusHours(3);/*from  w  w  w. ja v a 2s .com*/
    for (int i = 0; i < ((downloadDays * 24) / 3); i++) {
        Log.i(TAG,
                "downloadProgramGuide : starting download for [" + (i + 1) + " of " + ((downloadDays * 24) / 3)
                        + "] "
                        + DateUtils.getDateTimeUsingLocaleFormattingPretty(start,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType())
                        + ", end time=" + DateUtils.getDateTimeUsingLocaleFormattingPretty(end,
                                mMainApplication.getDateFormat(), mMainApplication.getClockType()));

        EtagInfoDelegate etag = mEtagDaoHelper.findByEndpointAndDataId(context, locationProfile,
                "GetProgramGuide", String.valueOf(i));
        Log.d(TAG, "downloadProgramGuide : etag=" + etag.getValue());

        if (null == etag.getDate() || start.isAfter(etag.getDate())) {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has passed");

            ResponseEntity<ProgramGuide> responseEntity = mMythServicesTemplate.guideOperations()
                    .getProgramGuide(start, end, 1, null, false, etag);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 200 OK");
                ProgramGuide programGuide = responseEntity.getBody();

                if (null != programGuide) {

                    if (null != programGuide) {
                        load(context, locationProfile, programGuide);
                    }

                }

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setEndpoint("GetProgramGuide");
                    etag.setDataId(i);
                    etag.setDate(locationProfile.getNextMythFillDatabase());
                    etag.setMasterHostname(locationProfile.getHostname());
                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            if (responseEntity.getStatusCode().equals(HttpStatus.NOT_MODIFIED)) {
                Log.i(TAG, "downloadProgramGuide : GetProgramGuide returned 304 Not Modified");

                if (null != etag.getValue()) {
                    Log.i(TAG, "downloadProgramGuide : saving etag: " + etag.getValue());

                    etag.setLastModified(new DateTime(DateTimeZone.UTC));
                    mEtagDaoHelper.save(context, locationProfile, etag);
                }

            }

            start = end;
            end = end.plusHours(3);

        } else {
            Log.v(TAG, "downloadProgramGuide : next mythfilldatabase has NOT passed!");
        }

    }

    Log.i(TAG, "downloadProgramGuide : interval=" + new Interval(startDownloading, new DateTime()).toString());

    Log.v(TAG, "downloadProgramGuide : exit");
}

From source file:de.zib.gndms.gndmc.gorfx.AbstractTaskFlowExecClient.java

/**
 * Polls a running task, until its either finished or failed.
 *
 * @param taskSpecifier The specifier of the task.
 * @param statusHandler The handler for the task status, can update some sort of UI.
 * @param taskClient  The task client, which should be used for polling.
 * @param pollingDelay The pollingDelay, its the delay between polling.
 * @param dn  The user DN.//from   w w  w. j  a  v a  2 s. com
 * @param wid The workflow id.
 *
 * @return The final task status, finished or failed.
 */
public static TaskStatus waitForFinishOrFail(final Specifier<Facets> taskSpecifier,
        final TaskStatusHandler statusHandler, final TaskClient taskClient, final long pollingDelay,
        final String dn, final String wid) {

    TaskStatus ts;
    String taskId = taskSpecifier.getUriMap().get("taskId");

    ResponseEntity<TaskStatus> stat;
    boolean done = false;
    do {
        // queries the status of the task execution
        stat = taskClient.getStatus(taskId, dn, wid);
        if (!HttpStatus.OK.equals(stat.getStatusCode()))
            throw new RuntimeException("Task::getStatus failed " + stat.getStatusCode().name());
        ts = stat.getBody();

        // allows the implementor to do something with the task status
        statusHandler.handleStatus(ts);
        try {
            Thread.sleep(pollingDelay);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // finished without an error, good(?)
        if (finished(ts)) {
            // collect the result
            ResponseEntity<TaskResult> tr = null;
            try {
                tr = taskClient.getResult(taskId, dn, wid);
            } catch (HttpClientErrorException e) {
                if (404 == e.getStatusCode().value())
                    continue;
            }

            if (!HttpStatus.OK.equals(tr.getStatusCode()))
                throw new RuntimeException("Failed to obtain task result " + tr.getStatusCode().name());

            // do something with it
            statusHandler.handleResult(tr.getBody());

            done = true;
        } else if (failed(ts)) { // must be failed, not so good
            // find out way
            ResponseEntity<TaskFailure> tf = taskClient.getErrors(taskId, dn, wid);
            if (!HttpStatus.OK.equals(tf.getStatusCode()))
                throw new RuntimeException("Failed to obtain task errors " + tf.getStatusCode().name());

            // handle the failure
            statusHandler.handleFailure(tf.getBody());

            done = true;
        }
    } while (!done); // run 'til the task hits a final state

    return ts;
}

From source file:main.ScorePipeline.java

/**
 * Send an event to the google analytics server for tool start monitoring.
 *///w  w w . ja  va2s  .  c o m
private static void sendAnalyticsEvent() {
    String COLLECT_URL = "http://www.google-analytics.com/collect";
    String POST = "v=1&tid=UA-36198780-13&cid=35119a79-1a05-49d7-b876-bb88420f825b&uid=asuueffeqqss&t=event&ec=usage&ea=toolstart&el=spectrumsimilarity";

    //spring rest template
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> request = new HttpEntity<>(POST);
    ResponseEntity<String> postForEntity = restTemplate.postForEntity(COLLECT_URL, request, String.class);

    if (postForEntity.getStatusCode().equals(HttpStatus.OK)) {
        LOGGER.info("Successfully sent analytics event.");
    }
}