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:tds.assessment.web.endpoints.AccommodationControllerIntegrationTests.java

@Test
public void shouldFindAccommodations() throws Exception {
    Accommodation accommodation = new Accommodation.Builder().withDefaultAccommodation(true)
            .withAccommodationCode("code").withAccommodationType("type").withAccommodationValue("value")
            .withAllowChange(true).withDependsOnToolType("depends").withAllowCombine(false)
            .withDisableOnGuestSession(true).withEntryControl(false).withFunctional(true)
            .withSegmentPosition(99).withToolMode("toolMode").withToolTypeSortOrder(25)
            .withToolValueSortOrder(50).withVisible(true).build();

    when(mockAccommodationsService.findAccommodationsByAssessmentId("SBAC", "id"))
            .thenReturn(singletonList(accommodation));

    String requestUri = UriComponentsBuilder.fromUriString("/SBAC/assessments/accommodations?assessmentId=id")
            .build().toUriString();/*  w  w w .j a  v  a  2s.c  o m*/

    http.perform(get(requestUri).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("[0].defaultAccommodation", is(true)))
            .andExpect(jsonPath("[0].code", is("code"))).andExpect(jsonPath("[0].value", is("value")))
            .andExpect(jsonPath("[0].allowChange", is(true)))
            .andExpect(jsonPath("[0].dependsOnToolType", is("depends")))
            .andExpect(jsonPath("[0].allowCombine", is(false)))
            .andExpect(jsonPath("[0].disableOnGuestSession", is(true)))
            .andExpect(jsonPath("[0].entryControl", is(false))).andExpect(jsonPath("[0].functional", is(true)))
            .andExpect(jsonPath("[0].segmentPosition", is(99)))
            .andExpect(jsonPath("[0].toolMode", is("toolMode")))
            .andExpect(jsonPath("[0].toolTypeSortOrder", is(25)))
            .andExpect(jsonPath("[0].toolValueSortOrder", is(50))).andExpect(jsonPath("[0].visible", is(true)))
            .andExpect(jsonPath("[0].type", is("type")));
}

From source file:org.hobsoft.contacts.server.controller.ContactsController.java

@RequestMapping(value = "/contact/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable long id) {
    Contact contact = contactRepository.get(id);

    contactRepository.delete(contact);/*from  w  w w  .j  a v a2s .c  o  m*/

    Link link = contactResourceAssembler.toResource(contact).getLink(Relation.COLLECTION.rel());
    URI location = UriComponentsBuilder.fromUriString(link.getHref()).build().toUri();

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
}

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

/**
 * Default mapping without path variables for REPORT
 * /*from   ww  w  . ja v a  2 s.  c  o m*/
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param model
 *            Spring model that can be used to render a view
 * @return A redirect URL
 */
@Override
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering petty cash book report...");
    }

    // Build a link to redirect
    UriComponents uriComponent = UriComponentsBuilder.fromUriString(Constants.KOGUCHI_PATH).build();
    URI uri = uriComponent.expand(proGNo).encode().toUri();
    return "redirect:" + uri.toString();
}

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

/**
 * Default mapping without path variables for Sales report screen
 * /*from w  ww.  j a v  a  2s  .c om*/
 * @param request
 * @param response
 * @param model
 * @param orgCode
 * @param businessDay
 * @return String redirect Uri
 */
@Override
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode,
        @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
    if (logger.isDebugEnabled()) {
        logger.debug("Redering uriage report without parameters...");
    }

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

From source file:org.mitre.uma.web.ClaimsCollectionEndpoint.java

@RequestMapping(method = RequestMethod.GET)
public String collectClaims(@RequestParam("client_id") String clientId,
        @RequestParam(value = "redirect_uri", required = false) String redirectUri,
        @RequestParam("ticket") String ticketValue,
        @RequestParam(value = "state", required = false) String state, Model m, OIDCAuthenticationToken auth) {

    ClientDetailsEntity client = clientService.loadClientByClientId(clientId);

    PermissionTicket ticket = permissionService.getByTicket(ticketValue);

    if (client == null || ticket == null) {
        logger.info("Client or ticket not found: " + clientId + " :: " + ticketValue);
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }/*from  ww w .  ja  va  2  s .  co  m*/

    // we've got a client and ticket, let's attach the claims that we have from the token and userinfo

    // subject
    Set<Claim> claimsSupplied = Sets.newHashSet(ticket.getClaimsSupplied());

    String issuer = auth.getIssuer();
    UserInfo userInfo = auth.getUserInfo();

    claimsSupplied.add(mkClaim(issuer, "sub", new JsonPrimitive(auth.getSub())));
    if (userInfo.getEmail() != null) {
        claimsSupplied.add(mkClaim(issuer, "email", new JsonPrimitive(userInfo.getEmail())));
    }
    if (userInfo.getEmailVerified() != null) {
        claimsSupplied.add(mkClaim(issuer, "email_verified", new JsonPrimitive(userInfo.getEmailVerified())));
    }
    if (userInfo.getPhoneNumber() != null) {
        claimsSupplied
                .add(mkClaim(issuer, "phone_number", new JsonPrimitive(auth.getUserInfo().getPhoneNumber())));
    }
    if (userInfo.getPhoneNumberVerified() != null) {
        claimsSupplied.add(mkClaim(issuer, "phone_number_verified",
                new JsonPrimitive(auth.getUserInfo().getPhoneNumberVerified())));
    }
    if (userInfo.getPreferredUsername() != null) {
        claimsSupplied.add(mkClaim(issuer, "preferred_username",
                new JsonPrimitive(auth.getUserInfo().getPreferredUsername())));
    }
    if (userInfo.getProfile() != null) {
        claimsSupplied.add(mkClaim(issuer, "profile", new JsonPrimitive(auth.getUserInfo().getProfile())));
    }

    ticket.setClaimsSupplied(claimsSupplied);

    PermissionTicket updatedTicket = permissionService.updateTicket(ticket);

    if (Strings.isNullOrEmpty(redirectUri)) {
        if (client.getClaimsRedirectUris().size() == 1) {
            redirectUri = client.getClaimsRedirectUris().iterator().next(); // get the first (and only) redirect URI to use here
            logger.info("No redirect URI passed in, using registered value: " + redirectUri);
        } else {
            throw new RedirectMismatchException("Unable to find redirect URI and none passed in.");
        }
    } else {
        if (!client.getClaimsRedirectUris().contains(redirectUri)) {
            throw new RedirectMismatchException("Claims redirect did not match the registered values.");
        }
    }

    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(redirectUri);
    template.queryParam("authorization_state", "claims_submitted");
    if (!Strings.isNullOrEmpty(state)) {
        template.queryParam("state", state);
    }

    String uriString = template.toUriString();
    logger.info("Redirecting to " + uriString);

    return "redirect:" + uriString;
}

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

/**
 * Returns the node with the given key from etcd.
 * //from   w  w w  . j av  a 2s .  c  o  m
 * @param key
 *            the node's key
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse get(String key) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);

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

From source file:tds.assessment.web.endpoints.AccommodationControllerIntegrationTests.java

@Test
public void shouldRequireAccommodationId() throws Exception {
    String requestUri = UriComponentsBuilder.fromUriString("/SBAC/assessments/accommodations").build()
            .toUriString();/*  www  .  j  a va2  s .com*/

    http.perform(get(requestUri).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isBadRequest());
}

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 ww  w.  j  av a2s.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()));
    }
}