Example usage for org.springframework.http HttpMethod GET

List of usage examples for org.springframework.http HttpMethod GET

Introduction

In this page you can find the example usage for org.springframework.http HttpMethod GET.

Prototype

HttpMethod GET

To view the source code for org.springframework.http HttpMethod GET.

Click Source Link

Usage

From source file:org.openlmis.fulfillment.service.referencedata.ProgramReferenceDataServiceTest.java

@Test
public void shouldFindProgramsByIds() {
    // given// w w w  .ja  va 2 s  .c  o  m
    UUID id = UUID.randomUUID();
    UUID id2 = UUID.randomUUID();
    List<UUID> ids = Arrays.asList(id, id2);

    ProgramDto program = generateInstance();
    program.setId(id);
    ProgramDto anotherProgram = generateInstance();
    anotherProgram.setId(id2);

    Map<String, Object> payload = new HashMap<>();
    payload.put("id", ids);
    ResponseEntity response = mock(ResponseEntity.class);

    // when
    when(response.getBody()).thenReturn(new ProgramDto[] { program, anotherProgram });

    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            eq(service.getArrayResultClass()))).thenReturn(response);

    Collection<ProgramDto> programs = service.findByIds(ids);

    // then
    verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.GET), entityCaptor.capture(),
            eq(service.getArrayResultClass()));
    assertTrue(programs.contains(program));
    assertTrue(programs.contains(anotherProgram));

    String actualUrl = uriCaptor.getValue().toString();
    assertTrue(actualUrl.startsWith(service.getServiceUrl() + service.getUrl()));
    assertTrue(actualUrl.contains(id.toString()));
    assertTrue(actualUrl.contains(id2.toString()));

    assertAuthHeader(entityCaptor.getValue());
}

From source file:com.javiermoreno.springboot.rest.TokenSecurityAdapter.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
            // Filter order: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/apidocs/org/springframework/security/config/annotation/web/HttpSecurityBuilder.html#addFilter%28javax.servlet.Filter%29
            .addFilterAfter(authenticationTokenProcessingFilterBean(), BasicAuthenticationFilter.class)
            .authorizeRequests()/* ww w  . j  av  a 2 s  .  c o m*/
            .antMatchers("/api-docs/**", "/public/**", "/views/**", "/errores/**", "/health/**", "/metrics/**",
                    "/configprops/**")
            .permitAll().antMatchers(HttpMethod.GET, "/private/**").hasRole("ADMIN")
            .antMatchers(HttpMethod.GET, "/shutdown/**").hasRole("ADMIN")
            //.access("hasRole('ROLE_ADMIN')")
            .anyRequest().authenticated().and().httpBasic();
}

From source file:com.example.RestTemplateStoreGatherer.java

/**
 * Enhance a Store with some metadata. Blocking.
 *
 * @param store a Store to enhance//from ww w  . j a  v a2  s  . co  m
 * @return the enhanced store
 */
private Store meta(Store store) {
    Map<String, Object> map = this.restTemplate.exchange(url + "/stores/{id}", HttpMethod.GET, null,
            new ParameterizedTypeReference<Map<String, Object>>() {
            }, store.getId()).getBody();
    @SuppressWarnings("unchecked")
    Map<String, Object> meta = (Map<String, Object>) map.get("address");
    store.getMeta().putAll(meta);
    return store;
}

From source file:com.epam.reportportal.auth.integration.github.GitHubClient.java

private <T> T getForObject(String url, ParameterizedTypeReference<T> type, Object... urlVars) {
    return this.restTemplate.exchange(url, HttpMethod.GET, null, type, urlVars).getBody();
}

From source file:org.starfishrespect.myconsumption.android.tasks.StatValuesUpdater.java

public void refreshDB() {

    AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() {
        @Override/*  ww  w  . jav a 2  s .  c  o  m*/
        protected Void doInBackground(Void... params) {
            DatabaseHelper db = SingleInstance.getDatabaseHelper();
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<StatDTO[]> responseEnt;
            template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

            try {
                for (SensorData sensor : db.getSensorDao().queryForAll()) {
                    // Stats
                    String url = String.format(SingleInstance.getServerUrl() + "stats/sensor/%s",
                            sensor.getSensorId());

                    responseEnt = template.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders),
                            StatDTO[].class);
                    StatDTO[] statsArray = responseEnt.getBody();
                    List<StatDTO> stats = new ArrayList<>(Arrays.asList(statsArray));

                    ObjectMapper mapper = new ObjectMapper();

                    try {
                        String json = mapper.writeValueAsString(stats);
                        String key = "stats_" + sensor.getSensorId();

                        int id = db.getIdForKey(key);
                        KeyValueData valueData = new KeyValueData(key, json);
                        valueData.setId(id);

                        LOGD(TAG, "writing stat in local db: " + json);
                        db.getKeyValueDao().createOrUpdate(valueData);

                    } catch (IOException e) {
                        LOGD(TAG, "Cannot create stats " + stats.toString(), e);
                    }

                }
            } catch (SQLException e) {
                LOGD(TAG, "Cannot create stats ", e);
            } catch (ResourceAccessException | HttpClientErrorException e) {
                LOGE(TAG, "Cannot access server ", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (statUpdateFinishedCallback != null) {
                statUpdateFinishedCallback.onStatUpdateFinished();
            }
        }
    };

    task.execute();
}

From source file:de.muenchen.eaidemo.AbstractIntegrationTest.java

/**
 * @param requestMappingUrl should be exactly the same as defined in your
 * RequestMapping value attribute (including the parameters in {})
 * RequestMapping(value = yourRestUrl)//from w w w.  j  ava  2  s.c o  m
 * @param serviceReturnTypeClass should be the the return type of the
 * service
 * @param parametersInOrderOfAppearance should be the parameters of the
 * requestMappingUrl ({}) in order of appearance
 * @return the result of the service, or null on error
 */
protected <T> T getEntity(final String requestMappingUrl, final Class<T> serviceReturnTypeClass,
        final Object... parametersInOrderOfAppearance) {
    // Make a rest template do do the service call
    final TestRestTemplate restTemplate = new TestRestTemplate();
    // Add correct headers, none for this example
    final HttpEntity<String> requestEntity = new HttpEntity<String>(new HttpHeaders());
    try {
        // Do a call to the url
        final ResponseEntity<T> entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET,
                requestEntity, serviceReturnTypeClass, parametersInOrderOfAppearance);
        // Return result
        return entity.getBody();
    } catch (final Exception ex) {
        // Handle exceptions
    }
    return null;
}

From source file:com.acc.test.UserWebServiceTest.java

@Test()
public void testGetUserReviews_Success_JSON() {
    final HttpEntity<String> requestEntity = new HttpEntity<String>(getJSONHeaders());
    final ResponseEntity<String> response = template.exchange(
            "http://localhost:9001/rest/v1/users/{userid}/reviews", HttpMethod.GET, requestEntity, String.class,
            TestConstants.USERNAME);/*www .  java2 s.com*/
    assertEquals("application/json;charset=UTF-8", response.getHeaders().getContentType().toString());
}

From source file:com.appglu.impl.StorageTemplateTest.java

@Test
public void streamStorageFile() {
    downloadMockServer.expect(requestTo(URL)).andExpect(method(HttpMethod.GET))
            .andRespond(withStatus(HttpStatus.OK).body(CONTENT).headers(responseHeaders));

    this.storageOperations.streamStorageFile(new StorageFile(URL), new InputStreamCallback() {
        public void doWithInputStream(InputStream inputStream) throws IOException {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, outputStream);

            Assert.assertEquals(new String(CONTENT), new String(outputStream.toByteArray()));
        }/*w w  w .j  a v a 2  s  .c o m*/
    });

    downloadMockServer.verify();
}

From source file:com.cloudera.nav.plugin.client.NavApiCient.java

/**
 * Call the Navigator API and retrieve all available sources
 *
 * @return a collection of available sources
 *//*from  w  ww. j av  a  2 s. com*/
public Collection<Source> getAllSources() {
    RestTemplate restTemplate = new RestTemplate();
    String url = getSourceUrl();
    HttpHeaders headers = getAuthHeaders();
    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<SourceAttrs[]> response = restTemplate.exchange(url, HttpMethod.GET, request,
            SourceAttrs[].class);
    Collection<Source> sources = Lists.newArrayList();
    for (SourceAttrs info : response.getBody()) {
        sources.add(info.createSource());
    }
    return sources;
}

From source file:at.create.android.ffc.http.FormBasedAuthentication.java

/**
 * Authentication via username and password.
 * @return True if the authentication succeeded, otherwise false is returned.
 *//*w w  w  .j  a  va2  s  . c om*/
public boolean authenticate() {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("authentication[username]", username);
    formData.add("authentication[password]", password);
    formData.add("authentication[remember_me]", "1");

    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.postForLocation(getUrl(), formData);

    if (CookiePreserveHttpRequestInterceptor.getInstance().hasCookieWithName("user_credentials")) {
        return true;
        // Try with another method
    } else {
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(baseUri, HttpMethod.GET, requestEntity,
                String.class);

        return !responseEntity.getBody().toString().contains("authentication[username]");
    }
}