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

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

Introduction

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

Prototype

@Override
public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) 

Source Link

Document

Append the given query parameter to the existing query parameters.

Usage

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

@Test
public void oauth2FlowTest() throws Exception {
    // Obtains the token
    obtainTokenFromOuth2LoginEndpoint();

    // Call remotelog        
    ResponseEntity<String> result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.OK, result.getStatusCode());

    // Call remotelog once the access token has expired (we wait enough to make sure it has expired)
    Thread.sleep(getTokenExpirationDelayInSeconds() * 1000);

    // Call remotelog        
    result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    assertTrue(result.getBody().contains("Access token expired"));

    // Refresh the token
    refreshToken();/*from  ww  w  . j a va 2 s  .  c om*/

    if (!isJwtTokenStore) {
        // The following code is executed only if the token store is not a JwtTokenStore. The reason is that using this kind of store
        // the tokens can't be revoked (they just expire) and so this part of the test would fail.
        // A JwtTokenStore is not a proper store as the tokens are not stored anywhere (as they contain all the required info about the user
        // themselves. That's why the token revocation is not possible.

        // We call logout endpoint (we need to use the access token for this)
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(resourceServerBaseUrl + baseApiPath + oauth2LogoutEndpointPath);
        builder.queryParam("access_token", accessToken);

        ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.POST, null, String.class);
        assertEquals(HttpStatus.OK, result2.getStatusCode());

        // We try to call the protected API again (after having logged out which removes the token) - We expect not to be able to call the service.
        // This will throw a exception. In this case here in the test we receive an exception but really what happened was 'access denied'
        // A production client will receive the proper http error
        result = callRemoteLogWithAccessToken();
        assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    }
}

From source file:org.openmhealth.shim.misfit.MisfitShim.java

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

    final MisfitDataTypes misfitDataType;
    try {/*from   www .  j  ava 2 s .  co  m*/
        misfitDataType = MisfitDataTypes.valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    // TODO don't truncate dates
    OffsetDateTime now = OffsetDateTime.now();

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

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

    if (Duration.between(startDateTime, endDateTime).toDays() > MAX_DURATION_IN_DAYS) {
        endDateTime = startDateTime.plusDays(MAX_DURATION_IN_DAYS - 1); // TODO when refactoring, break apart queries
    }

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL);

    for (String pathSegment : Splitter.on("/").split(misfitDataType.getEndPoint())) {
        uriBuilder.pathSegment(pathSegment);
    }

    uriBuilder.queryParam("start_date", startDateTime.toLocalDate()) // TODO convert ODT to LocalDate properly
            .queryParam("end_date", endDateTime.toLocalDate()).queryParam("detail", true); // added to all endpoints to support summaries

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

    if (shimDataRequest.getNormalize()) {

        MisfitDataPointMapper<?> dataPointMapper;

        switch (misfitDataType) {
        case ACTIVITIES:
            dataPointMapper = physicalActivityMapper;
            break;
        case SLEEP:
            dataPointMapper = sleepDurationMapper;
            break;
        case STEPS:
            dataPointMapper = stepCountMapper;
            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:com.github.ibm.domino.client.BaseClient.java

protected URI getUri(String pathParam) {

    StringBuilder baseUrl = new StringBuilder();
    if (!"http".equals(protocol) && !"https".equals(protocol)) {
        protocol = "http";
    }//from   www.  j  av a2 s .c o  m
    baseUrl.append(protocol).append("://").append(host);
    if (port > 0) {
        baseUrl.append(":").append(port);
    }
    if (!path.startsWith("/")) {
        baseUrl.append("/");
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl.toString())
            .path(path + (pathParam != null && !pathParam.isEmpty() ? "/" + pathParam : ""));
    parameters.entrySet().stream().forEach((parameter) -> {
        builder.queryParam(parameter.getKey(), parameter.getValue());
    });

    return builder.build().toUri();
}

From source file:org.obiba.mica.user.UserProfileService.java

private String getProfileServiceUrlByApp(String username, String application, String group) {
    UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(getAgateUrl()).path(DEFAULT_REST_PREFIX);

    if (Strings.isNullOrEmpty(username)) {
        urlBuilder.path(String.format("/application/%s/users", application));
    } else {/*  w w w .  j  a v  a2s .  co  m*/
        urlBuilder.path(String.format("/application/%s/user/%s", application, username));
    }

    if (!Strings.isNullOrEmpty(group)) {
        urlBuilder.queryParam("group", group);
    }

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

From source file:de.blizzy.documentr.markdown.macro.impl.FlattrMacro.java

@Override
public String getHtml(IMacroContext macroContext) {
    try {//from   w w w  .  j av  a2s .  c o m
        IMacroSettings settings = macroContext.getSettings();
        String userId = settings.getSetting("userId"); //$NON-NLS-1$
        if (StringUtils.isNotBlank(userId)) {
            HtmlSerializerContext htmlSerializerContext = macroContext.getHtmlSerializerContext();
            String projectName = htmlSerializerContext.getProjectName();
            String branchName = htmlSerializerContext.getBranchName();
            String path = htmlSerializerContext.getPagePath();
            String pageUri = htmlSerializerContext.getPageUri(path);
            String pageUrl = htmlSerializerContext.getUrl(pageUri);
            IPageStore pageStore = htmlSerializerContext.getPageStore();
            Page page = pageStore.getPage(projectName, branchName, path, false);
            String title = page.getTitle();
            String tags = StringUtils.join(page.getTags(), ","); //$NON-NLS-1$
            // http://developers.flattr.net/auto-submit/
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://flattr.com/submit/auto") //$NON-NLS-1$
                    .queryParam("user_id", userId) //$NON-NLS-1$
                    .queryParam("url", pageUrl) //$NON-NLS-1$
                    .queryParam("title", title) //$NON-NLS-1$
                    .queryParam("category", "text"); //$NON-NLS-1$ //$NON-NLS-2$
            if (StringUtils.isNotBlank(tags)) {
                builder.queryParam("tags", tags); //$NON-NLS-1$
            }
            String url = builder.build().encode(Charsets.UTF_8.name()).toUriString();
            return "<a href=\"" + StringEscapeUtils.escapeHtml4(url) + "\">" + //$NON-NLS-1$ //$NON-NLS-2$
                    "<img src=\"https://api.flattr.com/button/flattr-badge-large.png\"/></a>"; //$NON-NLS-1$
        }
    } catch (IOException e) {
        log.warn("error while rendering Flattr macro", e); //$NON-NLS-1$
    }
    return null;
}

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

/**
 * @param server/*  ww w . j  a  va 2 s  . c  om*/
 * @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:fi.vrk.xroad.catalog.collector.actors.FetchWsdlActor.java

private String buildUri(XRoadServiceIdentifierType service) {
    assert service.getXRoadInstance() != null;
    assert service.getMemberClass() != null;
    assert service.getMemberCode() != null;
    assert service.getServiceCode() != null;

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getHost()).path(WSDL_CONTEXT_PATH)
            .queryParam("xRoadInstance", service.getXRoadInstance())
            .queryParam("memberClass", service.getMemberClass())
            .queryParam("memberCode", service.getMemberCode())
            .queryParam("serviceCode", service.getServiceCode());
    if (!Strings.isNullOrEmpty(service.getSubsystemCode())) {
        builder = builder.queryParam("subsystemCode", service.getSubsystemCode());
    }/*from  www  .j a v  a 2  s  .  c  o  m*/
    if (!Strings.isNullOrEmpty(service.getServiceVersion())) {
        builder = builder.queryParam("version", service.getServiceVersion());
    }
    return builder.toUriString();
}

From source file:org.devefx.httpmapper.binding.MapperMethod.java

private URI appendUrlParams(URI uri, MultiValueMap<String, Object> body) throws URISyntaxException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUri(uri);
    for (Map.Entry<String, List<Object>> entry : body.entrySet()) {
        String key = entry.getKey();
        for (Object value : entry.getValue()) {
            if (value instanceof String) {
                builder.queryParam(key, (String) value);
            }//from  w w  w.j  a  v  a  2  s.c o  m
        }
    }
    UriComponents uriComponents = builder.build();
    return uriComponents.toUri();
}

From source file:com.teradata.benchto.driver.graphite.GraphiteClient.java

private URI buildLoadMetricsURI(Map<String, String> metrics, long fromEpochSecond, long toEpochSecond) {
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(graphiteURL).path("/render")
            .queryParam("format", "json").queryParam("from", fromEpochSecond)
            .queryParam("until", toEpochSecond);

    for (Map.Entry<String, String> metric : metrics.entrySet()) {
        String metricQueryExpr = metric.getValue();
        String metricName = metric.getKey();

        uriBuilder.queryParam("target", format("alias(%s,'%s')", metricQueryExpr, metricName));
    }//from  www  .  j a  v a  2s .co m

    return URI.create(uriBuilder.toUriString());
}

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  va  2  s  .co m*/

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