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.uaa.integration.util.IntegrationTestUtils.java

public static BaseClientDetails createOrUpdateClient(String adminToken, String url, String switchToZoneId,
        BaseClientDetails client) throws Exception {

    RestTemplate template = new RestTemplate();
    template.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override/*from  w w w.  ja  v  a  2 s.c o m*/
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.is5xxServerError();
        }
    });
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", APPLICATION_JSON_VALUE);
    headers.add("Authorization", "bearer " + adminToken);
    headers.add("Content-Type", APPLICATION_JSON_VALUE);
    if (StringUtils.hasText(switchToZoneId)) {
        headers.add(IdentityZoneSwitchingFilter.HEADER, switchToZoneId);
    }
    HttpEntity getHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
    ResponseEntity<String> clientCreate = template.exchange(url + "/oauth/clients", HttpMethod.POST, getHeaders,
            String.class);
    if (clientCreate.getStatusCode() == HttpStatus.CREATED) {
        return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
    } else if (clientCreate.getStatusCode() == HttpStatus.CONFLICT) {
        HttpEntity putHeaders = new HttpEntity(JsonUtils.writeValueAsBytes(client), headers);
        ResponseEntity<String> clientUpdate = template.exchange(url + "/oauth/clients/" + client.getClientId(),
                HttpMethod.PUT, putHeaders, String.class);
        if (clientUpdate.getStatusCode() == HttpStatus.OK) {
            return JsonUtils.readValue(clientCreate.getBody(), BaseClientDetails.class);
        } else {
            throw new RuntimeException("Invalid update return code:" + clientUpdate.getStatusCode());
        }
    }
    throw new RuntimeException("Invalid crete return code:" + clientCreate.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static BaseClientDetails updateClient(RestTemplate template, String url, BaseClientDetails client)
        throws Exception {

    ResponseEntity<BaseClientDetails> response = template.exchange(url + "/oauth/clients/{clientId}",
            HttpMethod.PUT, new HttpEntity<>(client), BaseClientDetails.class, client.getClientId());

    return response.getBody();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static IdentityProvider createOrUpdateProvider(String accessToken, String url,
        IdentityProvider provider) {//from   www.  j  a v a 2  s  .  c o m
    RestTemplate client = new RestTemplate();
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", APPLICATION_JSON_VALUE);
    headers.add("Authorization", "bearer " + accessToken);
    headers.add("Content-Type", APPLICATION_JSON_VALUE);
    headers.add(IdentityZoneSwitchingFilter.HEADER, provider.getIdentityZoneId());
    List<IdentityProvider> existing = getProviders(accessToken, url, provider.getIdentityZoneId());
    if (existing != null) {
        for (IdentityProvider p : existing) {
            if (p.getOriginKey().equals(provider.getOriginKey())
                    && p.getIdentityZoneId().equals(provider.getIdentityZoneId())) {
                provider.setId(p.getId());
                HttpEntity putHeaders = new HttpEntity(provider, headers);
                ResponseEntity<String> providerPut = client.exchange(url + "/identity-providers/{id}",
                        HttpMethod.PUT, putHeaders, String.class, provider.getId());
                if (providerPut.getStatusCode() == HttpStatus.OK) {
                    return JsonUtils.readValue(providerPut.getBody(), IdentityProvider.class);
                }
            }
        }
    }

    HttpEntity postHeaders = new HttpEntity(provider, headers);
    ResponseEntity<String> providerPost = client.exchange(url + "/identity-providers/{id}", HttpMethod.POST,
            postHeaders, String.class, provider.getId());
    if (providerPost.getStatusCode() == HttpStatus.CREATED) {
        return JsonUtils.readValue(providerPost.getBody(), IdentityProvider.class);
    }
    throw new IllegalStateException(
            "Invalid result code returned, unable to create identity provider:" + providerPost.getStatusCode());
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

@Override
public <E extends Locatable> void update(E entity) {
    if (entity == null) {
        throw new IllegalArgumentException("entity cannot be null");
    }/*from   w ww .j  a  va 2  s  .c om*/
    if (entity.getUri() == null) {
        throw new IllegalArgumentException("entity has no URI set. It may need to be created first.");
    }

    Class<? extends Locatable> entityClass = entity.getClass();
    GenologicsEntity entityAnno = checkEntityAnnotated(entityClass);

    if (!entityAnno.updateable()) {
        throw new GenologicsUpdateException(getShortClassName(entityClass) + " cannot be updated.");
    }

    assert entityAnno.primaryEntity() == void.class : entityClass.getName()
            + " has a primary entity set, but such things cannot be created through the API.";

    ResponseEntity<? extends Locatable> response = restClient.exchange(entity.getUri(), HttpMethod.PUT,
            new HttpEntity<Locatable>(entity), entity.getClass());

    reflectiveUpdate(entity, response.getBody());
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Update entities in Clarity with the entity objects given here. The objects are
 * updated in-situ, so any changes made in the server will be pushed into the
 * objects in the collection.//from   w w w  . j av a2 s .  c  om
 *
 * <p>Uses the bulk create mechanism where it is available for the entity.</p>
 *
 * @param entities The collection of entities to update.
 *
 * @param <E> The type of the entity.
 * @param <BH> The type of the object that is sent to perform the bulk update.
 *
 * @throws IllegalArgumentException if {@code entities} contains a null value or
 * an entity that already exists in the API (i.e. has a URI).
 *
 * @throws GenologicsUpdateException if the entities cannot be updated via the API
 * (as determined by the {@link GenologicsEntity#updateable()} flag).
 */
private <E extends Locatable, BH extends BatchUpdate<E>> void doUpdateAll(Collection<E> entities) {
    if (entities != null && !entities.isEmpty()) {
        Class<E> entityClass = checkCollectionHomogeneousAndUnique(entities, true);

        GenologicsEntity entityAnno = checkEntityAnnotated(entityClass);

        if (!entityAnno.updateable()) {
            throw new GenologicsUpdateException(getShortClassName(entityClass) + " cannot be updated.");
        }

        assert entityAnno.primaryEntity() == void.class : entityClass.getName()
                + " has a primary entity set, but such things cannot be updated through the API.";

        Class<BH> batchUpdateClass = getBatchRetrieveClassForEntity(entityClass);

        boolean doBatchUpdates = false;

        if (batchUpdateClass != null) {
            GenologicsBatchRetrieveResult batchAnnotation = batchUpdateClass
                    .getAnnotation(GenologicsBatchRetrieveResult.class);
            assert batchAnnotation != null : "No GenologicsBatchRetrieveResult annotation on result class "
                    + entityClass.getName();

            doBatchUpdates = batchAnnotation.batchUpdate() && entities.size() > 1;
        }

        checkServerSet();

        if (doBatchUpdates) {
            try {
                List<E> updatedEntities = new ArrayList<E>(entities.size());

                final int batchCapacity = Math.min(bulkOperationBatchSize, entities.size());
                List<E> batch = new ArrayList<E>(batchCapacity);

                Iterator<E> entityIter = entities.iterator();

                while (entityIter.hasNext()) {
                    batch.clear();

                    while (entityIter.hasNext() && batch.size() < batchCapacity) {
                        batch.add(entityIter.next());
                    }

                    BH details = batchUpdateClass.newInstance();
                    details.addForUpdate(batch);

                    String url = apiRoot + entityAnno.uriSection() + "/batch/update";

                    ResponseEntity<Links> updateReply = restClient.exchange(url, HttpMethod.POST,
                            new HttpEntity<BH>(details), Links.class);
                    Links replyLinks = updateReply.getBody();

                    assert replyLinks.getSize() == batch.size() : "Have " + replyLinks.getSize()
                            + " links returned for " + batch.size() + " submitted entities.";

                    // Fetch the updated objects to make sure all the properties are correct.
                    // Some may be disallowed or just not updated in the LIMS.

                    url = apiRoot + entityAnno.uriSection() + "/batch/retrieve";

                    ResponseEntity<BH> reloadReply = restClient.exchange(url, HttpMethod.POST,
                            new HttpEntity<Links>(replyLinks), batchUpdateClass);

                    updatedEntities.addAll(reloadReply.getBody().getList());
                }

                // The fetch of the entities using the Links object may not bring them back in
                // the order originally requested, so sort based on the order of the original
                // entities. As these entities already existed, they will all have URIs to
                // compare. We can then update the originals.

                reorderBatchFetchList(entities, updatedEntities);

                reflectiveCollectionUpdate(entities, updatedEntities);
            } catch (IllegalAccessException e) {
                logger.error("Cannot access the default constructor on {}", batchUpdateClass.getName());
            } catch (InstantiationException e) {
                logger.error("Cannot create a new {}: {}", batchUpdateClass.getName(), e.getMessage());
            }
        } else {
            for (E entity : entities) {
                if (entity != null) {
                    ResponseEntity<? extends Locatable> response = restClient.exchange(entity.getUri(),
                            HttpMethod.PUT, new HttpEntity<E>(entity), entity.getClass());

                    reflectiveUpdate(entity, response.getBody());
                }
            }
        }
    }
}

From source file:org.geoserver.rest.catalog.AbstractStoreUploadController.java

/**
 *
 * @param store/*from  w ww  .  j  a  va2 s.  c  o m*/
 * @param format
 * @param directory
 *
 */
protected List<Resource> handleFileUpload(String store, String workspace, UploadMethod method, String format,
        Resource directory, HttpServletRequest request) {

    List<Resource> files = new ArrayList<>();

    Resource uploadedFile;
    boolean external = false;
    try {
        if (method == UploadMethod.file) {
            // we want to delete the previous dir contents only in case of PUT, not
            // in case of POST (harvest, available only for raster data)
            boolean cleanPreviousContents = HttpMethod.PUT.name().equals(request.getMethod());
            String filename = request.getParameter("filename");
            if (filename == null) {
                filename = buildUploadedFilename(store, format);
            }
            uploadedFile = RESTUtils.handleBinUpload(filename, directory, cleanPreviousContents, request,
                    workspace);
        } else if (method == UploadMethod.url) {
            uploadedFile = RESTUtils.handleURLUpload(buildUploadedFilename(store, format), workspace, directory,
                    request);
        } else if (method == UploadMethod.external) {
            uploadedFile = RESTUtils.handleEXTERNALUpload(request);
            external = true;
        } else {
            throw new RestException("Unrecognized file upload method: " + method, HttpStatus.BAD_REQUEST);
        }
    } catch (Throwable t) {
        if (t instanceof RestException) {
            throw (RestException) t;
        } else {
            throw new RestException("Error while storing uploaded file:", HttpStatus.INTERNAL_SERVER_ERROR, t);
        }
    }

    // handle the case that the uploaded file was a zip file, if so unzip it
    if (RESTUtils.isZipMediaType(request)) {
        // rename to .zip if need be
        if (!uploadedFile.name().endsWith(".zip")) {
            Resource newUploadedFile = uploadedFile.parent()
                    .get(FilenameUtils.getBaseName(uploadedFile.path()) + ".zip");
            String oldFileName = uploadedFile.name();
            if (!uploadedFile.renameTo(newUploadedFile)) {
                String errorMessage = "Error renaming zip file from " + oldFileName + " -> "
                        + newUploadedFile.name();
                throw new RestException(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            uploadedFile = newUploadedFile;
        }
        // unzip the file
        try {
            // Unzipping of the file and, if it is a POST request, filling of the File List
            RESTUtils.unzipFile(uploadedFile, directory, workspace, store, request, files, external);

            // look for the "primary" file
            // TODO: do a better check
            Resource primaryFile = findPrimaryFile(directory, format);
            if (primaryFile != null) {
                uploadedFile = primaryFile;
            } else {
                throw new RestException("Could not find appropriate " + format + " file in archive",
                        HttpStatus.BAD_REQUEST);
            }
        } catch (RestException e) {
            throw e;
        } catch (Exception e) {
            throw new RestException("Error occured unzipping file", HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    }
    // If the File List is empty then the uploaded file must be added
    if (uploadedFile != null) {
        files.clear();
        files.add(uploadedFile);
    }

    return files;
}

From source file:org.motechproject.mds.docs.swagger.SwaggerGenerator.java

private void addCrudEndpoints(SwaggerModel swaggerModel, Entity entity, Locale locale) {
    final String entityPath = ClassName.restUrl(entity.getName(), entity.getModule(), entity.getNamespace());

    RestOptions restOptions = restOptionsOrDefault(entity);

    if (restOptions.isAllowRead()) {
        // retrieveAll and retrieveById
        swaggerModel.addPathEntry(entityPath, HttpMethod.GET, readPathEntry(entity, locale));
    }/*from  ww  w .  java2 s .  com*/
    if (restOptions.isAllowCreate()) {
        // post new item
        swaggerModel.addPathEntry(entityPath, HttpMethod.POST, postPathEntry(entity, locale));
    }
    if (restOptions.isAllowUpdate()) {
        // update an existing item
        swaggerModel.addPathEntry(entityPath, HttpMethod.PUT, putPathEntry(entity, locale));
    }
    if (restOptions.isAllowDelete()) {
        // delete an item
        swaggerModel.addPathEntry(entityPath + ID_PATHVAR, HttpMethod.DELETE, deletePathEntry(entity, locale));
    }
}

From source file:org.opentestsystem.shared.trapi.TrClient.java

@Override
public void put(String url, Object request) {
    try {/*  w  w  w  . jav a2 s.  c  o m*/
        exchange(url, JsonHelper.serialize(request), TrApiContentType.JSON, HttpMethod.PUT);
    } catch (TrApiException e) {
        throw e;
    } catch (Exception e) {
        throw new TrApiException(e);
    }
}

From source file:org.rippleosi.common.service.proxies.DefaultRequestProxy.java

@Override
public <T> ResponseEntity<T> putWithoutSession(String uri, Class<T> cls, Object body) {

    String json = convertObjectToJson(body);

    HttpEntity<String> request = buildRequestWithoutSession(json);

    return restTemplate().exchange(uri, HttpMethod.PUT, request, cls);
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void errorPageFromPutRequest() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/hello"));
    this.webServer = factory.getWebServer(exampleServletRegistration(), errorServletRegistration());
    this.webServer.start();
    assertThat(getResponse(getLocalUrl("/hello"), HttpMethod.PUT)).isEqualTo("Hello World");
    assertThat(getResponse(getLocalUrl("/bang"), HttpMethod.PUT)).isEqualTo("Hello World");
}