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:org.springframework.data.rest.tests.mongodb.MongoWebTests.java

/**
 * @see DATAREST-160/*from   ww  w. j  av a  2  s  .  c  om*/
 */
@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:alfio.util.EventUtil.java

public static String getGoogleCalendarURL(Event event, TicketCategory category, String description) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyMMdd'T'HHmmss");
    ZonedDateTime validityStart = Optional.ofNullable(category).map(TicketCategory::getTicketValidityStart)
            .map(d -> d.withZoneSameInstant(event.getZoneId())).orElse(event.getBegin());
    ZonedDateTime validityEnd = Optional.ofNullable(category).map(TicketCategory::getTicketValidityEnd)
            .map(d -> d.withZoneSameInstant(event.getZoneId())).orElse(event.getEnd());
    return UriComponentsBuilder.fromUriString("https://www.google.com/calendar/event")
            .queryParam("action", "TEMPLATE")
            .queryParam("dates", validityStart.format(formatter) + "/" + validityEnd.format(formatter))
            .queryParam("ctz", event.getTimeZone()).queryParam("text", event.getDisplayName())
            .queryParam("location", event.getLocation()).queryParam("detail", description).toUriString();
}

From source file:alfio.manager.PaypalManager.java

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary,
        CustomerName customerName, String email, String billingAddress, Locale locale,
        boolean postponeAssignment) throws Exception {

    APIContext apiContext = getApiContext(event);

    Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext);

    List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale);
    String eventName = event.getShortName();

    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");

    Payment payment = new Payment();
    payment.setIntent("sale");
    payment.setPayer(payer);/* w w  w  .j ava  2 s .  c o  m*/
    payment.setTransactions(transactions);
    RedirectUrls redirectUrls = new RedirectUrls();

    String baseUrl = StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/");
    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";

    UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl)
            .queryParam("fullName", customerName.getFullName())
            .queryParam("firstName", customerName.getFirstName())
            .queryParam("lastName", customerName.getLastName()).queryParam("email", email)
            .queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment)
            .queryParam("hmac", computeHMAC(customerName, email, billingAddress, event));
    String finalUrl = bookUrlBuilder.toUriString();

    redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true");
    redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true");
    payment.setRedirectUrls(redirectUrls);

    experienceProfileId.ifPresent(payment::setExperienceProfileId);

    Payment createdPayment = payment.create(apiContext);

    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    //add 15 minutes of validity in case the paypal flow is slow
    ticketReservationRepository.updateValidity(reservationId,
            DateUtils.addMinutes(reservation.getValidity(), 15));

    if (!"created".equals(createdPayment.getState())) {
        throw new Exception(createdPayment.getFailureReason());
    }

    //extract url for approval
    return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst()
            .map(Links::getHref).orElseThrow(IllegalStateException::new);

}

From source file:org.openmhealth.shim.googlefit.GoogleFitShim.java

protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {
    final GoogleFitDataTypes googleFitDataType;
    try {//  w w  w. j  av  a2 s.  c o  m
        googleFitDataType = GoogleFitDataTypes.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.");
    }

    OffsetDateTime todayInUTC = LocalDate.now().atStartOfDay().atOffset(ZoneOffset.UTC);

    OffsetDateTime startDateInUTC = shimDataRequest.getStartDateTime() == null ? todayInUTC.minusDays(1)
            : shimDataRequest.getStartDateTime();
    long startTimeNanos = (startDateInUTC.toEpochSecond() * 1000000000) + startDateInUTC.toInstant().getNano();

    OffsetDateTime endDateInUTC = shimDataRequest.getEndDateTime() == null ? todayInUTC.plusDays(1)
            : shimDataRequest.getEndDateTime().plusDays(1); // We are inclusive of the last day, so add 1 day to get
    // the end of day on the last day, which captures the
    // entire last day
    long endTimeNanos = (endDateInUTC.toEpochSecond() * 1000000000) + endDateInUTC.toInstant().getNano();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(googleFitDataType.getStreamId(), "datasets", "{startDate}-{endDate}");
    // TODO: Add limits back into the request once Google has fixed the 'limit' query parameter and paging

    URI uriRequest = uriBuilder.buildAndExpand(startTimeNanos, endTimeNanos).encode().toUri();

    ResponseEntity<JsonNode> responseEntity;
    try {
        responseEntity = restTemplate.getForEntity(uriRequest, JsonNode.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        // TODO figure out how to handle this
        logger.error("A request for Google Fit data failed.", e);
        throw e;
    }

    if (shimDataRequest.getNormalize()) {
        GoogleFitDataPointMapper<?> dataPointMapper;
        switch (googleFitDataType) {
        case BODY_WEIGHT:
            dataPointMapper = new GoogleFitBodyWeightDataPointMapper();
            break;
        case BODY_HEIGHT:
            dataPointMapper = new GoogleFitBodyHeightDataPointMapper();
            break;
        case ACTIVITY:
            dataPointMapper = new GoogleFitPhysicalActivityDataPointMapper();
            break;
        case STEP_COUNT:
            dataPointMapper = new GoogleFitStepCountDataPointMapper();
            break;
        case HEART_RATE:
            dataPointMapper = new GoogleFitHeartRateDataPointMapper();
            break;
        case CALORIES_BURNED:
            dataPointMapper = new GoogleFitCaloriesBurnedDataPointMapper();
            break;
        default:
            throw new UnsupportedOperationException();
        }

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

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

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

/**
 * Sets the value of the node with the given key in etcd. Any previously
 * existing key-value pair is returned as prevNode in the etcd response.
 * /*  w w  w  .  ja v  a 2s  .  c o m*/
 * @param key
 *            the node's key
 * @param value
 *            the node's value
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse put(final String key, final String value) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);

    MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(1);
    payload.set("value", value);

    return execute(builder, HttpMethod.PUT, payload, EtcdResponse.class);
}

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

/**
 * Default mapping without path variables for Jisekim report screen
 * //w w  w  .jav  a 2s .co  m
 * @param businessDay
 * @param proGNo
 * @param selectedCode
 * @return String redirect Uri
 */
@RequestMapping(value = "/{selectedCode:[a-z0-9]+}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay,
        @PathVariable String proGNo, @PathVariable String selectedCode) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering Jisekim report ...");
    }

    // Automatically build a redirect link
    UriComponents uriComponents = UriComponentsBuilder
            .fromUriString(Constants.JISEKIM_PATH + "/{selectedCode}/{monthly}").build();
    String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
    URI uri = uriComponents.expand(proGNo, selectedCode, businessMonth).encode().toUri();
    return "redirect:" + uri.toString();
}

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  w ww  .j a v a 2s  .c om*/
    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.openmhealth.shim.misfit.MisfitShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code").queryParam("scope", Joiner.on(',').join(resource.getScope()))
            .queryParam("redirect_uri", getCallbackUrl());

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

From source file:io.pivotal.github.GithubClient.java

public void deleteRepository() throws IOException {
    if (!shouldDeleteCreateRepository()) {
        return;/*from  w w  w  .  j  av a 2s  .  com*/
    }
    String slug = getRepositorySlug();

    CommitService commitService = new CommitService(client());
    try {
        commitService.getCommits(createRepositoryId());
        throw new IllegalStateException("Attempting to delete a repository that has commits. Terminating!");
    } catch (RequestException e) {
        if (e.getStatus() != 404 & e.getStatus() != 409) {
            throw new IllegalStateException(
                    "Attempting to delete a repository, but it appears the repository may have commits. Terminating!",
                    e);
        }
    }

    UriComponentsBuilder uri = UriComponentsBuilder.fromUriString("https://api.github.com/repos/" + slug)
            .queryParam("access_token", getAccessToken());
    rest.delete(uri.toUriString());
}

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

/**
 * Sets the value of the node with the given key in etcd.
 * /*from w w w.ja  v  a  2 s.c o  m*/
 * @param key
 *            the node's key
 * @param value
 *            the node's value
 * @param ttl
 *            the node's time-to-live or <code>-1</code> to unset existing
 *            ttl
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse put(String key, String value, int ttl) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("ttl", ttl == -1 ? "" : ttl);

    MultiValueMap<String, String> payload = new LinkedMultiValueMap<>(1);
    payload.set("value", value);

    return execute(builder, HttpMethod.PUT, payload, EtcdResponse.class);
}