Example usage for org.springframework.web.client RestTemplate getForObject

List of usage examples for org.springframework.web.client RestTemplate getForObject

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate getForObject.

Prototype

@Override
    @Nullable
    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException 

Source Link

Usage

From source file:org.projecthdata.ehr.viewer.service.PatientSyncService.java

private void doSyncPatientInfo() {
    this.editor = prefs.edit();
    editor.putString(Constants.PREF_PATIENT_INFO_SYNC_STATE, SyncState.WORKING.toString()).commit();

    try {//from w  w w.  j  ava2  s  . co  m
        Dao<RootEntry, Integer> rootDao = hDataOrmManager.getDatabaseHelper().getRootEntryDao();
        Dao<SectionDocMetadata, Integer> sectionDao = hDataOrmManager.getDatabaseHelper()
                .getSectionDocMetadataDao();

        // find the first entry that has the right schema and contains xml documents
        RootEntry entry = rootDao.queryForFirst(
                rootDao.queryBuilder().where().eq(RootEntry.COLUMN_NAME_EXTENSION, Constants.EXTENSION_PATIENT)
                        .and().eq(RootEntry.COLUMN_NAME_CONTENT_TYPE, MediaType.APPLICATION_XML).prepare());

        //find the metadata for the first xml document in the section owned by the previous found root entry
        SectionDocMetadata metadata = sectionDao
                .queryForFirst(sectionDao.queryBuilder().where().eq("rootEntry_id", entry.get_id()).and()
                        .eq("contentType", MediaType.APPLICATION_XML).prepare());

        // grab that document and parse out the patient info
        Connection<HData> connection = connectionRepository.getPrimaryConnection(HData.class);

        RestTemplate restTemplate = connection.getApi().getRootOperations().getRestTemplate();

        Patient patientInfo = restTemplate.getForObject(metadata.getLink(), Patient.class);

        save(patientInfo);

        //get the url for their photo
        entry = rootDao.queryForFirst(
                rootDao.queryBuilder().where().eq(RootEntry.COLUMN_NAME_EXTENSION, Constants.EXTENSION_PNG)
                        .and().eq(RootEntry.COLUMN_NAME_CONTENT_TYPE, MediaType.IMAGE_PNG).prepare());
        if (entry != null) {
            metadata = sectionDao.queryForFirst(sectionDao.queryBuilder().where()
                    .eq("rootEntry_id", entry.get_id()).and().eq("contentType", MediaType.IMAGE_PNG).prepare());

            this.editor.putString(Constants.PREF_PATIENT_PHOTO_URL, metadata.getLink());
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    this.editor.putString(Constants.PREF_PATIENT_INFO_SYNC_STATE, SyncState.READY.toString());
    //committing all of the changes 
    this.editor.commit();
}

From source file:com.netflix.genie.web.configs.aws.AwsMvcConfigUnitTests.java

/**
 * Make sure we get IPv4 hostname if public hostname fails.
 *
 * @throws IOException on any problem/*  www.j  a v  a  2  s  . c om*/
 */
@Test
@SuppressWarnings("unchecked")
public void canGetIPv4Hostname() throws IOException {
    final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
    final String hostname = UUID.randomUUID().toString();
    Mockito.when(restTemplate.getForObject(this.awsMvcConfig.publicHostNameGet, String.class))
            .thenThrow(Exception.class);

    Mockito.when(restTemplate.getForObject(this.awsMvcConfig.localIPV4HostNameGet, String.class))
            .thenReturn(hostname);

    Assert.assertThat(this.awsMvcConfig.hostName(restTemplate), Matchers.is(hostname));
    Mockito.verify(restTemplate, Mockito.times(1)).getForObject(awsMvcConfig.publicHostNameGet, String.class);
    Mockito.verify(restTemplate, Mockito.times(1)).getForObject(awsMvcConfig.localIPV4HostNameGet,
            String.class);
}

From source file:com.venilnoronha.dzone.feed.fetcher.ArticlesFetcher.java

private ArticlesResponse fetchArticles(int portal, Integer from, Integer page) {
    StringBuilder api = new StringBuilder(ARTICLES_API);
    api.append("&portal=").append(portal);
    if (from != null) {
        api.append("&from=").append(from);
    }/* w w w . j av  a  2  s  .  c om*/
    if (page != null) {
        api.append("&page=").append(page);
    }
    RestTemplate restTemplate = new RestTemplate();
    ArticlesResponse articlesResponse = restTemplate.getForObject(api.toString(), ArticlesResponse.class);
    return articlesResponse;
}

From source file:com.provenance.cloudprovenance.connector.policy.PolicyEnforcementConnector.java

/** Method returns a policy response based on a repose URI as a string */
@Override/*from  ww  w  .  j ava  2  s.  com*/
public String policyResponse(String serviceId, URL policyResponseURI) {

    RestTemplate restTemplate = new RestTemplate();

    logger.info("Invoking URI: " + policyResponseURI);

    String policyResponse = restTemplate.getForObject(policyResponseURI.toExternalForm(), String.class);

    return policyResponse;
}

From source file:de.codecentric.boot.admin.services.SpringBootAdminRegistratorTask.java

/**
 * @see java.lang.Runnable#run()/*from w  ww .  j  a  va2 s. co m*/
 */
@Override
public void run() {
    try {
        String id = env.getProperty("info.id");
        int port = env.getProperty("server.port", Integer.class);
        String adminUrl = env.getProperty("spring.boot.admin.url");
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        ApplicationList list = template.getForObject(adminUrl + "/api/applications", ApplicationList.class);
        for (Application app : list) {
            if (id.equals(app.getId())) {
                // the application is already registered at the admin tool
                LOGGER.debug("Application already registered with ID '{}'", id);
                return;
            }
        }
        // register the application with the used URL and port
        String url = new URL("http", InetAddress.getLocalHost().getCanonicalHostName(), port, "").toString();
        Application app = new Application();
        app.setId(id);
        app.setUrl(url);
        template.postForObject(adminUrl + "/api/applications", app, String.class);
        LOGGER.info("Application registered itself at the admin application with ID '{}' and URL '{}'", id,
                url);
    } catch (Exception e) {
        LOGGER.warn("Failed to register application at spring-boot-admin, message={}", e.getMessage());
    }
}

From source file:com.github.cjm.service.BaseService.java

public ResourceCollection load(String resource, Class clazz, int page) {

    StringBuilder uri = new StringBuilder(MOVIEDB_URL);
    uri.append(resource);/*from w w w .  j a v a  2  s  . co m*/
    uri.append("?api_key=").append(apiKey);
    if (page > 1) {
        uri.append("&page=").append(page);
    }

    RestTemplate restTemplate = new RestTemplate();
    ResourceCollection<T> resourceCollection = new ResourceCollection<>();
    String data = null;
    try {
        data = restTemplate.getForObject(uri.toString(), String.class);
    } catch (HttpClientErrorException e) {
        log.warn(e.getMessage());
    }
    if (data != null) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            TypeFactory t = TypeFactory.defaultInstance();
            resourceCollection = mapper.readValue(data, t.constructType(clazz));
        } catch (IOException ex) {
            log.error("ObjectMapper exception: ", ex);
        }
    }
    return resourceCollection;
}

From source file:com.jskj.asset.client.login.LoginTask.java

@Override
protected Object doInBackground() throws Exception {
    try {/*from   w w  w. j  a v a  2  s. c o  m*/
        RestTemplate restTemplate = (RestTemplate) BeanFactory.instance().createBean(RestTemplate.class);

        if (logined) {
            ComResponse<String> com = restTemplate.getForObject(
                    java.net.URI.create(Constants.HTTP + Constants.APPID + "logout"), ComResponse.class);
            if (com.getResponseStatus() != ComResponse.STATUS_OK) {
                return new Exception("logout failed. ");
            } else {
                BaseTreePane.disTabCount.clear();
            }
        }

        Object userNameObj = map.get("userName");
        ;
        Object passwdObj = map.get("userPassword");

        HttpComponentsClientHttpRequestFactory httpRequestFactory = (HttpComponentsClientHttpRequestFactory) restTemplate
                .getRequestFactory();
        DefaultHttpClient httpClient = (DefaultHttpClient) httpRequestFactory.getHttpClient();
        String unicodeStr = UnicodeConverter.toEncodedUnicode(userNameObj.toString(), false);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(unicodeStr,
                passwdObj.toString());
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);

        UserSessionEntity session = restTemplate.getForObject(java.net.URI.create(URI),
                UserSessionEntity.class);

        return session;
    } catch (Exception e) {
        e.printStackTrace();
        return e;
    }
}

From source file:co.mafiagame.telegraminterface.inputhandler.UpdateController.java

@SuppressWarnings("InfiniteLoopStatement")
@PostConstruct//  w ww  .jav  a2  s .  c om
public void init() {
    Thread thread = new Thread(() -> {
        try {
            long offset = 1;
            Thread.sleep(TimeUnit.MINUTES.toMillis(2));
            while (true) {
                try {
                    RestTemplate restTemplate = new RestTemplate();
                    setErrorHandler(restTemplate);
                    TResult tResult = restTemplate.getForObject(
                            telegramUrl + telegramToken + "/getUpdates?offset=" + String.valueOf(offset + 1),
                            TResult.class);
                    for (TUpdate update : tResult.getResult()) {
                        if (offset < update.getId()) {
                            offset = update.getId();
                            if (Objects.nonNull(update.getMessage())) {
                                logger.info("receive: {}", update);
                                commandDispatcher.handle(update);
                            }
                            logger.info("offset set to {}", offset);
                        }
                    }
                    Thread.sleep(TimeUnit.MILLISECONDS.toMillis(500));
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    thread.start();
}

From source file:com.bytebybyte.mapquest.geocoding.service.standard.MapQuestTest.java

@Test
public void testGetDistanceUsingAddressCoordinates() {
    String location1 = "Dange Chowk, Pune, Maharashtra, 411033";
    String location2 = "Chapekar chowk, Pune, Maharashtra, 411019";

    String ADDRESSURL = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=";

    String finalUrl = ADDRESSURL + location1 + "&destinations=" + location2
            + "&mode=driving&language=en-EN&sensor=false";
    System.out.println(finalUrl);

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(finalUrl, String.class);
    System.out.println("Result : " + result);

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(result);

    JsonElement je = new JsonParser().parse(jsonObject.get("rows").toString());
    JsonArray jsonArray = je.getAsJsonArray();
    jsonObject = jsonArray.get(0).getAsJsonObject();

    JsonElement je1 = new JsonParser().parse(jsonObject.get("elements").toString());
    JsonArray jsonArray1 = je1.getAsJsonArray();
    jsonObject = jsonArray1.get(0).getAsJsonObject();

    JsonElement je2 = jsonObject.get("distance");
    JsonObject jo = je2.getAsJsonObject();
    System.out.println("Distance : " + jo.get("text"));

    Assert.assertEquals("OK", removeDoubleQuotes(jsonObject.get("status").toString()));
    Assert.assertEquals("2.7 km", removeDoubleQuotes(jo.get("text").toString()));
}