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

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

Introduction

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

Prototype

public static UriComponentsBuilder fromUriString(String uri) 

Source Link

Document

Create a builder that is initialized with the given URI string.

Usage

From source file:net.longfalcon.newsj.service.TraktService.java

public TraktEpisodeResult getEpisode(long traktId, int season, int episode) {
    try {//from  w  w w  .j  a va2  s .com
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder
                .fromUriString(
                        traktApiUrl + "/shows/" + traktId + "/seasons/" + season + "/episodes/" + episode)
                .queryParam("extended", "full").build();
        ResponseEntity<TraktEpisodeResult> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktEpisodeResult.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}

From source file:org.openmhealth.shim.jawbone.JawboneShim.java

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

    final JawboneDataTypes jawboneDataType;
    try {//from   w  ww .ja v  a  2  s. co m
        jawboneDataType = JawboneDataTypes.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.");
    }

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

    OffsetDateTime today = OffsetDateTime.now();

    OffsetDateTime startDateTime = shimDataRequest.getStartDateTime() == null ? today.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeInEpochSecond = startDateTime.toEpochSecond();

    // We are inclusive of the last day, so we need to add an extra day since we are dealing with start of day,
    // and would miss the activities that occurred during the last day within going to midnight of that day
    OffsetDateTime endDateTime = shimDataRequest.getEndDateTime() == null ? today.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1);
    long endTimeInEpochSecond = endDateTime.toEpochSecond();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .path(jawboneDataType.getEndPoint()).queryParam("start_time", startTimeInEpochSecond)
            .queryParam("end_time", endTimeInEpochSecond).queryParam("limit", numToReturn);

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

    if (shimDataRequest.getNormalize()) {

        JawboneDataPointMapper mapper;
        switch (jawboneDataType) {
        case WEIGHT:
            mapper = new JawboneBodyWeightDataPointMapper();
            break;
        case STEPS:
            mapper = new JawboneStepCountDataPointMapper();
            break;
        case BODY_MASS_INDEX:
            mapper = new JawboneBodyMassIndexDataPointMapper();
            break;
        case ACTIVITY:
            mapper = new JawbonePhysicalActivityDataPointMapper();
            break;
        case SLEEP:
            mapper = new JawboneSleepDurationDataPointMapper();
            break;
        case HEART_RATE:
            mapper = new JawboneHeartRateDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

        return ResponseEntity.ok().body(ShimDataResponse.result(JawboneShim.SHIM_KEY,
                mapper.asDataPoints(singletonList(responseEntity.getBody()))));

    } else {

        return ResponseEntity.ok()
                .body(ShimDataResponse.result(JawboneShim.SHIM_KEY, responseEntity.getBody()));
    }

}

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  ww w  .j ava  2 s.  c o m
        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.springframework.data.web.config.EnableSpringDataWebSupportIntegrationTests.java

@Test // DATACMNS-630
public void createsProxyForInterfaceBasedControllerMethodParameter() throws Exception {

    WebApplicationContext applicationContext = WebTestUtils.createApplicationContext(SampleConfig.class);
    MockMvc mvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("/proxy");
    builder.queryParam("name", "Foo");
    builder.queryParam("shippingAddresses[0].zipCode", "ZIP");
    builder.queryParam("shippingAddresses[0].city", "City");
    builder.queryParam("billingAddress.zipCode", "ZIP");
    builder.queryParam("billingAddress.city", "City");
    builder.queryParam("date", "2014-01-11");

    mvc.perform(post(builder.build().toString())).//
            andExpect(status().isOk());/*from  w  w w .  jav a2 s  .c om*/
}

From source file:org.zalando.boot.etcd.EtcdClient.java

/**
 * Returns the node with the given key from etcd.
 * // ww  w .j a v a2s  .  c  o  m
 * @param key
 *            the node's key
 * @param recursive
 *            <code>true</code> if child nodes should be returned,
 *            <code>false</code> otherwise
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse get(String key, boolean recursive) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("recursive", recursive);

    return execute(builder, HttpMethod.GET, null, EtcdResponse.class);
}

From source file:com.nec.harvest.controller.SonekihController.java

@RequestMapping(value = "/{unitLevel}/{unitDept}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo,
        @PathVariable String unitLevel, @PathVariable String unitDept, final HttpServletRequest request,
        final Model model) {

    UriComponents uriComponents = UriComponentsBuilder
            .fromUriString(Constants.SONEKIH_PATH + "/{unitLevel}/{unitDept}/{month}").build();
    String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
    URI uri = uriComponents.expand(proGNo, unitLevel, unitDept, businessMonth).encode().toUri();
    return "redirect:" + uri.toString();
}

From source file:org.springframework.data.rest.webmvc.mongodb.MongoWebTests.java

/**
 * @see DATAREST-160/*from w  w w .ja va2s .com*/
 */
@Test
public void returnConflictWhenConcurrentlyEditingVersionedEntity() throws Exception {

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

    Receipt receipt = new Receipt();
    receipt.amount = new BigDecimal(50);
    receipt.saleItem = "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", concurrencyTag))
            .andExpect(status().isPreconditionFailed());
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }/*  w w w .  ja v  a  2 s  . co m*/

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}