Example usage for org.springframework.web.client RestTemplate postForLocation

List of usage examples for org.springframework.web.client RestTemplate postForLocation

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate postForLocation.

Prototype

@Override
    @Nullable
    public URI postForLocation(URI url, @Nullable Object request) throws RestClientException 

Source Link

Usage

From source file:io.fabric8.che.starter.client.WorkspaceClient.java

public void startWorkspace(String cheServerUrl, String workspaceId) {
    // Before starting a workspace, we must first stop all other running workspaces
    List<Workspace> workspaces = listWorkspaces(cheServerUrl);

    boolean alreadyStarted = false;

    for (Workspace workspace : workspaces) {
        if (workspace.getId().equals(workspaceId)) {
            if (WorkspaceState.RUNNING.toString().equals(workspace.getStatus())
                    || WorkspaceState.STARTING.toString().equals(workspace.getStatus())) {
                alreadyStarted = true;// ww  w  .j  a v  a 2 s.c om
            }
        } else if (!WorkspaceState.STOPPED.toString().equals(workspace.getStatus())) {
            stopWorkspace(cheServerUrl, workspace.getId());
        }
    }

    if (!alreadyStarted) {
        String url = CheRestEndpoints.START_WORKSPACE.generateUrl(cheServerUrl, workspaceId);
        RestTemplate template = new RestTemplate();
        template.postForLocation(url, null);
    }
}

From source file:io.fabric8.che.starter.client.CheRestClient.java

public void startWorkspace(String cheServerURL, String workspaceId) {
    String url = generateURL(cheServerURL, CheRestEndpoints.START_WORKSPACE, workspaceId);
    RestTemplate template = new RestTemplate();
    template.postForLocation(url, null);
}

From source file:com.wisemapping.test.rest.RestAccountITCase.java

private URI createUser(HttpHeaders requestHeaders, RestTemplate templateRest, RestUser restUser) {
    HttpEntity<RestUser> createUserEntity = new HttpEntity<RestUser>(restUser, requestHeaders);
    return templateRest.postForLocation(BASE_REST_URL + "/admin/users", createUserEntity);
}

From source file:org.n52.tamis.rest.forward.processes.execute.ExecuteRequestForwarder.java

/**
 * {@inheritDoc} <br/>/*from   www . j  a  va 2  s .  c  om*/
 * <br/>
 * Delegates an incoming execute request to the WPS proxy.
 * 
 * Has two possible return values depending on the type of execution
 * (synchronous or asynchronous)! See return description.
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance and
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to
 *            identify the process
 * 
 * @param requestBody
 *            must be an instance of {@link Execute_HttpPostBody}
 * @return either a String value representing the location header to the
 *         created job instance (in case of asynchronous execution)
 *         <b>OR</b> an instance of {@link ResultDocument} (in case of
 *         synchronous execution).
 * @throws IOException
 */
@Override
public Object forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) throws IOException {
    initializeRequestSpecificParameters(parameterValueStore);

    Execute_HttpPostBody executeBody = null;

    /*
     * requestBody must be an instance of Execute_HttpPostBody
     */
    if (requestBody instanceof Execute_HttpPostBody)
        executeBody = (Execute_HttpPostBody) requestBody;
    else
        logger.error(
                "Request body was expected to be an instance of \"{}\", but was \"{}\". NullPointerException might occur.",
                Execute_HttpPostBody.class, requestBody.getClass());

    // add process Id, since it is not included in the received execute
    // body, but is needed
    executeBody.setProcessId(this.getProcessId());

    sosRequestConstructor.constructSosGetObservationRequestsForInputs(executeBody);

    String execute_url_wpsProxy = createTargetURL_WpsProxy(request);

    /*
     * To guarantee the existence of the parameter "sync-execute" in the
     * request-object, the parameter has been added as an attribute to the
     * request.
     */
    boolean syncExecute_parameter = (boolean) request
            .getAttribute(ExecuteProcessController.SYNC_EXECUTE_PARAMETER_NAME);
    execute_url_wpsProxy = append_syncExecute_parameter(syncExecute_parameter, execute_url_wpsProxy);

    /*
     * forward execute request to WPS proxy.
     * 
     * depending on the request parameter "sync-execute" the call should be
     * realized asynchronously or synchronously.
     */
    URI createdJobUri_wpsProxy = null;

    /**
     * content headers!
     */
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    if (syncExecute_parameter) {
        // synchronous
        RestTemplate synchronousExecuteTemplate = new RestTemplate();

        /*
         * execute the POST request synchronously
         * 
         * the return value will be a result document of the newly created
         * resource. Thus, we have to extract the jobId from it to manually
         * build the location header)
         * 
         */

        HttpEntity requestEntity = new HttpEntity(executeBody, headers);

        ResultDocument resultDocument = synchronousExecuteTemplate.postForObject(execute_url_wpsProxy,
                requestEntity, ResultDocument.class);

        /*
         * the WPS is not conceptualized to offer a StatusRequest against a
         * job that has been executed synchronously. Hence, any jobID-URL
         * pointing to a synchronous job will fail (and result in a Bad
         * Request error or syntax error)
         * 
         * Hence, we will simply return the ResultDocument!
         */

        return resultDocument;
    } else {

        /*
         * Proceed similar to synchronous, since I just call the WPS proxy
         * with different sync-execute parameter;
         * 
         * In opposite to synchronous call, will receive and return the
         * location header of the newly created job instance
         */

        RestTemplate asynchronousExecuteTemplate = new RestTemplate();

        createdJobUri_wpsProxy = asynchronousExecuteTemplate.postForLocation(execute_url_wpsProxy, executeBody);

        /*
         * from the result of the execution request against the WPS proxy,
         * extract the location header and return it.
         * 
         * the location header points to an URL specific for the WPS proxy!
         * 
         * What we need is the URL pointing to THIS applications resource.
         * Hence, we must adapt the URL! --> Basically we have to extract the
         * job ID and append it to the standard URL path of THIS application.
         * 
         * createdJobUrl_wpsProxy looks like "<baseUrl-wpsProxy>/processes/{processId}/jobs/{jobId}"
         */
        String jobId = createdJobUri_wpsProxy.getPath().split(URL_Constants_WpsProxy.SLASH_JOBS + "/")[1];

        /*
         * target job URL should look like: "<base-url-tamis>/services/{serviceId}/processes/{processId}/jobs/{jobId}"
         */

        String createdJobUrl = request.getRequestURL().toString();
        createdJobUrl = createdJobUrl + URL_Constants_TAMIS.SLASH_JOBS + "/" + jobId;

        return createdJobUrl;
    }
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.UploadDataFile.java

/**
 * Method, where data file information is pushed to server in order to create data file record.
 * All heavy lifting is made here.// ww w.  ja v  a  2s.c  o  m
 *
 * @param dataFileContents must be three params in order - experiment id, description, path to file
 * @return URI of uploaded file
 */
@Override
protected URI doInBackground(String... dataFileContents) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DATAFILE;

    setState(RUNNING, R.string.working_ws_upload_data_file);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    //so files wont buffer in memory
    factory.setBufferRequestBody(false);
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    try {
        Log.d(TAG, url);
        FileSystemResource toBeUploadedFile = new FileSystemResource(dataFileContents[2]);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
        form.add("experimentId", dataFileContents[0]);
        form.add("description", dataFileContents[1]);
        form.add("file", toBeUploadedFile);

        HttpEntity<Object> entity = new HttpEntity<Object>(form, requestHeaders);
        // Make the network request
        return restTemplate.postForLocation(url, entity);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.thingsboard.demo.loader.data.DemoData.java

public void uploadData(RestTemplate restTemplate, String baseUrl) throws Exception {
    plugins.forEach(plugin -> {/*  w w  w . ja  v a 2  s. c  om*/
        try {
            String apiToken = plugin.getApiToken();
            PluginMetaData savedPlugin = null;
            try {
                savedPlugin = restTemplate.getForObject(baseUrl + "/api/plugin/token/" + apiToken,
                        PluginMetaData.class);
            } catch (HttpClientErrorException e) {
                if (e.getStatusCode() != HttpStatus.NOT_FOUND) {
                    throw e;
                }
            }
            if (savedPlugin == null) {
                savedPlugin = restTemplate.postForObject(baseUrl + "/api/plugin", plugin, PluginMetaData.class);
            }
            if (savedPlugin.getState() == ComponentLifecycleState.SUSPENDED) {
                restTemplate.postForLocation(
                        baseUrl + "/api/plugin/" + savedPlugin.getId().getId().toString() + "/activate", null);
            }
        } catch (Exception e) {
            log.error("Unable to upload plugin!");
            log.error("Cause:", e);
        }
    });

    rules.forEach(rule -> {
        try {
            RuleMetaData savedRule = null;
            TextPageData<RuleMetaData> rules;
            ResponseEntity<TextPageData<RuleMetaData>> entity = restTemplate.exchange(
                    baseUrl + "/api/rule?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null,
                    new ParameterizedTypeReference<TextPageData<RuleMetaData>>() {
                    }, 1000, rule.getName());
            rules = entity.getBody();
            if (rules.getData().size() > 0) {
                savedRule = rules.getData().get(0);
            }
            if (savedRule == null) {
                savedRule = restTemplate.postForObject(baseUrl + "/api/rule", rule, RuleMetaData.class);
            }
            if (savedRule.getState() == ComponentLifecycleState.SUSPENDED) {
                restTemplate.postForLocation(
                        baseUrl + "/api/rule/" + savedRule.getId().getId().toString() + "/activate", null);
            }
        } catch (Exception e) {
            log.error("Unable to upload rule!");
            log.error("Cause:", e);
        }
    });

    Map<String, CustomerId> customerIdMap = new HashMap<>();
    customers.forEach(customer -> {
        try {
            Customer savedCustomer = null;
            TextPageData<Customer> customers;
            ResponseEntity<TextPageData<Customer>> entity = restTemplate.exchange(
                    baseUrl + "/api/customers?limit={limit}&textSearch={textSearch}", HttpMethod.GET, null,
                    new ParameterizedTypeReference<TextPageData<Customer>>() {
                    }, 1000, customer.getTitle());
            customers = entity.getBody();
            if (customers.getData().size() > 0) {
                savedCustomer = customers.getData().get(0);
            }
            if (savedCustomer == null) {
                savedCustomer = restTemplate.postForObject(baseUrl + "/api/customer", customer, Customer.class);
            }
            customerIdMap.put(savedCustomer.getTitle(), savedCustomer.getId());
        } catch (Exception e) {
            log.error("Unable to upload customer!");
            log.error("Cause:", e);
        }
    });

    List<Device> loadedDevices = new ArrayList<>();

    Map<String, DeviceId> deviceIdMap = new HashMap<>();
    devices.forEach(device -> {
        try {
            CustomerId customerId = null;
            String customerTitle = customerDevices.get(device.getName());
            if (customerTitle != null) {
                customerId = customerIdMap.get(customerTitle);
            }
            Device savedDevice = null;
            TextPageData<Device> devices;
            if (customerId != null) {
                ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange(
                        baseUrl + "/api/customer/{customerId}/devices?limit={limit}&textSearch={textSearch}",
                        HttpMethod.GET, null, new ParameterizedTypeReference<TextPageData<Device>>() {
                        }, customerId.getId().toString(), 1000, device.getName());
                devices = entity.getBody();
                if (devices.getData().size() > 0) {
                    savedDevice = devices.getData().get(0);
                }
            }
            if (savedDevice == null) {
                ResponseEntity<TextPageData<Device>> entity = restTemplate.exchange(
                        baseUrl + "/api/tenant/devices?limit={limit}&textSearch={textSearch}", HttpMethod.GET,
                        null, new ParameterizedTypeReference<TextPageData<Device>>() {
                        }, 1000, device.getName());
                devices = entity.getBody();
                if (devices.getData().size() > 0) {
                    savedDevice = devices.getData().get(0);
                }
            }
            if (savedDevice == null) {
                savedDevice = restTemplate.postForObject(baseUrl + "/api/device", device, Device.class);
            }
            if (customerId != null && savedDevice.getCustomerId().isNullUid()) {
                restTemplate.postForLocation(baseUrl + "/api/customer/{customerId}/device/{deviceId}", null,
                        customerId.getId().toString(), savedDevice.getId().toString());
            }
            String deviceName = savedDevice.getName();
            DeviceId deviceId = savedDevice.getId();
            deviceIdMap.put(deviceName, deviceId);
            loadedDevices.add(savedDevice);
            DeviceCredentials credentials = restTemplate.getForObject(
                    baseUrl + "/api/device/{deviceId}/credentials", DeviceCredentials.class,
                    deviceId.getId().toString());
            loadedDevicesCredentialsMap.put(deviceId, credentials);

            Map<String, JsonNode> attributesMap = devicesAttributes.get(deviceName);
            if (attributesMap != null) {
                attributesMap.forEach((k, v) -> {
                    restTemplate.postForObject(baseUrl + "/api/plugins/telemetry/{deviceId}/{attributeScope}",
                            v, Void.class, deviceId.getId().toString(), k);
                });
            }
        } catch (Exception e) {
            log.error("Unable to upload device!");
            log.error("Cause:", e);
        }
    });

    devices = loadedDevices;

    Map<String, Dashboard> pendingDashboards = dashboards.stream()
            .collect(Collectors.toMap(Dashboard::getTitle, Function.identity()));
    Map<String, Dashboard> savedDashboards = new HashMap<>();
    while (pendingDashboards.size() != 0) {
        Dashboard savedDashboard = null;
        for (Dashboard dashboard : pendingDashboards.values()) {
            savedDashboard = getDashboardByName(restTemplate, baseUrl, dashboard);
            if (savedDashboard == null) {
                try {
                    Optional<String> dashboardConfigurationBody = resolveLinks(savedDashboards,
                            dashboard.getConfiguration());
                    if (dashboardConfigurationBody.isPresent()) {
                        dashboard.setConfiguration(objectMapper.readTree(dashboardConfigurationBody.get()));
                        JsonNode dashboardConfiguration = dashboard.getConfiguration();
                        JsonNode deviceAliases = dashboardConfiguration.get("deviceAliases");
                        deviceAliases.forEach(jsonNode -> {
                            String aliasName = jsonNode.get("alias").asText();
                            DeviceId deviceId = deviceIdMap.get(aliasName);
                            if (deviceId != null) {
                                ((ObjectNode) jsonNode).put("deviceId", deviceId.getId().toString());
                            }
                        });
                        savedDashboard = restTemplate.postForObject(baseUrl + "/api/dashboard", dashboard,
                                Dashboard.class);
                    }
                } catch (Exception e) {
                    log.error("Unable to upload dashboard!");
                    log.error("Cause:", e);
                }
            }
            if (savedDashboard != null) {
                break;
            }
        }
        if (savedDashboard != null) {
            savedDashboards.put(savedDashboard.getTitle(), savedDashboard);
            pendingDashboards.remove(savedDashboard.getTitle());
        } else {
            log.error("Unable to upload dashboards due to unresolved references!");
            break;
        }
    }

    dashboards = new ArrayList<>(savedDashboards.values());
}