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:gov.fda.open.demo.service.FDADataProxyServiceImpl.java

/**
 * Helper method to build DrugEvetn Restful URI
 * //w  ww . j  av a 2 s .co  m
 * @param params
 * @return
 */
private URI buildDrugEventsRequestURI(final Map<String, String> params) {
    StringBuilder drugURL = new StringBuilder(uri);
    drugURL.append(DRUG_EVENT_SEARCH_URL);

    URI httpUri = UriComponentsBuilder.fromHttpUrl(drugURL.toString()).buildAndExpand(params).toUri();

    LOG.debug(" URI : {}", httpUri);

    return httpUri;

}

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

@RequestMapping(value = "/fetch", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_FORM_URLENCODED_VALUE)
public String fetch(@RequestParam("resource") String resource, Model m, HttpSession session) {

    // get the access token if we have one
    String accessTokenValue = acccessTokenService.getAccessToken(resource);

    // send our request to the resource

    HttpHeaders headers = new HttpHeaders();
    if (!Strings.isNullOrEmpty(accessTokenValue)) {
        headers.add("Authorization", "Bearer " + accessTokenValue);
    }// w w  w. ja v a 2 s. c om

    @SuppressWarnings("rawtypes")
    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(resource, 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 {
        // if we get back an error, try to get an access token
        List<String> authHeaders = responseEntity.getHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
        // assume there's only one auth header for now
        String authHeader = Iterators.getOnlyElement(authHeaders.iterator());

        // parse the header to get the good bits
        String authServerUri = null;
        String ticket = null;
        Iterable<String> parts = Splitter.on(",").split(authHeader.substring("UMA ".length()));
        for (String part : parts) {
            List<String> subparts = Splitter.on("=").splitToList(part.trim());
            if (subparts.get(0).equals("as_uri")) {
                authServerUri = subparts.get(1);
                // strip quotes
                authServerUri = authServerUri.substring(1, authServerUri.length() - 1);
            } else if (subparts.get(0).equals("ticket")) {
                ticket = subparts.get(1);
                // strip quotes
                ticket = ticket.substring(1, ticket.length() - 1);
            }
        }

        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(authServerUri);

        // 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, resource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, authServerUri);

                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

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

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

            request = new HttpEntity<>(headers);

            responseEntity = restTemplate.exchange(resource, 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";
            }
        }

    }

}

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

/**
 * Delete an entity// ww  w . j  av a  2  s . co 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
 * @return the listener to notify of completion
 */
public ListenableFuture<Void> deleteEntity(String entityId, String type) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}");
    addParam(builder, "type", type);
    return adapt(request(HttpMethod.DELETE, builder.buildAndExpand(entityId).toUriString(), null, Void.class));
}

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

/**
 * @param server/*from  w w  w.  jav a 2s . c o m*/
 * @param client
 * @return
 */
private String redirectForPAT(MultipartyServerConfiguration server, RegisteredClient client,
        HttpSession session) {

    String state = new RandomValueStringGenerator().generate();
    session.setAttribute("STATE", state);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(server.getAuthorizationEndpointUri());
    builder.queryParam("client_id", client.getClientId());
    builder.queryParam("response_type", "code");
    builder.queryParam("state", state);
    builder.queryParam("scope", "uma_protection");
    builder.queryParam("redirect_uri", "http://localhost:8080/multiparty-resource/pat_callback");

    logger.warn("Redirecting to: " + builder.toUriString());

    return "redirect:" + builder.toUriString();
}

From source file:com.jvoid.quote.controller.JVoidQuoteController.java

public ProductsMaster getJVoidProduct(int productId) {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {/*from   w  ww .j av  a 2  s . c o  m*/
        jsonObj.put("id", productId);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("param jsonObj=>" + jsonObj.toString());

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

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

    JSONArray productsArr = null;
    ProductsMaster productsMaster = null;
    try {
        productsArr = returnJsonObj.getJSONArray("products");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    productsMaster = new ProductsMaster();
    try {
        ObjectMapper mapper = new ObjectMapper();
        try {
            productsMaster = mapper.readValue(productsArr.getJSONObject(0).toString(), ProductsMaster.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return productsMaster;
}

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

@RequestMapping(value = "/sign-up", method = RequestMethod.POST)
public @ResponseBody String jvoidSignUpNewUser(
        @RequestParam(required = false, value = "params") JSONObject jsonParams) {
    System.out.println("sign-up:jsonParams=>" + jsonParams.toString());

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    String uri = "";
    try {/*from  ww w  . j av a  2s  .co m*/
        if (jsonParams.getInt("id") > 0) {
            uri = ServerUris.CUSTOMER_SERVER_URI + URIConstants.UPDATE_CUSTOMER;
        } else {
            uri = ServerUris.CUSTOMER_SERVER_URI + URIConstants.ADD_CUSTOMER;
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri).queryParam("params", jsonParams);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    return returnString.getBody();
}

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

/**
 * Retrieve the attribute of an entity//w w  w  . j  ava  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<Attribute> getAttribute(String entityId, String type, String attributeName) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL);
    builder.path("v2/entities/{entityId}/attrs/{attributeName}");
    addParam(builder, "type", type);
    return adapt(request(HttpMethod.GET, builder.buildAndExpand(entityId, attributeName).toUriString(), null,
            Attribute.class));
}

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

@Test
public void obtainTokenFromOuth2LoginEndpoint() throws Exception {
    obtainAuthorizationCode();/* w ww .  j  av  a2  s  .c  o m*/
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
    // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in        
    builder.queryParam("client_id", getClientId());
    builder.queryParam("grant_type", "authorization_code");
    builder.queryParam("code", authorizationCode);
    builder.queryParam("redirect_uri", "http://anywhere");

    // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
    HttpHeaders headers = new HttpHeaders();
    Encoder encoder = Base64.getEncoder();
    headers.add("Authorization",
            "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));

    HttpEntity<String> entity = new HttpEntity<>("", headers);
    ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, OAuth2AccessToken.class);

    // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token.
    // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the 
    // redirect_uri with the token after #
    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);

    refreshToken = result2.getBody().getRefreshToken().getValue();
    assertNotNull(refreshToken);
}

From source file:com.epam.cme.storefront.controllers.pages.checkout.MultiStepCheckoutController.java

@ModelAttribute("checkoutSteps")
public List<CheckoutSteps> addCheckoutStepsToModel(final HttpServletRequest request) {
    final String baseUrl = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .replacePath(request.getContextPath()).build().toUriString();

    final List<CheckoutSteps> checkoutSteps = new ArrayList<CheckoutSteps>();
    checkoutSteps/*from  w  ww .  ja  v a 2s.  c  o m*/
            .add(new CheckoutSteps("deliveryAddress", baseUrl + "/checkout/multi/choose-delivery-address"));
    checkoutSteps.add(new CheckoutSteps("deliveryMethod", baseUrl + "/checkout/multi/choose-delivery-method"));
    checkoutSteps.add(new CheckoutSteps("paymentMethod", baseUrl + "/checkout/multi/choose-payment-method"));
    checkoutSteps.add(new CheckoutSteps("confirmOrder", baseUrl + "/checkout/multi/summary"));

    return checkoutSteps;
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationRemoteLogServiceEnabledTest() throws Exception {
    TestLoginInfo loginInfo = simpleLogin();

    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");

    // This test requires the test CSRF Token. This implies passing JSESSIONID and CSRF Token
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath)
            .queryParam(DEFAULT_CSRF_PARAMETER_NAME, loginInfo.getXsrfToken());
    ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, String.class);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
}