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.EtcdClientTest.java

@Test
public void compareAndSwapWithPrevIndexAndSetTtl() throws EtcdException {
    server.expect(MockRestRequestMatchers.requestTo("http://localhost:2379/v2/keys/sample?ttl=60&prevIndex=2"))
            .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", 60, 2);
    Assert.assertNotNull("response", response);

    server.verify();/*from  ww  w  .  j a v  a 2 s.  co m*/
}

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

/**
 * Atomically creates or updates a key-value pair in etcd.
 * // w w w. ja v a 2  s  . c  o  m
 * @param key
 *            the key
 * @param value
 *            the value
 * @param prevExist
 *            <code>true</code> if the existing node should be updated,
 *            <code>false</code> of the node should be created
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndSwap(final String key, final String value, boolean prevExist)
        throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("prevExist", prevExist);

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

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

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

@Test
public void updateUserGroupsDoesNothing() {
    ResponseEntity<ScimUser> response = createUser(JOE, "Joe", "User", "joe@blah.com");
    ScimUser joe = response.getBody();//from w w  w. j a  v a2 s  . c o m
    assertEquals(JOE, joe.getUserName());
    assertEquals(NUM_DEFAULT_GROUPS_ON_STARTUP, joe.getGroups().size());

    joe.setGroups(Arrays.asList(new ScimUser.Group(UUID.randomUUID().toString(), "uaa.admin")));

    HttpHeaders headers = new HttpHeaders();
    headers.add("If-Match", "\"" + joe.getVersion() + "\"");
    response = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}", HttpMethod.PUT,
            new HttpEntity<ScimUser>(joe, headers), ScimUser.class, joe.getId());
    ScimUser joe1 = response.getBody();
    assertEquals(JOE, joe1.getUserName());

    assertEquals(joe.getId(), joe1.getId());
    assertEquals(NUM_DEFAULT_GROUPS_ON_STARTUP, joe1.getGroups().size());
}

From source file:access.deploy.Deployer.java

/**
 * Deploys a GeoTIFF resource to GeoServer. This will create a new GeoServer data store and layer. This will upload
 * the file directly to GeoServer using the GeoServer REST API.
 * //from w  w  w .  ja v a2 s . c o m
 * @param dataResource
 *            The DataResource to deploy.
 * @return The Deployment
 * @throws InvalidInputException
 * @throws IOException
 * @throws AmazonClientException
 */
private Deployment deployRaster(DataResource dataResource)
        throws GeoServerException, IOException, InvalidInputException {
    // Get the File Bytes of the Raster to be uploaded
    byte[] fileBytes = accessUtilities.getBytesForDataResource(dataResource);

    // Create the Request that will upload the File
    authHeaders.add(HttpHeaders.CONTENT_TYPE, "image/tiff");
    HttpEntity<byte[]> request = new HttpEntity<>(fileBytes, authHeaders.get());

    // Send the Request
    String url = String.format("%s/rest/workspaces/piazza/coveragestores/%s/file.geotiff",
            accessUtilities.getGeoServerBaseUrl(), dataResource.getDataId());
    try {
        pzLogger.log(String.format("Creating new Raster Deployment to %s", url), Severity.INFORMATIONAL,
                new AuditElement(ACCESS, "deployGeoServerRasterLayer", dataResource.getDataId()));
        restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException exception) {
        if (exception.getStatusCode() == HttpStatus.METHOD_NOT_ALLOWED) {
            // If 405 NOT ALLOWED is encountered, then the layer may already exist on the GeoServer. Check if it
            // exists already. If it does, then use this layer for the Deployment.
            if (!doesGeoServerLayerExist(dataResource.getDataId())) {
                // If it doesn't exist, throw an error. Something went wrong.
                String error = String.format(
                        "GeoServer would not allow for layer creation, despite an existing layer not being present: url: %s, statusCode: %s, exceptionBody: %s",
                        url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
                pzLogger.log(error, Severity.ERROR);
                LOGGER.error(error, exception);
                throw new GeoServerException(error);
            }
        } else if ((exception.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR)
                && (exception.getResponseBodyAsString().contains("Error persisting"))) {
            // If a 500 is received, then it's possible that GeoServer is processing this layer already via a
            // simultaneous POST, and there is a collision. Add this information to the response.
            // TODO: In the future, we should persist a lookup table where only one Data ID is persisted at a time
            // to GeoServer, to avoid this collision.
            String error = String.format(
                    "Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s. This may be the result of GeoServer processing this Data Id simultaneously by another request. Please try again.",
                    url, exception.getStatusCode().toString(), exception.getResponseBodyAsString());
            pzLogger.log(error, Severity.ERROR,
                    new AuditElement(ACCESS, "failedToDeployRaster", dataResource.getDataId()));
            LOGGER.error(error, exception);
            throw new GeoServerException(error);
        } else {
            // For any other errors, report back this error to the user and fail the job.
            String error = String.format(
                    "Creating Layer on GeoServer at URL %s returned HTTP Status %s with Body: %s", url,
                    exception.getStatusCode().toString(), exception.getResponseBodyAsString());
            pzLogger.log(error, Severity.ERROR,
                    new AuditElement(ACCESS, "failedToDeployRaster", dataResource.getDataId()));
            LOGGER.error(error, exception);
            throw new GeoServerException(error);
        }
    }

    // Create a Deployment for this Resource
    String deploymentId = uuidFactory.getUUID();
    String capabilitiesUrl = String.format("%s%s", accessUtilities.getGeoServerBaseUrl(), CAPABILITIES_URL);
    String deploymentLayerName = dataResource.getDataId();
    return new Deployment(deploymentId, dataResource.getDataId(), accessUtilities.getGeoServerBaseUrl(), null,
            deploymentLayerName, capabilitiesUrl);
}

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

/**
 * Update the attribute of an entity/*from w ww  .  j  ava  2s  . c  om*/
 * @param entityId the entity ID
 * @param type optional entity type to avoid ambiguity when multiple entities have the same ID, null or zero-length for empty
 * @param attributeName the attribute name
 * @return
 */
public ListenableFuture<Void> updateAttribute(String entityId, String type, String attributeName,
        Attribute attribute) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}/attrs/{attributeName}");
    addParam(builder, "type", type);
    return adapt(request(HttpMethod.PUT, builder.buildAndExpand(entityId, attributeName).toUriString(),
            attribute, Void.class));
}

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

@Test
public void compareAndSwapWithPrevIndexAndUnsetTtl() throws EtcdException {
    server.expect(MockRestRequestMatchers.requestTo("http://localhost:2379/v2/keys/sample?ttl=&prevIndex=2"))
            .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, 2);
    Assert.assertNotNull("response", response);

    server.verify();//  w w  w .j a v a2  s .c o m
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java

/**
 * {@inheritDoc}//w w w  .ja v a  2s  . co  m
 */
@Override
public void upload(final EnricherJob job, final GeneratorResult result) throws Exception {
    String indexCollection = job.getDatabaseName();

    // Create a new update request

    List<Map<String, Object>> documents = ((MultiGeneratorResult<Map<String, Object>>) result).getDocuments();

    // Set a collection in case of a (resolvable) composite database name

    if (StringUtils.hasText(job.getDatabaseNameComposition())) {
        String compositeDatabaseName = determineAlternateDatabaseName(job.getDatabaseName(),
                job.getDatabaseNameComposition(), job.getDatabaseNamePrerequisitesExpression(),
                ((MultiGeneratorResult<Map<String, Object>>) result).getDocuments());

        if (compositeDatabaseName != null) {
            if (logger.isDebugEnabled())
                logger.debug(
                        format("Composite database name resolved to collection '%s'", compositeDatabaseName));

            indexCollection = compositeDatabaseName;
        } else {
            if (logger.isDebugEnabled())
                logger.debug(format(
                        "Composite database name could not be (completely) resolved - will use default collection '%s'",
                        job.getDatabaseName()));
        }
    }

    // Now perform the request

    String elasticSearchUri = getElasticSearchUri();

    ElasticSearchDomainConverter converter = new ElasticSearchDomainConverter(
            retrieveMetaData(elasticSearchUri, job));

    // Bulk it all together

    for (Map<String, Object> document : documents) {
        Map<String, Object> actualDocument = converter.convert(document);

        // Then add it to the index

        final String id = getReference(actualDocument);

        String encodedId = URLEncoder.encode(getReference(actualDocument), "UTF-8");
        String formattedUri = format("http://%s/%s/%s/%s", elasticSearchUri, indexCollection,
                job.getDatabaseType(), encodedId);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            XContentBuilder builder = XContentFactory.jsonBuilder(outputStream);

            try {
                builder.map(actualDocument);

                builder.flush();

                // Now send it on its way

                final String content = new String(outputStream.toByteArray(), "UTF-8");

                if (logger.isTraceEnabled())
                    logger.trace(format("Posting document to URL %s ... %s", formattedUri, content));

                HttpStatus status = operations.execute(formattedUri, HttpMethod.PUT, new RequestCallback() {
                    @Override
                    public void doWithRequest(final ClientHttpRequest request) throws IOException {
                        request.getBody().write(content.getBytes());
                    }
                }, new ResponseExtractor<HttpStatus>() {
                    @Override
                    public HttpStatus extractData(final ClientHttpResponse response) throws IOException {
                        return response.getStatusCode();
                    }
                });

                if (status.equals(HttpStatus.OK) || status.equals(HttpStatus.CREATED))
                    logger.info(format("Successfully added document %s to ElasticSearch index %s", id,
                            indexCollection));
                else
                    logger.error(
                            format("Failed to add document %s to ElasticSearch index %s", id, indexCollection));
            } finally {
                builder.close();
            }
        } catch (RestClientException e) {
            logger.error(format("Failed to add document %s to ElasticSearch index %s", id, indexCollection), e);
        } catch (ElasticSearchException e) {
            logger.error(format("Failed to add document %s to ElasticSearch index %s", id, indexCollection), e);
        }
    }

    // Perform direct notification now that the document(s) have been uploaded

    notifier.process(result);
}

From source file:com.citrix.g2w.webdriver.dependencies.AccountServiceQAIImpl.java

/**
 * Method used to create license for user account.
 * /*w w  w .jav a2 s. c  o  m*/
 * @param accountKey
 *            (user account key)
 * @param enabled
 *            (user enabled)
 * @param serviceType
 *            (user service type)
 * @param roles
 *            (user roles)
 * @param seats
 *            (user seats)
 * @param channel
 *            (user channel)
 * @return licenseKey
 */
private String createLicenseForAccount(final Long accountKey, final boolean enabled, final String serviceType,
        final String[] roles, final int seats, final String channel, int tier) {
    String licenseKey;

    try {
        JSONObject requestJson = new JSONObject();
        requestJson.put("enabled", enabled);
        requestJson.put("serviceType", serviceType);
        requestJson.put("description", "G2W License");
        requestJson.put("roles", roles);
        requestJson.put("seats", seats);
        requestJson.put("channel", channel);
        requestJson.put("tier", tier);

        HttpEntity entityLicense = new HttpEntity(requestJson.toString(), this.accountSvcHeaders);
        licenseKey = this.restTemplate.exchange(this.accountSvcUrl + "/accounts/" + accountKey + "/licenses",
                HttpMethod.POST, entityLicense, String.class).getBody();

        // Set maxAttendees on license for G2W
        JSONObject entitlementRequestJson = new JSONObject();
        entitlementRequestJson.put("maxAttendees", tier);
        this.restTemplate.exchange(this.accountSvcUrl + "/licenses/" + licenseKey + "/products/g2w",
                HttpMethod.PUT, new HttpEntity(entitlementRequestJson.toString(), this.accountSvcHeaders),
                null);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
    return licenseKey;
}

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

/**
 * Update a subscription//from ww  w  .j  a va  2 s  .  com
 * @param url the URL of the broker
 * @param httpHeaders the HTTP header to use, or null for default
 * @param subscriptionID the ID of the subscription to update
 * @param updateContextSubscription the parameters to update
 * @return a future for an UpdateContextSubscriptionResponse
 */
public ListenableFuture<UpdateContextSubscriptionResponse> updateContextSubscription(String url,
        HttpHeaders httpHeaders, String subscriptionID, UpdateContextSubscription updateContextSubscription) {
    return request(HttpMethod.PUT, url + subscriptionsPath + subscriptionID, httpHeaders,
            updateContextSubscription, UpdateContextSubscriptionResponse.class);
}

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

/**
 * Atomically creates or updates a key-value pair in etcd.
 * /*from  w w w.ja v a2 s. c om*/
 * @param key
 *            the key
 * @param value
 *            the value
 * @param ttl
 *            the time-to-live
 * @param prevExist
 *            <code>true</code> if the existing node should be updated,
 *            <code>false</code> of the node should be created
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndSwap(final String key, final String value, int ttl, boolean prevExist)
        throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("ttl", ttl == -1 ? "" : ttl);
    builder.queryParam("prevExist", prevExist);

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

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