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

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

Introduction

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

Prototype

public UriComponents build() 

Source Link

Document

Build a UriComponents instance from the various components contained in this builder.

Usage

From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java

/**
 * @see DATAREST-160/*  www . j  a v  a2s  . co m*/
 */
@Test
public void returnConflictWhenConcurrentlyEditingVersionedEntity() throws Exception {

    Link receiptLink = client.discoverUnique("receipts");

    Receipt receipt = new Receipt();
    receipt.setAmount(new BigDecimal(50));
    receipt.setSaleItem("Springy Tacos");

    String stringReceipt = mapper.writeValueAsString(receipt);

    MockHttpServletResponse createdReceipt = postAndGet(receiptLink, stringReceipt, MediaType.APPLICATION_JSON);
    Link tacosLink = client.assertHasLinkWithRel("self", createdReceipt);
    assertJsonPathEquals("$.saleItem", "Springy Tacos", createdReceipt);

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
    String concurrencyTag = createdReceipt.getHeader("ETag");

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
            .contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))
            .andExpect(status().is2xxSuccessful());

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
            .contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, "\"falseETag\""))
            .andExpect(status().isPreconditionFailed());
}

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);
    }//from  w ww  .  j  a v a  2  s . co m

    @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:it.scoppelletti.wui.HeadTag.java

/**
 * Implementazione./*from w  w  w  .  j a v a 2s.c o  m*/
 */
@Override
public void doTag() throws IOException, JspException {
    URI uri;
    UriComponentsBuilder uriBuilder;
    WebApplicationManager applMgr;
    List<String> applList;
    ApplicationContext applCtx;
    PageContext pageCtx = (PageContext) getJspContext();

    applCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(pageCtx.getServletContext());

    applMgr = applCtx.getBean(WebApplicationManager.BEAN_NAME, WebApplicationManager.class);
    applList = applMgr.listRunningApplications();

    for (String ctxPath : applList) {
        uriBuilder = UriComponentsBuilder.fromHttpUrl(applMgr.getBaseUrl());
        uriBuilder.path(ctxPath).path(HeadTag.HEAD_PATH);
        uriBuilder.queryParam(AbstractServerResource.QUERY_LOCALE, pageCtx.getRequest().getLocale().toString());
        uri = uriBuilder.build().toUri();

        try {
            head(uri, pageCtx.getOut());
        } catch (Exception ex) {
            myLogger.error(String.format("Failed to get %1$s.", uri), ex);
        }
    }
}

From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    String dataTypeKey = shimDataRequest.getDataTypeKey().trim().toUpperCase();

    RunkeeperDataType runkeeperDataType;
    try {/*from w w  w.j a v  a 2s  .  c  om*/
        runkeeperDataType = RunkeeperDataType.valueOf(dataTypeKey);
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + dataTypeKey
                + " in shimDataRequest, cannot retrieve data.");
    }

    /***
     * Setup default date parameters
     */
    OffsetDateTime now = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();

    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    Runkeeper defaults to returning a maximum of 25 entries per request (pageSize = 25 by default), so
    we override the default by specifying an arbitrarily large number as the pageSize.
     */
    long numToReturn = 100_000;

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(runkeeperDataType.getEndPointUrl())
            .queryParam("noEarlierThan", startDateTime.toLocalDate())
            .queryParam("noLaterThan", endDateTime.toLocalDate()).queryParam("pageSize", numToReturn)
            .queryParam("detail", true); // added to all endpoints to support summaries

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", runkeeperDataType.getDataTypeHeader());

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.exchange(uriBuilder.build().encode().toUri(), GET,
                new HttpEntity<JsonNode>(headers), JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // FIXME figure out how to handle this
        logger.error("A request for RunKeeper data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {
        RunkeeperDataPointMapper<?> dataPointMapper;
        switch (runkeeperDataType) {
        case ACTIVITY:
            dataPointMapper = new RunkeeperPhysicalActivityDataPointMapper();
            break;
        case CALORIES:
            dataPointMapper = new RunkeeperCaloriesBurnedDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ok().body(ShimDataResponse.result(SHIM_KEY,
                dataPointMapper.asDataPoints(singletonList(responseEntity.getBody()))));
    } else {
        return ok().body(ShimDataResponse.result(SHIM_KEY, responseEntity.getBody()));
    }
}

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

@Test
public void obtainAuthorizationCode() throws Exception {
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2AuthorizeEndpointPath);
    builder.queryParam("username", getUsername());
    builder.queryParam("password", getPassword());
    builder.queryParam("client_id", getClientId());
    builder.queryParam("response_type", "code");
    builder.queryParam("redirect_uri", "http://anywhere");
    // builder.queryParam("realm","oauth2-resource");

    // optional builder.queryParam("scope", "");
    // recommended (optional) builder.queryParam("state", "");

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

    // check this! assertEquals(HttpStatus.FOUND, result2.getStatusCode());        

    // Obtain the token from redirection URL after #
    URI location = result2.getHeaders().getLocation();
    authorizationCode = extractAuthorizationCode(location.toString());
    assertNotNull(authorizationCode);// w  w w .  j a v  a  2 s  . c o  m
}

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

public void refreshToken() {
    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("grant_type", "refresh_token");
    builder.queryParam("refresh_token", refreshToken);

    // 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);

    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);/*from   w  w  w.j a  v a 2s  . c om*/

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

From source file:it.scoppelletti.programmerpower.web.control.ActionBase.java

/**
 * Restituisce l&rsquo;indirizzo della pagina HTML di guida.
 * //from   w  w  w  .j  a v a2  s.c o m
 * <P>Questa implementazione del metodo {@code getHelpUrl} rileva il valore 
 * della propriet&agrave; {@code path.help} tra le risorse
 * associate all&rsquo;azione: se questa propriet&agrave; &egrave;
 * impostata, &egrave; considerata come un percorso relativo
 * all&rsquo;indirizzo di base della guida di riferimento di Programmer
 * Power ({@code http://www.scoppelletti.it/programmerpower/reference});
 * questo indirizzo di base pu&ograve; essere sovrascritto dal valore
 * impostato sulla propriet&agrave; di ambiente
 * {@code it.scoppelletti.programmerpower.web.help.url}.<BR>
 * Le classi derivate da terze parti dovrebbero implementare una versione
 * prevalente del metodo {@code getHelpUrl} per restituire l&rsquo;URL
 * opportuno.</P>
 * 
 * @return Valore. Se la guida non &egrave; prevista, restituisce
 *         {@code null}.
 * @see <A HREF="{@docRoot}/../reference/setup/envprops.html"
 *      TARGET="_top">Propriet&agrave; di ambiente</A>          
 */
public String getHelpUrl() {
    String base, path;
    UriComponentsBuilder uriBuilder;
    Environment env;

    path = getText(ActionBase.PROP_HELPPATH);
    if (Strings.isNullOrEmpty(path) || ActionBase.PROP_HELPPATH.equals(path)) {
        return null;
    }

    if (myApplCtx == null) {
        base = ActionBase.DEF_HELPURL;
    } else {
        env = myApplCtx.getEnvironment();
        base = env.getProperty(ActionBase.PROP_HELPURL, ActionBase.DEF_HELPURL);
    }

    if (!base.endsWith("/") && !path.startsWith("/")) {
        base = base.concat("/");
    }

    uriBuilder = UriComponentsBuilder.fromUriString(base);
    uriBuilder.path(path);

    return uriBuilder.build().toUriString();
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Returns a list of available SENSE service API resource URLs.
 *
 * Operation: GET /api/sense/v1/*from  w w  w  .  j a  v  a  2 s .co  m*/
 *
 * @return A RESTful response.
 * @throws java.net.MalformedURLException
 */
@ApiOperation(value = "Get a list of supported SENSE resources.", notes = "Returns a list of available SENSE resource URL.", response = DeltaResource.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_MSG, response = Resource.class),
        @ApiResponse(code = HttpConstants.UNAUTHORIZED_CODE, message = HttpConstants.UNAUTHORIZED_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class), })
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<?> getResources() throws MalformedURLException {
    try {
        // We need the request URL to build fully qualified resource URLs.
        final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

        log.info("[SenseRmController] GET operation = {}", location);

        // We will populate some HTTP response headers.
        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Location", location.toASCIIString());

        List<Resource> resources = new ArrayList<>();
        Method[] methods = SenseRmController.class.getMethods();
        for (Method m : methods) {
            if (m.isAnnotationPresent(ResourceAnnotation.class)) {
                ResourceAnnotation ra = m.getAnnotation(ResourceAnnotation.class);
                RequestMapping rm = m.getAnnotation(RequestMapping.class);
                if (ra == null || rm == null) {
                    continue;
                }
                Resource resource = new Resource();
                resource.setId(ra.name());
                resource.setVersion(ra.version());
                UriComponentsBuilder path = utilities.getPath(location.toASCIIString());
                path.path(rm.value()[0]);
                resource.setHref(path.build().toUriString());
                resources.add(resource);
            }
        }

        return new ResponseEntity<>(resources, headers, HttpStatus.OK);
    } catch (SecurityException | MalformedURLException ex) {
        log.error("[SenseRmController] Exception caught", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}