Example usage for org.springframework.http HttpMethod PUT

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

Introduction

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

Prototype

HttpMethod PUT

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

Click Source Link

Usage

From source file:org.cloudfoundry.identity.api.web.AppsIntegrationTests.java

/**
 * tests a happy-day flow of the native application profile.
 *//*from ww  w.  ja v a  2 s  .com*/
@Test
public void testHappyDay() throws Exception {

    RestOperations restTemplate = serverRunning.createRestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(serverRunning.getUrl("/api/apps"),
            String.class);
    // first make sure the resource is actually protected.
    assertNotSame(HttpStatus.OK, response.getStatusCode());
    HttpHeaders approvalHeaders = new HttpHeaders();
    OAuth2AccessToken accessToken = context.getAccessToken();
    approvalHeaders.set("Authorization", "bearer " + accessToken.getValue());
    Date oneMinuteAgo = new Date(System.currentTimeMillis() - 60000);
    Date expiresAt = new Date(System.currentTimeMillis() + 60000);
    ResponseEntity<Approval[]> approvals = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/uaa/approvals"), HttpMethod.PUT,
            new HttpEntity<Approval[]>((new Approval[] {
                    new Approval(testAccounts.getUserName(), "app", "cloud_controller.read", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "openid", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo),
                    new Approval(testAccounts.getUserName(), "app", "password.write", expiresAt,
                            ApprovalStatus.APPROVED, oneMinuteAgo) }),
                    approvalHeaders),
            Approval[].class);
    assertEquals(HttpStatus.OK, approvals.getStatusCode());

    ResponseEntity<String> result = serverRunning.getForString("/api/apps");
    assertEquals(HttpStatus.OK, result.getStatusCode());
    String body = result.getBody();
    assertTrue("Wrong response: " + body, body.contains("dsyerapi.cloudfoundry.com"));

}

From source file:com.orange.ngsi.client.NgsiRestClient.java

/**
 * Append attributes to a context element
 * @param url the URL of the broker//  w  ww.  j a v a2  s  .c o m
 * @param httpHeaders the HTTP header to use, or null for default
 * @param entityID the ID of the entity
 * @param updateContextElement attributes to update
 * @return a future for an UpdateContextElementResponse
 */
public ListenableFuture<UpdateContextElementResponse> updateContextElement(String url, HttpHeaders httpHeaders,
        String entityID, UpdateContextElement updateContextElement) {
    return request(HttpMethod.PUT, url + entitiesPath + entityID, httpHeaders, updateContextElement,
            UpdateContextElementResponse.class);
}

From source file:org.springbyexample.contact.web.client.AbstractPersistenceClient.java

@Override
public R update(S request) {
    R response = null;/*from   w  w  w. j  a v  a 2  s  . co  m*/

    String url = client.createUrl(updateRequest);

    logger.debug("REST client update.  id={}  url='{}'", request.getId(), url);

    Map<String, Long> vars = createPkVars(request.getId());

    response = client.getRestTemplate()
            .exchange(url, HttpMethod.PUT, new HttpEntity(request), responseClazz, vars).getBody();

    return response;
}

From source file:com.onyxscheduler.domain.HttpJobExecutionIT.java

@Test
public void shouldSendSpecifiedMethodToServerWhenRunWithNonDefaultMethod() {
    job.setMethod(HttpMethod.PUT);
    job.run();
    verify(putRequestedFor(urlEqualTo(TEST_PATH)));
}

From source file:net.prasenjit.auth.config.SecurityConfig.java

/**
 * {@inheritDoc}//ww w  .jav a2 s . com
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    //@formatter:off
    http.csrf().csrfTokenRepository(csrfTokenRepository()).and().exceptionHandling()
            .accessDeniedHandler(ajaxAwareHandler).authenticationEntryPoint(ajaxAwareHandler).and().formLogin()
            .loginPage("/login").permitAll().loginProcessingUrl("/api/login").successHandler(ajaxAwareHandler)
            .failureHandler(ajaxAwareHandler).and().logout().logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxAwareHandler).invalidateHttpSession(true).permitAll().and()
            .authorizeRequests().antMatchers(HttpMethod.PUT, "/api/user").anonymous().anyRequest()
            .authenticated().and().addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class);
    //@formatter:on
}

From source file:example.company.SecurityConfiguration.java

/**
 * This section defines the security policy for the app.
 * <p>/*from   ww  w  .java 2  s. c om*/
 * <ul>
 * <li>BASIC authentication is supported (enough for this REST-based demo).</li>
 * <li>/employees is secured using URL security shown below.</li>
 * <li>CSRF headers are disabled since we are only testing the REST interface, not a web one.</li>
 * </ul>
 * NOTE: GET is not shown which defaults to permitted.
 *
 * @param http
 * @throws Exception
 * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.httpBasic().and().authorizeRequests().//
            antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN").//
            antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN").//
            antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN").and().//
            csrf().disable();
}

From source file:com.onyxscheduler.domain.HttpJobJsonSerializationIT.java

private HttpJob buildJobWithNonDefaultParameters(UUID id) throws MalformedURLException {
    HttpJob expectedJob = new HttpJob();
    expectedJob.setId(id);//from  w w  w .  j a v  a  2 s  .c om
    expectedJob.setName("httpJobWithNonDefaultParams");
    //This is just to avoid a different ID to make the assert fail
    expectedJob.setUrl(new URL("http://localhost/test"));
    expectedJob.setMethod(HttpMethod.PUT);
    expectedJob.setHeaders(ImmutableMap.of("Content-Type", "application/json"));
    expectedJob.setBody("{\"field\":\"value\"}");
    expectedJob.setTriggers(ImmutableSet.of(TriggerTestUtils.buildTriggerWithCron()));
    return expectedJob;
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategyTest.java

@Test
public void testUploadDataSet() throws IOException, URISyntaxException, ResponseStatusException {

    final String data_id = "data-id=00987123";
    mockServer.expect(requestTo(/*from  w  w w .  j  av a  2  s.com*/
            "https://my.eu1.fredhopperservices.com:443/fas:test1/data/input/data.zip?checksum=ecd92758bc155e9bcd73bff5cb847687"))
            .andExpect(method(HttpMethod.PUT))
            .andRespond(withCreatedEntity(new URI(
                    "https://my.eu1.fredhopperservices.com:443/fas:test1/data/input/2001-01-01_21-12-21/"))
                            .body(data_id));

    final File file = new File(getClass().getResource("/data-test.zip").getFile());
    final String response = strategy.uploadDataSet(config, file);
    Assert.assertEquals(data_id, response);
}

From source file:com.bradley.musicapp.test.restapi.TrackRestControllerTest.java

@Test
public void testTrackUpdate() {
    ctx = new AnnotationConfigApplicationContext(ConnectionConfigTest.class);
    trackService = ctx.getBean(TrackFindService.class);
    // LEFT AS AN EXERCISE FOR YOU
    // GET THE TRACK and THEN CHANGE AND MAKE A COPY
    //THEN SEND TO THE SERVER USING A PUT OR POST
    // THEN READ BACK TO SEE IF YOUR CHANGE HAS HAPPENED
    System.out.println("id = " + id);
    System.out.println("track = " + trackService);
    Track foundTrack = trackService.find(id);
    Track track = new Track.Builder().track(foundTrack).trackName("lollipop").trackLength("02:22").build();

    HttpEntity<Track> requestEntity = new HttpEntity<>(track, getContentType());
    //        Make the HTTP POST request, marshaling the request to JSON, and the response to a String
    ResponseEntity<String> responseEntity = restTemplate.exchange(URL + "api/track/update", HttpMethod.PUT,
            requestEntity, String.class);
    System.out.println(" THE RESPONSE BODY " + responseEntity.getBody());
    System.out.println(" THE RESPONSE STATUS CODE " + responseEntity.getStatusCode());
    System.out.println(" THE RESPONSE IS HEADERS " + responseEntity.getHeaders());

    Track foundTrack1 = trackService.find(id);
    System.out.println("updated track = " + track + " | original track = " + foundTrack1);
    Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);

}

From source file:com.tservice.Logica.PersistenceFacede.java

public void realizarPago(Licencias licencia, InformacionPago pago) throws tserviceExceptions, Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<>(headers);
    String url = "http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/" + pago.getNumeroTarjeta() + "/"
            + pago.getNombreTarjeta() + "/Credito/" + pago.getCodigoSeguridad() + "/"
            + usuarioactivo.getCorreo() + "/monto/" + (int) licencia.getValor()
            + "/seguridad/2/TService?servicio=pago";
    //http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/4916701440291035/Visa/Credito/9209/asd@asd.com/monto/1000/seguridad/2/TService?api=api2
    ResponseEntity<Object> resultado = rest.exchange(url, HttpMethod.PUT, HttpEntity.EMPTY, Object.class);
    //http://serviciosrest.cloudhub.io/rest/PAYPAL/pago/tarjeta/4916701440291035/Visa/Credito/9209/asd@asd.com/monto/30/seguridad/2/TService?servicio=pago
    String resu = resultado.getBody().toString();

    resu = resu.replace("{", "");
    resu = resu.replace("}", "");

    ResultadoTransaccion result = new ResultadoTransaccion(resu.split(",")[0].split("=")[1],
            Integer.parseInt(resu.split(",")[1].split("=")[1]));

    if (result.getCodTransaccion() == 0) {
        throw new tserviceExceptions("La tarjeta es invalida o el saldo es insuficiente por favor verifique");
    } else/*  w  w  w.j  a v a 2s  .co m*/
        resultadoTransaccion(result.getCodTransaccion(), licencia);
}