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

/**
 * Atomically updates a key-value pair in etcd.
 * /* w w  w. j ava 2  s  .  c o  m*/
 * @param key
 *            the key
 * @param value
 *            the value
 * @param ttl
 *            the time-to-live
 * @param prevIndex
 *            the modified index of the key
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndSwap(String key, String value, int ttl, int prevIndex) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("ttl", ttl == -1 ? "" : ttl);
    builder.queryParam("prevIndex", prevIndex);

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

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

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {
    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder callBackUriBuilder = UriComponentsBuilder.fromUriString(getCallbackUrl())
            .queryParam("state", exception.getStateKey());

    UriComponentsBuilder authorizationUriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri()).queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code").queryParam("APIName", Joiner.on(' ').join(resource.getScope()))
            .queryParam("redirect_uri", callBackUriBuilder.build().toString());

    return authorizationUriBuilder.build().encode().toString();
}

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

/**
 * Atomically updates a key-value pair in etcd.
 * /* w  ww . j  av a  2s . com*/
 * @param key
 *            the key
 * @param value
 *            the value
 * @param prevValue
 *            the previous value of the key
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndSwap(String key, String value, String prevValue) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("prevValue", prevValue);

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

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

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

private int getImportedIssueNumber(ImportedIssue importedIssue) throws InterruptedException {
    if (importedIssue.getIssueNumber() != null) {
        return importedIssue.getIssueNumber();
    }// www.j  a v a  2s  .  com
    String importIssuesUrl = importedIssue.getImportResponse().getUrl();

    URI uri = UriComponentsBuilder.fromUriString(importIssuesUrl).build().toUri();
    RequestEntity<Void> request = RequestEntity.get(uri)
            .accept(new MediaType("application", "vnd.github.golden-comet-preview+json"))
            .header("Authorization", "token " + getAccessToken()).build();

    long secondsToWait = 1;
    while (true) {
        ResponseEntity<ImportStatusResponse> result = rest.exchange(request, ImportStatusResponse.class);
        String url = result.getBody().getIssueUrl();
        if (url == null) {
            System.out.println(
                    "Issue " + importedIssue.getJiraIssue().getKey() + " is still pending import, waiting "
                            + secondsToWait + " seconds to look up GitHub issue number again");
            Thread.sleep(TimeUnit.SECONDS.toMillis(secondsToWait));
            secondsToWait = (1 + secondsToWait) * 2;
            continue;
        }
        UriComponents parts = UriComponentsBuilder.fromUriString(url).build();
        List<String> segments = parts.getPathSegments();
        int issueNumber = Integer.parseInt(segments.get(segments.size() - 1));
        importedIssue.setIssueNumber(issueNumber);
        return issueNumber;
    }
}

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

/**
 * Load given department current page//from  ww w.  j a  va2 s.  c om
 * 
 * @param request
 *            HttpServletRequest
 * @param processingGroup
 *            Current processing group menu
 * @param selectedDepartment
 *            Given department
 * @param model
 *            Model interchange between client and server
 */
private void loadDepartmentPage(HttpServletRequest request, String processingGroup, String selectedDepartment,
        String processingDepartment, Model model) {
    if (StringUtils.isEmpty(processingGroup) || StringUtils.isEmpty(selectedDepartment)) {
        model.addAttribute("page", null);
        model.addAttribute("manualLoad", false);
    }

    UriComponents uriComponent = UriComponentsBuilder
            .fromUriString(
                    request.getContextPath() + "/{proNo}/pagination/paging/{orglevel}/{deptCode}/{index}")
            .build();
    URI uri = uriComponent.expand(processingGroup, selectedDepartment, processingDepartment, 0).encode()
            .toUri();

    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpHost host = new HttpHost(request.getServerName(), request.getLocalPort(), request.getScheme());
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(host, get);

        // Get the content
        String htmlPage = read(response.getEntity().getContent());

        // 
        model.addAttribute("page", htmlPage);
        model.addAttribute("manualLoad", true);
        model.addAttribute("unitDept", selectedDepartment);
        model.addAttribute("deptCode", processingDepartment);
    } catch (IOException ex) {
        logger.error(ex.getMessage(), ex);
    }
}

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

/**
 * Render page with path variables mapping
 * /{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}
 * /*from   ww w  . j a va2s.  c  o m*/
 * @param userOrgCode
 *            Logged-in user's code
 * @param businessDay
 *            Actual business day
 * @param proGNo
 *            A path variable user's group code
 * @param unitLevel
 *            A path variable classify's code
 * @param unitDept
 *            A path variable department level2's code
 * @param deptCode
 *            A path variable department selected on page view
 * @param year
 *            A path variable year
 * @param quarter
 *            A path variable quarter
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/{unitLevel}/{unitDept}/{deptCode}/{year:\\d{4}}/{quarter:[1-4]}", 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, @PathVariable String deptCode,
        @PathVariable String year, @PathVariable String quarter, final HttpServletRequest request,
        final Model model) {
    logger.info(
            "Loading profit and loss manager in a quarter data by full path [/suih/{unitLevel}/{unitDept}/{deptCode}/{year}/{quarter}]");

    Date currentYear = null;
    int currentQuarter = 0;

    // cast year, quarter
    try {
        currentYear = DateFormatUtil.parse(year, DateFormat.DATE_YEAR);
        currentQuarter = Integer.parseInt(quarter);
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    try {
        /* Get classify list */
        List<Division> divisions;
        try {
            divisions = divisionService.findByKbnId(DEFAULT_KBN_ID);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());

            // Set divisions is empty
            divisions = Collections.emptyList();
        }

        // set list classifies first drop down list
        final String CLASSIFIES = "classifies";
        model.addAttribute(CLASSIFIES, divisions);

        // set value selected first drop down list
        final String UNIT_LEVEL = "unitLevel";
        model.addAttribute(UNIT_LEVEL, selectedClassify(divisions, unitLevel));

        List<Organization> departments = null;
        try {
            // Get the list of organizations level 2
            departments = organizationService.findByKaisoBango(unitLevel);
        } catch (IllegalArgumentException | ObjectNotFoundException ex) {
            logger.warn(ex.getMessage());
        }

        // set attribute list departments for drop down list level2
        final String DEPARTMENTS = "departments";
        model.addAttribute(DEPARTMENTS, departments);

        // set attribute name selected for drop down list level2
        final String UNIT_DEPT = "unitDeptName";
        model.addAttribute(UNIT_DEPT, selectedDepartment(departments, unitDept));

        final String UNIT_DEPT_CODE = "unitDeptCode";
        model.addAttribute(UNIT_DEPT_CODE, unitDept);

        // set attribute department code
        final String DEPT_CODE = "deptCode";
        boolean isTotalCalculation = unitDept.equals(deptCode);
        model.addAttribute(DEPT_CODE, isTotalCalculation ? unitDept : deptCode);

        // set attribute current quarter of business
        final String CURRENT_QUARTER = "currentQuarter";
        model.addAttribute(CURRENT_QUARTER, year.concat("/").concat(quarter));

        InputStreamReader in = null;
        try {
            UriComponents uriComponents = UriComponentsBuilder.fromUriString(
                    request.getContextPath() + Constants.PAGINATION_PATH + "/{unitDept}/{deptCode}/{pageindex}")
                    .build();
            URI uri = uriComponents.expand(proGNo, unitDept, deptCode, 0).encode().toUri();

            // initial HttpHost, HttpGet
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpHost httpHost = new HttpHost(request.getServerName(), request.getLocalPort(),
                    request.getScheme());
            HttpGet httpGet = new HttpGet(uri.toString());
            HttpResponse httpResp = httpClient.execute(httpHost, httpGet);
            if (httpResp.getStatusLine().getStatusCode() != 200) {
                // Release the connection
                httpClient.close();
                httpClient = null;

                // call rest paging error
                throw new RuntimeException(
                        "Failed : HTTP error code : " + httpResp.getStatusLine().getStatusCode());
            }

            // read pagination 
            in = new InputStreamReader(httpResp.getEntity().getContent(),
                    HttpServletContentType.DEFAULT_ENCODING);
            BufferedReader rd = new BufferedReader(in);
            StringBuilder textView = new StringBuilder();

            String line = "";
            while ((line = rd.readLine()) != null) {
                textView.append(line);
            }

            // set attribute pagination
            final String HTML_PAGINATION = "pagination";
            model.addAttribute(HTML_PAGINATION, textView);

            // Release the connection
            httpClient.close();
            httpClient = null;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    logger.warn(ex.getMessage());
                }
            }
        }
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR, true);
        model.addAttribute(ERROR_MESSAGE, getSystemError());
    }

    // 
    return processingSuih(userOrgCode, businessDay, unitDept, deptCode, currentYear, currentQuarter, model);
}

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

/**
 * Atomically updates a key-value pair in etcd.
 * //from www.ja v  a 2s .co m
 * @param key
 *            the key
 * @param value
 *            the value
 * @param ttl
 *            the time-to-live
 * @param prevValue
 *            the previous value of the key
 * @return the response from etcd with the node
 * @throws EtcdException
 *             in case etcd returned an error
 */
public EtcdResponse compareAndSwap(String key, String value, int ttl, String prevValue) throws EtcdException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE);
    builder.pathSegment(key);
    builder.queryParam("ttl", ttl == -1 ? "" : ttl);
    builder.queryParam("prevValue", prevValue);

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

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

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
    notNull(path, "Path");
    if (requestBody != null && !multiParts.isEmpty()) {
        throw new IllegalStateException(
                "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
    }/*from   w  w w  . java2 s  . c  om*/

    String baseUri;
    if (isNotBlank(basePath)) {
        baseUri = mergeAndRemoveDoubleSlash(basePath, path);
    } else {
        baseUri = path;
    }

    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
    if (!queryParams.isEmpty()) {
        new ParamApplier(queryParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                uriComponentsBuilder.queryParam(paramName, paramValues);
            }
        }.applyParams();
    }
    String uri = uriComponentsBuilder.build().toUriString();

    final MockHttpServletRequestBuilder request;
    if (multiParts.isEmpty()) {
        request = MockMvcRequestBuilders.request(method, uri, pathParams);
    } else if (method != POST) {
        throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST);
    } else {
        request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
    }

    String requestContentType = findContentType();

    if (!params.isEmpty()) {
        new ParamApplier(params) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!formParams.isEmpty()) {
        if (method == GET) {
            throw new IllegalArgumentException("Cannot use form parameters in a GET request");
        }
        new ParamApplier(formParams) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();

        boolean isInMultiPartMode = isInMultiPartMode(request);
        if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }

    if (!attributes.isEmpty()) {
        new ParamApplier(attributes) {
            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.requestAttr(paramName, paramValues[0]);
            }
        }.applyParams();
    }

    if (RestDocsClassPathChecker.isSpringRestDocsInClasspath()
            && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
        request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
    }

    if (StringUtils.isNotBlank(requestContentType)) {
        request.contentType(MediaType.parseMediaType(requestContentType));
    }

    if (headers.exist()) {
        for (Header header : headers) {
            request.header(header.getName(), header.getValue());
        }
    }

    if (cookies.exist()) {
        for (Cookie cookie : cookies) {
            javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(),
                    cookie.getValue());
            if (cookie.hasComment()) {
                servletCookie.setComment(cookie.getComment());
            }
            if (cookie.hasDomain()) {
                servletCookie.setDomain(cookie.getDomain());
            }
            if (cookie.hasMaxAge()) {
                servletCookie.setMaxAge(cookie.getMaxAge());
            }
            if (cookie.hasPath()) {
                servletCookie.setPath(cookie.getPath());
            }
            if (cookie.hasVersion()) {
                servletCookie.setVersion(cookie.getVersion());
            }
            servletCookie.setSecure(cookie.isSecured());
            request.cookie(servletCookie);
        }
    }

    if (!sessionAttributes.isEmpty()) {
        request.sessionAttrs(sessionAttributes);
    }

    if (!multiParts.isEmpty()) {
        MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
        for (MockMvcMultiPart multiPart : multiParts) {
            MockMultipartFile multipartFile;
            String fileName = multiPart.getFileName();
            String controlName = multiPart.getControlName();
            String mimeType = multiPart.getMimeType();
            if (multiPart.isByteArray()) {
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        (byte[]) multiPart.getContent());
            } else if (multiPart.isFile() || multiPart.isInputStream()) {
                InputStream inputStream;
                if (multiPart.isFile()) {
                    try {
                        inputStream = new FileInputStream((File) multiPart.getContent());
                    } catch (FileNotFoundException e) {
                        return SafeExceptionRethrower.safeRethrow(e);
                    }
                } else {
                    inputStream = (InputStream) multiPart.getContent();
                }
                try {
                    multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
                } catch (IOException e) {
                    return SafeExceptionRethrower.safeRethrow(e);
                }
            } else { // String
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType,
                        ((String) multiPart.getContent()).getBytes());
            }
            multiPartRequest.file(multipartFile);
        }
    }

    if (requestBody != null) {
        if (requestBody instanceof byte[]) {
            request.content((byte[]) requestBody);
        } else if (requestBody instanceof File) {
            byte[] bytes = toByteArray((File) requestBody);
            request.content(bytes);
        } else {
            request.content(requestBody.toString());
        }
    }

    logRequestIfApplicable(method, baseUri, path, pathParams);

    return performRequest(request);
}