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.zalando.boot.etcd.EtcdClient.java

public EtcdResponse deleteDir(String key, boolean recursive) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);/*from www.  j a v a  2  s. c om*/
    builder.queryParam("recursive", recursive);

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

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

/**
 * Returns a representation of all members in the etcd cluster.
 * /*  www. jav a 2  s .  co m*/
 * @return the members
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdMemberResponse listMembers() throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(MEMBERSPACE);
    return execute(builder, HttpMethod.GET, null, EtcdMemberResponse.class);
}

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

/**
 * @see DATAREST-160/*from   w ww  .  j a  v  a2s. c  om*/
 */
@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:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private void cleanPages(final ConfluencePage targetPage) {
    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();

    if (swaggerConfluenceConfig.getPaginationMode() != PaginationMode.INDIVIDUAL_PAGES) {
        return;//from  w  ww  . j av a  2  s.  c om
    }

    final HttpHeaders httpHeaders = buildHttpHeaders(swaggerConfluenceConfig.getAuthentication());
    final HttpEntity<String> requestEntity = new HttpEntity<>(httpHeaders);

    final String path = String.format("/content/%s/child", targetPage.getId());

    final URI targetUrl = UriComponentsBuilder.fromUriString(swaggerConfluenceConfig.getConfluenceRestApiUrl())
            .path(path).queryParam(EXPAND, "page").build().toUri();

    final ResponseEntity<String> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.GET,
            requestEntity, String.class);

    final String jsonBody = responseEntity.getBody();
    final JSONArray jsonArray = JsonPath.read(jsonBody, "$.page.results");

    final Iterator<Object> iterator = jsonArray.iterator();

    // This matching is designed to make sure we only clean out pages that
    // were created by Swagger Confluence by carefully matching the names.
    while (iterator.hasNext()) {
        final Map<String, Object> page = (Map<String, Object>) iterator.next();
        final String id = (String) page.get(ID);
        final String title = (String) page.get(TITLE);
        deletePage(id, title);
    }
}

From source file:net.sf.sze.frontend.base.URL.java

/**
 * Give a {@link UriComponents} to the URL.
 *
 * @param url a url as String//from ww  w .j a  v  a  2 s .  c  o  m
 * @return the {@link UriComponents}
 */
private static UriComponents getUriComponent(String url) {
    if (!URI_MAP.containsKey(url)) {
        URI_MAP.put(url, UriComponentsBuilder.fromUriString(url).build());
    }

    return URI_MAP.get(url);
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private void deletePage(final String pageId, final String title) {
    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();

    final HttpHeaders httpHeaders = buildHttpHeaders(swaggerConfluenceConfig.getAuthentication());
    final HttpEntity<String> requestEntity = new HttpEntity<>(httpHeaders);

    final String path = String.format("/content/%s", pageId);

    final URI targetUrl = UriComponentsBuilder.fromUriString(swaggerConfluenceConfig.getConfluenceRestApiUrl())
            .path(path).queryParam(EXPAND, "page").build().toUri();

    final ResponseEntity<String> responseEntity;

    try {/* ww  w .j  a  v a 2 s. c o m*/
        responseEntity = restTemplate.exchange(targetUrl, HttpMethod.DELETE, requestEntity, String.class);
    } catch (final HttpClientErrorException e) {
        throw new ConfluenceAPIException(String.format("Failed to Clean Page -> %s : %s", pageId, title), e);
    }

    if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) {
        LOG.info("Cleaned Path Page -> {} : {}", pageId, title);
    } else {
        throw new ConfluenceAPIException(String.format("Failed to Clean Page -> %s : %s", pageId, title));
    }
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private void createPage(final ConfluencePage page, final Map<String, ConfluenceLink> confluenceLinkMap) {
    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();
    final URI targetUrl = UriComponentsBuilder.fromUriString(swaggerConfluenceConfig.getConfluenceRestApiUrl())
            .path("/content").build().toUri();

    final HttpHeaders httpHeaders = buildHttpHeaders(swaggerConfluenceConfig.getAuthentication());
    final String formattedXHtml = reformatXHtml(page.getXhtml(), confluenceLinkMap);
    final String jsonPostBody = buildPostBody(page.getAncestorId(), page.getConfluenceTitle(), formattedXHtml)
            .toJSONString();/*from w w  w  . j a  v  a  2  s .c  om*/

    LOG.debug("CREATE PAGE REQUEST: {}", jsonPostBody);

    final HttpEntity<String> requestEntity = new HttpEntity<>(jsonPostBody, httpHeaders);

    final HttpEntity<String> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.POST, requestEntity,
            String.class);

    LOG.debug("CREATE PAGE RESPONSE: {}", responseEntity.getBody());

    final Integer pageId = getPageIdFromResponse(responseEntity);
    page.setAncestorId(pageId);
}

From source file:net.slkdev.swagger.confluence.service.impl.XHtmlToConfluenceServiceImpl.java

private void updatePage(final ConfluencePage page, final Map<String, ConfluenceLink> confluenceLinkMap) {
    final SwaggerConfluenceConfig swaggerConfluenceConfig = SWAGGER_CONFLUENCE_CONFIG.get();

    final URI targetUrl = UriComponentsBuilder.fromUriString(swaggerConfluenceConfig.getConfluenceRestApiUrl())
            .path(String.format("/content/%s", page.getId())).build().toUri();

    final HttpHeaders httpHeaders = buildHttpHeaders(swaggerConfluenceConfig.getAuthentication());

    final JSONObject postVersionObject = new JSONObject();
    postVersionObject.put("number", page.getVersion() + 1);

    final String formattedXHtml = reformatXHtml(page.getXhtml(), confluenceLinkMap);
    final JSONObject postBody = buildPostBody(page.getAncestorId(), page.getConfluenceTitle(), formattedXHtml);
    postBody.put(ID, page.getId());//from  ww w .java2  s .c o  m
    postBody.put("version", postVersionObject);

    final HttpEntity<String> requestEntity = new HttpEntity<>(postBody.toJSONString(), httpHeaders);

    LOG.debug("UPDATE PAGE REQUEST: {}", postBody);

    final HttpEntity<String> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.PUT, requestEntity,
            String.class);

    LOG.debug("UPDATE PAGE RESPONSE: {}", responseEntity.getBody());

    final Integer pageId = getPageIdFromResponse(responseEntity);
    page.setAncestorId(pageId);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken,
        Authentication authUser) {/*from   w  ww  . j  a  v a 2  s . c  o  m*/

    String requestedRedirect = authorizationRequest.getRedirectUri();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }

    StringBuilder url = new StringBuilder();
    url.append("token_type=").append(encode(accessToken.getTokenType()));

    //only append access token if grant_type is implicit
    //or token is part of the response type
    if (authorizationRequest.getResponseTypes().contains("token")) {
        url.append("&access_token=").append(encode(accessToken.getValue()));
    }

    if (accessToken instanceof CompositeToken
            && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) {
        url.append("&").append(CompositeToken.ID_TOKEN).append("=")
                .append(encode(((CompositeToken) accessToken).getIdTokenValue()));
    }

    if (authorizationRequest.getResponseTypes().contains("code")) {
        String code = generateCode(authorizationRequest, authUser);
        url.append("&code=").append(encode(code));
    }

    String state = authorizationRequest.getState();
    if (state != null) {
        url.append("&state=").append(encode(state));
    }

    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        url.append("&expires_in=").append(expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        url.append("&" + OAuth2Utils.SCOPE + "=")
                .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope())));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            url.append("&" + encode(key) + "=" + encode(value.toString()));
        }
    }

    if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
        HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect));
        String sessionState = openIdSessionStateCalculator.calculate(
                ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(),
                httpHost.toURI());

        url.append("&session_state=").append(sessionState);
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect);
    String existingFragment = builder.build(true).getFragment();
    if (StringUtils.hasText(existingFragment)) {
        existingFragment = existingFragment + "&" + url.toString();
    } else {
        existingFragment = url.toString();
    }
    builder.fragment(existingFragment);
    // Do not include the refresh token (even if there is one)
    return builder.build(true).toUriString();
}