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.zalando.boot.etcd.EtcdClient.java

/**
 * Sets the value of the node with the given key in etcd.
 * //from w w  w.j  a  v a2  s  .com
 * @param key
 *            the node's key
 * @param value
 *            the node's value
 * @param ttl
 *            the node's time-to-live or <code>-1</code> to unset existing
 *            ttl
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse put(String key, String value, int ttl) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("ttl", ttl == -1 ? "" : ttl);

    MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(1);
    payload.set("value", value);

    return execute(builder, HttpMethod.PUT, payload, EtcdResponse.class);
}

From source file:com.frequentis.maritime.mcsr.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    log.debug("Configuring HttpSecurity");
    log.debug("RememberMe service {}", rememberMeServices);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
            .addFilterBefore(basicAuthenticationFilter(), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakPreAuthActionsFilter()), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakAuthenticationProcessingFilter()),
                    X509AuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
            //            .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
            //            .exceptionHandling()
            //            .accessDeniedHandler(new CustomAccessDeniedHandler())
            //            .authenticationEntryPoint(authenticationEntryPoint)
            //        .and()
            .rememberMe().rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
            .key(jHipsterProperties.getSecurity().getRememberMe().getKey()).and().formLogin()
            .loginProcessingUrl("/api/authentication").successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").permitAll().and().logout().logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler).deleteCookies("JSESSIONID", "CSRF-TOKEN")
            .permitAll().and().headers().frameOptions().disable().and().authorizeRequests()
            .antMatchers("/api/register").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/api/elasticsearch/**").permitAll().antMatchers("/api/activate").permitAll()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/account/reset_password/inactivateit").permitAll()
            .antMatchers("/api/account/reset_password/finish").permitAll().antMatchers("/api/profile-info")
            .permitAll().antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/websocket/**").permitAll().antMatchers("/management/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/v2/api-docs/**").permitAll()
            .antMatchers(HttpMethod.PUT, "/api/**").authenticated().antMatchers(HttpMethod.POST, "/api/**")
            .authenticated().antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
            .antMatchers(HttpMethod.TRACE, "/api/**").authenticated().antMatchers(HttpMethod.HEAD, "/api/**")
            .authenticated().antMatchers(HttpMethod.PATCH, "/api/**").authenticated()
            .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll().antMatchers(HttpMethod.GET, "/api/**")
            .permitAll().antMatchers("/swagger-resources/configuration/ui").permitAll()
            .antMatchers("/swagger-ui/index.html").permitAll().and().csrf().disable();

}

From source file:org.zalando.boot.etcd.EtcdClientTest.java

@Test
public void compareAndSwapWithPrevExistAndUnsetTtl() throws EtcdException {
    server.expect(//from ww  w  .j av a2s.  com
            MockRestRequestMatchers.requestTo("http://localhost:2379/v2/keys/sample?ttl=&prevExist=false"))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.PUT))
            .andExpect(MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_FORM_URLENCODED))
            .andExpect(MockRestRequestMatchers.content().string("value=Hello+world")).andRespond(
                    MockRestResponseCreators.withSuccess(new ClassPathResource("EtcdClientTest_delete.json"),
                            MediaType.APPLICATION_JSON));

    EtcdResponse response = client.compareAndSwap("sample", "Hello world", -1, false);
    Assert.assertNotNull("response", response);

    server.verify();
}

From source file:de.zib.gndms.gndmc.dspace.test.MockRestTemplate.java

/**
 * Checks if the given HTTP method is allowed to be executed on the given url.
 * //w ww  .  j  a  v  a 2  s  .co  m
 * @param url The url the method shall be executed.
 * @param method The HTTP method.
 * @return true, if the method can be executed on the url, else false.
 */
private boolean validUrlMethod(final String url, final HttpMethod method) {
    if (url.matches(serviceURL + "/dspace")) {
        if (method.equals(HttpMethod.GET)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.PUT)
                || method.equals(HttpMethod.DELETE)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/config")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.PUT)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/slicekinds")) {
        if (method.equals(HttpMethod.GET)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/_\\w+")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.DELETE)
                || method.equals(HttpMethod.POST)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/_\\w+/_\\w+")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.DELETE)
                || method.equals(HttpMethod.POST)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/_\\w+/_\\w+/files")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/_\\w+/_\\w+/gsiftp")) {
        if (method.equals(HttpMethod.GET)) {
            return true;
        }
    }

    if (url.matches(serviceURL + "/dspace/_\\w+/_\\w+/_\\w+/_\\w+")) {
        if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.PUT)
                || method.equals(HttpMethod.DELETE)) {
            return true;
        }
    }
    return false;
}

From source file:com.orange.ngsi2.client.Ngsi2Client.java

/**
 * Replace all the existing attributes of an entity with a new set of attributes
 * @param entityId the entity ID//  w  w  w  . j  a va 2  s  .  co m
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attributes the new set of attributes
 * @return the listener to notify of completion
 */
public ListenableFuture<Void> replaceEntity(String entityId, String type, Map<String, Attribute> attributes) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}");
    addParam(builder, "type", type);
    return adapt(
            request(HttpMethod.PUT, builder.buildAndExpand(entityId).toUriString(), attributes, Void.class));
}

From source file:com.ge.predix.test.utils.UaaTestUtil.java

private BaseClientDetails createOrUpdateClient(final BaseClientDetails client) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    if (StringUtils.isNotEmpty(this.zone)) {
        headers.add("X-Identity-Zone-Id", "uaa");
    }//  www. jav a2 s.  c o m

    HttpEntity<String> postEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);

    ResponseEntity<String> clientCreate = null;
    try {
        clientCreate = this.adminRestTemplate.exchange(this.uaaUrl + "/oauth/clients", HttpMethod.POST,
                postEntity, String.class);
        if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
            return JSON_UTILS.deserialize(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException(
                    "Unexpected return code for client create: " + clientCreate.getStatusCode());
        }
    } catch (InvalidClientException ex) {
        if (ex.getMessage().equals("Client already exists: " + client.getClientId())) {
            HttpEntity<String> putEntity = new HttpEntity<String>(JSON_UTILS.serialize(client), headers);
            ResponseEntity<String> clientUpdate = this.adminRestTemplate.exchange(
                    this.uaaUrl + "/oauth/clients/" + client.getClientId(), HttpMethod.PUT, putEntity,
                    String.class);
            if (clientUpdate.getStatusCode() == HttpStatus.OK) {
                return JSON_UTILS.deserialize(clientUpdate.getBody(), BaseClientDetails.class);
            } else {
                throw new RuntimeException(
                        "Unexpected return code for client update: " + clientUpdate.getStatusCode());
            }
        }
    }
    throw new RuntimeException("Unexpected return code for client creation: " + clientCreate.getStatusCode());
}

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

@Test()
public void testPutProductByCode_Success_XML_Options_Review() {

    final PrincipalData principal = new PrincipalData();
    principal.setName(USER);//from w ww .ja  v a2  s.  c o  m
    principal.setUid(USER);

    final ReviewData review = new ReviewData();
    review.setAlias("alias message");
    review.setComment("comment here ");
    review.setHeadline("head line new");
    review.setPrincipal(principal);
    review.setDate(new Date());
    review.setRating(Double.valueOf(1));

    final HttpEntity<ReviewData> requestEntity = new HttpEntity<ReviewData>(review, getXMLHeaders());

    final ResponseEntity<ReviewData> response = template.exchange(URL + "/{code}/reviews", HttpMethod.PUT,
            requestEntity, ReviewData.class, TestConstants.PRODUCT_CODE);
    final ReviewData reviewData = response.getBody();

    Assert.assertNotNull(reviewData);

}

From source file:org.cloudfoundry.identity.uaa.integration.ScimUserEndpointsIntegrationTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from ww  w  .ja v  a 2 s .  c om
public void testJsonCaseInsensitivity() throws Exception {

    ResponseEntity<ScimUser> created = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = created.getBody();
    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<String, Object>(
            mapper.readValue(mapper.writeValueAsString(joe), Map.class));
    map.put("username", JOE + "0");
    map.remove("userName");
    ResponseEntity<ScimUser> response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}",
            HttpMethod.PUT, new HttpEntity<Map>(map, headers), ScimUser.class, joe.getId());
    ScimUser joe1 = response.getBody();
    assertEquals(JOE + "0", joe1.getUserName());
}

From source file:org.cloudfoundry.identity.uaa.integration.ClientAdminEndpointsIntegrationTests.java

@Test
public void testChangeSecret() throws Exception {
    headers = getAuthenticatedHeaders(//from  w  w w.j a v  a  2s  .com
            getClientCredentialsAccessToken("clients.read clients.write clients.secret"));
    BaseClientDetails client = createClient("client_credentials");

    client.setResourceIds(Collections.singleton("foo"));

    SecretChangeRequest change = new SecretChangeRequest();
    change.setOldSecret(client.getClientSecret());
    change.setSecret("newsecret");
    ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/clients/{client}/secret"), HttpMethod.PUT,
            new HttpEntity<SecretChangeRequest>(change, headers), Void.class, client.getClientId());
    assertEquals(HttpStatus.OK, result.getStatusCode());
}

From source file:gateway.controller.AlertTriggerController.java

/**
 * Update a Trigger//from w  ww.j av  a  2 s .c o  m
 * 
 * @see http://pz-swagger.stage.geointservices.io/#!/Trigger/put_trigger
 * 
 * @param dataId
 *            The Id of the resource
 * @param user
 *            the user submitting the request
 * @return OK if successful; error if not.
 */
@RequestMapping(value = "/trigger/{triggerId}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Update a Trigger", notes = "This will update the Trigger to either be enabled or disabled.", tags = {
        "Trigger", "Workflow" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Confirmation that the Trigger has been updated.", response = SuccessResponse.class),
        @ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = ErrorResponse.class),
        @ApiResponse(code = 404, message = "Not Found", response = ErrorResponse.class),
        @ApiResponse(code = 500, message = "Internal Error", response = ErrorResponse.class) })
public ResponseEntity<PiazzaResponse> updateMetadata(
        @ApiParam(value = "Id of the Trigger to update", required = true) @PathVariable(value = "triggerId") String triggerId,
        @ApiParam(value = "The object containing the boolean field to enable or disable", required = true) @Valid @RequestBody TriggerUpdate triggerUpdate,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s requested Update of information for %s.",
                gatewayUtil.getPrincipalName(user), triggerId), PiazzaLogger.INFO);

        // Proxy the request to Ingest
        try {
            return new ResponseEntity<PiazzaResponse>(
                    restTemplate.exchange(String.format("%s/%s/%s", WORKFLOW_URL, "trigger", triggerId),
                            HttpMethod.PUT, new HttpEntity<TriggerUpdate>(triggerUpdate), SuccessResponse.class)
                            .getBody(),
                    HttpStatus.OK);
        } catch (HttpClientErrorException | HttpServerErrorException hee) {
            LOGGER.error("Error Updating Trigger.", hee);
            return new ResponseEntity<PiazzaResponse>(
                    gatewayUtil.getErrorResponse(
                            hee.getResponseBodyAsString().replaceAll("}", " ,\"type\":\"error\" }")),
                    hee.getStatusCode());
        }
    } catch (Exception exception) {
        String error = String.format("Error Updating information for item %s by user %s: %s", triggerId,
                gatewayUtil.getPrincipalName(user), exception.getMessage());
        LOGGER.error(error, exception);
        logger.log(error, PiazzaLogger.ERROR);
        return new ResponseEntity<PiazzaResponse>(new ErrorResponse(error, "Gateway"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}