Example usage for org.springframework.web.util UriComponentsBuilder fromHttpUrl

List of usage examples for org.springframework.web.util UriComponentsBuilder fromHttpUrl

Introduction

In this page you can find the example usage for org.springframework.web.util UriComponentsBuilder fromHttpUrl.

Prototype

public static UriComponentsBuilder fromHttpUrl(String httpUrl) 

Source Link

Document

Create a URI components builder from the given HTTP URL String.

Usage

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/jvoid-products-by-cat")
public @ResponseBody String listAllJVoidProductsByCategoryForOutView(@RequestParam("catId") String catId) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {//  w  w w. j  a  v a 2  s . c o m
        jsonObj.put("id", Integer.parseInt(catId));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.PRODUCT_SERVER_URI + URIConstants.GET_PRODUCTS_BY_CATEGORY)
            .queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);

    JSONObject returnJsonObj = null;
    try {
        returnJsonObj = new JSONObject(returnString.getBody());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return returnJsonObj.toString();
}

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

/**
 * Retrieve the attribute of an entity//from   www  .j  a  v  a 2 s  .c  o  m
 * @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<String> getAttributeValueAsString(String entityId, String type, String attributeName) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}/attrs/{attributeName}/value");
    addParam(builder, "type", type);
    HttpHeaders httpHeaders = cloneHttpHeaders();
    httpHeaders.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
    return adapt(request(HttpMethod.GET, builder.buildAndExpand(entityId, attributeName).toUriString(),
            httpHeaders, null, String.class));
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

protected ResponseEntity<String> callRemoteLogWithAccessToken() {
    RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO();
    remoteLogRequest.setLogLevel("DEBUG");
    remoteLogRequest.setMessage("This is my log message!");

    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest);
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath);
    builder.queryParam("access_token", accessToken);

    ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entity, String.class);
    return result;
}

From source file:com.jvoid.core.controller.HomeController.java

@RequestMapping("/jvoid-categories")
public @ResponseBody String listAllJVoidCategoriesForOutView() {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {/*from w  w w. jav a  2s .  c  o  m*/
        jsonObj.put("id", -1);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(ServerUris.PRODUCT_SERVER_URI + URIConstants.GET_CATEGORY)
            .queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);

    JSONObject returnJsonObj = null;
    try {
        returnJsonObj = new JSONObject(returnString.getBody());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return returnJsonObj.toString();
}

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

/**
 * Retrieve a list of entity types//from  www .  j  a va 2  s . c  o  m
 * @param offset an optional offset (0 for none)
 * @param limit an optional limit (0 for none)
 * @param count true to return the total number of matching entities
 * @return a pagined list of entity types
 */
public ListenableFuture<Paginated<EntityType>> getEntityTypes(int offset, int limit, boolean count) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/types");
    addPaginationParams(builder, offset, limit);
    if (count) {
        addParam(builder, "options", "count");
    }
    return adaptPaginated(request(HttpMethod.GET, builder.toUriString(), null, EntityType[].class), offset,
            limit);
}

From source file:org.mitreid.multiparty.web.ClientController.java

@RequestMapping(value = "claims_submitted")
public String claimsSubmissionCallback(@RequestParam("authorization_state") String authorizationState,
        @RequestParam("state") String returnState, @RequestParam("ticket") String ticket, HttpSession session,
        Model m) {/*w ww  .j  a  va 2 s  . co m*/

    // get our saved information out of the session
    String savedState = (String) session.getAttribute(STATE_SESSION_VAR);
    String savedResource = (String) session.getAttribute(RESOURCE_SESSION_VAR);
    String savedAuthServerUri = (String) session.getAttribute(AUTHSERVERURI_SESSION_VAR);

    // make sure the state matches
    if (Strings.isNullOrEmpty(returnState) || !returnState.equals(savedState)) {
        // it's an error if it doesn't
        logger.error("Unable to match states");
        return "home";
    }

    if (authorizationState.equals("claims_submitted")) {
        // claims have been submitted, let's go try to get a token again
        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(savedAuthServerUri);

        // find the client configuration (maybe register)
        RegisteredClient client = clientConfig.getClientConfiguration(server);

        HttpHeaders tokenHeaders = new HttpHeaders();
        tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // send request to the token endpoint
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("client_id", client.getClientId());
        params.add("client_secret", client.getClientSecret());
        params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation");
        params.add("ticket", ticket);
        //params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders);

        ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(),
                tokenRequest, String.class);
        JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject();

        if (o.has("error")) {
            if (o.get("error").getAsString().equals("need_info")) {
                // if we get need info, redirect

                JsonObject details = o.get("error_details").getAsJsonObject();

                // this is the URL to send the user to
                String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString();
                String newTicket = details.get("ticket").getAsString();

                // set a state value for our return
                String state = UUID.randomUUID().toString();
                session.setAttribute(STATE_SESSION_VAR, state);

                // save bits about the request we were trying to make
                session.setAttribute(RESOURCE_SESSION_VAR, savedResource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, savedAuthServerUri);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint)
                        .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket)
                        .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt
                        .queryParam("state", state);

                return "redirect:" + builder.build();
            } else {
                // it's an error we don't know how to deal with, give up
                logger.error("Unknown error from token endpoint: " + o.get("error").getAsString());
                return "home";
            }
        } else {
            // if we get an access token, try it again

            String accessTokenValue = o.get("access_token").getAsString();
            acccessTokenService.saveAccesstoken(savedResource, accessTokenValue);

            HttpHeaders headers = new HttpHeaders();
            if (!Strings.isNullOrEmpty(accessTokenValue)) {
                headers.add("Authorization", "Bearer " + accessTokenValue);
            }

            HttpEntity<Object> request = new HttpEntity<>(headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(savedResource, HttpMethod.GET,
                    request, String.class);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                // if we get back data, display it
                JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
                m.addAttribute("label", rso.get("label").getAsString());
                m.addAttribute("value", rso.get("value").getAsString());
                return "home";
            } else {
                logger.error("Unable to get a token");
                return "home";
            }
        }
    } else {
        logger.error("Unknown response from claims endpoing: " + authorizationState);
        return "home";
    }

}

From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker.java

/**
 * This method is for demonstrating ingest of raster data This will be
 * refactored once the API changes have been communicated to other team
 * members//w w w  .  j ava 2 s . c  om
 */
public void handleRasterType(ExecuteServiceJob executeJob, Job job, Producer<String, String> producer) {
    RestTemplate restTemplate = new RestTemplate();
    ExecuteServiceData data = executeJob.data;
    // Get the id from the data
    String serviceId = data.getServiceId();
    Service sMetadata = accessor.getServiceById(serviceId);
    // Default request mimeType application/json
    String requestMimeType = "application/json";
    new LinkedMultiValueMap<String, String>();

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl());
    Map<String, DataType> postObjects = new HashMap<String, DataType>();
    Iterator<Entry<String, DataType>> it = data.getDataInputs().entrySet().iterator();
    String postString = "";

    while (it.hasNext()) {
        Entry<String, DataType> entry = it.next();
        String inputName = entry.getKey();

        if (entry.getValue() instanceof URLParameterDataType) {
            String paramValue = ((TextDataType) entry.getValue()).getContent();
            if (inputName.length() == 0) {
                builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl() + "?" + paramValue);
            } else {
                builder.queryParam(inputName, paramValue);
            }
        } else if (entry.getValue() instanceof BodyDataType) {
            BodyDataType bdt = (BodyDataType) entry.getValue();
            postString = bdt.getContent();
            requestMimeType = bdt.getMimeType();
        }
        // Default behavior for other inputs, put them in list of objects
        // which are transformed into JSON consistent with default
        // requestMimeType
        else {
            postObjects.put(inputName, entry.getValue());
        }
    }
    if (postString.length() > 0 && postObjects.size() > 0) {
        return;
    } else if (postObjects.size() > 0) {
        ObjectMapper mapper = makeNewObjectMapper();
        try {
            postString = mapper.writeValueAsString(postObjects);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    URI url = URI.create(builder.toUriString());
    HttpHeaders headers = new HttpHeaders();

    // Set the mimeType of the request
    MediaType mediaType = createMediaType(requestMimeType);
    headers.setContentType(mediaType);
    // Set the mimeType of the request
    // headers.add("Content-type",
    // sMetadata.getOutputs().get(0).getDataType().getMimeType());

    if (postString.length() > 0) {

        coreLogger.log("The postString is " + postString, PiazzaLogger.DEBUG);

        HttpHeaders theHeaders = new HttpHeaders();
        // headers.add("Authorization", "Basic " + credentials);
        theHeaders.setContentType(MediaType.APPLICATION_JSON);

        // Create the Request template and execute
        HttpEntity<String> request = new HttpEntity<String>(postString, theHeaders);

        try {
            coreLogger.log("About to call special service " + url, PiazzaLogger.DEBUG);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request,
                    String.class);
            coreLogger.log("The Response is " + response.getBody(), PiazzaLogger.DEBUG);

            String serviceControlString = response.getBody();
            coreLogger.log("Service Control String " + serviceControlString, PiazzaLogger.DEBUG);

            ObjectMapper tempMapper = makeNewObjectMapper();
            DataResource dataResource = tempMapper.readValue(serviceControlString, DataResource.class);
            coreLogger.log("dataResource type is " + dataResource.getDataType().getClass().getSimpleName(),
                    PiazzaLogger.DEBUG);

            dataResource.dataId = uuidFactory.getUUID();
            coreLogger.log("dataId " + dataResource.dataId, PiazzaLogger.DEBUG);

            PiazzaJobRequest pjr = new PiazzaJobRequest();
            pjr.createdBy = "pz-sc-ingest-raster-test";

            IngestJob ingestJob = new IngestJob();
            ingestJob.data = dataResource;
            ingestJob.host = true;
            pjr.jobType = ingestJob;

            ProducerRecord<String, String> newProdRecord = JobMessageFactory.getRequestJobMessage(pjr,
                    uuidFactory.getUUID(), SPACE);
            producer.send(newProdRecord);

            coreLogger.log("newProdRecord sent " + newProdRecord.toString(), PiazzaLogger.DEBUG);

            StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS);

            // Create a text result and update status
            DataResult textResult = new DataResult(dataResource.dataId);
            statusUpdate.setResult(textResult);
            ProducerRecord<String, String> prodRecord = JobMessageFactory.getUpdateStatusMessage(job.getJobId(),
                    statusUpdate, SPACE);

            producer.send(prodRecord);
            coreLogger.log("prodRecord sent " + prodRecord.toString(), PiazzaLogger.DEBUG);

        } catch (JsonProcessingException jpe) {
            jpe.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

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

/**
 * Retrieve an entity type//from ww w .  ja v  a  2  s. co m
 * @param entityType the entityType to retrieve
 * @return an entity type
 */
public ListenableFuture<EntityType> getEntityType(String entityType) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/types/{entityType}");
    return adapt(
            request(HttpMethod.GET, builder.buildAndExpand(entityType).toUriString(), null, EntityType.class));
}

From source file:org.starfishrespect.myconsumption.android.ui.AddSensorActivity.java

private boolean create() {
    DatabaseHelper db = new DatabaseHelper(this);
    String user = null;/* www.  ja  va 2s .  c  o m*/
    KeyValueData userJson = db.getValueForKey("user");
    ObjectMapper mapper = new ObjectMapper();
    if (userJson != null) {

        try {
            user = mapper.readValue(userJson.getValue(), UserData.class).getName();
        } catch (IOException e) {
            return false;
        }
    }
    if (user == null) {
        return false;
    }
    RestTemplate template = new RestTemplate();
    HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
    ResponseEntity<String> responseEnt;
    template.getMessageConverters().add(new FormHttpMessageConverter());
    template.getMessageConverters().add(new StringHttpMessageConverter());

    try {
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(SingleInstance.getServerUrl() + "sensors/")
                .queryParam("name", editTextSensorName.getText().toString())
                .queryParam("type", selectedSensorType).queryParam("user", user)
                .queryParam("settings", mapper.writeValueAsString(sensorView.getSensorSettings()));

        responseEnt = template.exchange(builder.build().encode().toUri(), HttpMethod.POST,
                new HttpEntity<>(httpHeaders), String.class);

        String result = responseEnt.getBody();
        Log.d(TAG, result);

        SimpleResponseDTO response = mapper.readValue(result, SimpleResponseDTO.class);
        if (response.getStatus() == 0) {
            return true;
        }
    } catch (HttpClientErrorException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return false;
}

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

/**
 * Retrieve the list of all Registrations
 * @return a list of registrations/* w  w w  . j  av  a 2s.com*/
 */
public ListenableFuture<List<Registration>> getRegistrations() {

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/registrations");

    ListenableFuture<ResponseEntity<Registration[]>> e = request(HttpMethod.GET, builder.toUriString(), null,
            Registration[].class);
    return new ListenableFutureAdapter<List<Registration>, ResponseEntity<Registration[]>>(e) {
        @Override
        protected List<Registration> adapt(ResponseEntity<Registration[]> result) throws ExecutionException {
            return new ArrayList<>(Arrays.asList(result.getBody()));
        }
    };
}