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

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

Introduction

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

Prototype

@Override
public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) 

Source Link

Document

Append the given query parameter to the existing query parameters.

Usage

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?");
    }// w w w . jav  a  2s . co  m

    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);
}

From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker.java

/**
 * This method is for demonstrating ingest of raster data This will be
 * refactored once the API changes have been communicated to other team
 * members//from  w w  w .j a v  a 2s . c o m
 */
public void handleRasterType(ExecuteServiceJob executeJob, Job job, Producer<String, String> producer) {
    RestTemplate restTemplate = new RestTemplate();
    ExecuteServiceData data = executeJob.data;
    // Get the id from the data
    String serviceId = data.getServiceId();
    Service sMetadata = accessor.getServiceById(serviceId);
    // Default request mimeType application/json
    String requestMimeType = "application/json";
    new LinkedMultiValueMap<String, String>();

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl());
    Map<String, DataType> postObjects = new HashMap<String, DataType>();
    Iterator<Entry<String, DataType>> it = data.getDataInputs().entrySet().iterator();
    String postString = "";

    while (it.hasNext()) {
        Entry<String, DataType> entry = it.next();
        String inputName = entry.getKey();

        if (entry.getValue() instanceof URLParameterDataType) {
            String paramValue = ((TextDataType) entry.getValue()).getContent();
            if (inputName.length() == 0) {
                builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl() + "?" + paramValue);
            } else {
                builder.queryParam(inputName, paramValue);
            }
        } else if (entry.getValue() instanceof BodyDataType) {
            BodyDataType bdt = (BodyDataType) entry.getValue();
            postString = bdt.getContent();
            requestMimeType = bdt.getMimeType();
        }
        // Default behavior for other inputs, put them in list of objects
        // which are transformed into JSON consistent with default
        // requestMimeType
        else {
            postObjects.put(inputName, entry.getValue());
        }
    }
    if (postString.length() > 0 && postObjects.size() > 0) {
        return;
    } else if (postObjects.size() > 0) {
        ObjectMapper mapper = makeNewObjectMapper();
        try {
            postString = mapper.writeValueAsString(postObjects);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    URI url = URI.create(builder.toUriString());
    HttpHeaders headers = new HttpHeaders();

    // Set the mimeType of the request
    MediaType mediaType = createMediaType(requestMimeType);
    headers.setContentType(mediaType);
    // Set the mimeType of the request
    // headers.add("Content-type",
    // sMetadata.getOutputs().get(0).getDataType().getMimeType());

    if (postString.length() > 0) {

        coreLogger.log("The postString is " + postString, PiazzaLogger.DEBUG);

        HttpHeaders theHeaders = new HttpHeaders();
        // headers.add("Authorization", "Basic " + credentials);
        theHeaders.setContentType(MediaType.APPLICATION_JSON);

        // Create the Request template and execute
        HttpEntity<String> request = new HttpEntity<String>(postString, theHeaders);

        try {
            coreLogger.log("About to call special service " + url, PiazzaLogger.DEBUG);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request,
                    String.class);
            coreLogger.log("The Response is " + response.getBody(), PiazzaLogger.DEBUG);

            String serviceControlString = response.getBody();
            coreLogger.log("Service Control String " + serviceControlString, PiazzaLogger.DEBUG);

            ObjectMapper tempMapper = makeNewObjectMapper();
            DataResource dataResource = tempMapper.readValue(serviceControlString, DataResource.class);
            coreLogger.log("dataResource type is " + dataResource.getDataType().getClass().getSimpleName(),
                    PiazzaLogger.DEBUG);

            dataResource.dataId = uuidFactory.getUUID();
            coreLogger.log("dataId " + dataResource.dataId, PiazzaLogger.DEBUG);

            PiazzaJobRequest pjr = new PiazzaJobRequest();
            pjr.createdBy = "pz-sc-ingest-raster-test";

            IngestJob ingestJob = new IngestJob();
            ingestJob.data = dataResource;
            ingestJob.host = true;
            pjr.jobType = ingestJob;

            ProducerRecord<String, String> newProdRecord = JobMessageFactory.getRequestJobMessage(pjr,
                    uuidFactory.getUUID(), SPACE);
            producer.send(newProdRecord);

            coreLogger.log("newProdRecord sent " + newProdRecord.toString(), PiazzaLogger.DEBUG);

            StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS);

            // Create a text result and update status
            DataResult textResult = new DataResult(dataResource.dataId);
            statusUpdate.setResult(textResult);
            ProducerRecord<String, String> prodRecord = JobMessageFactory.getUpdateStatusMessage(job.getJobId(),
                    statusUpdate, SPACE);

            producer.send(prodRecord);
            coreLogger.log("prodRecord sent " + prodRecord.toString(), PiazzaLogger.DEBUG);

        } catch (JsonProcessingException jpe) {
            jpe.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandler.java

/**
 * Handles requests to execute a service. 
 * TODO this needs to change to leverage pz-jbcommon ExecuteServiceMessage after it builds.
 * //w  w w .  j av a  2 s .c  o  m
 * @param message
 * @return the Response as a String
 */
public ResponseEntity<String> handle(ExecuteServiceData data) {
    coreLogger.log("executeService serviceId=" + data.getServiceId(), PiazzaLogger.INFO);
    ResponseEntity<String> responseEntity = null;
    String serviceId = data.getServiceId();
    Service sMetadata = null;
    // Default request mimeType application/json
    String requestMimeType = "application/json";
    try {
        // Accessor throws exception if can't find service
        sMetadata = accessor.getServiceById(serviceId);

        ObjectMapper om = new ObjectMapper();
        String result = om.writeValueAsString(sMetadata);
        coreLogger.log(result, PiazzaLogger.INFO);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (sMetadata != null) {
        String rawURL = sMetadata.getUrl();
        coreLogger.log("URL to use = " + rawURL, PiazzaLogger.INFO);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(rawURL);

        Map<String, DataType> postObjects = new HashMap<>();
        Iterator<Entry<String, DataType>> it = data.getDataInputs().entrySet().iterator();
        String postString = "";
        while (it.hasNext()) {
            Entry<String, DataType> entry = it.next();
            String inputName = entry.getKey();
            coreLogger.log("The parameter is " + inputName, PiazzaLogger.DEBUG);

            if (entry.getValue() instanceof URLParameterDataType) {
                String paramValue = ((URLParameterDataType) entry.getValue()).getContent();
                if (inputName.length() == 0) {
                    coreLogger.log("sMetadata.getResourceMeta=" + sMetadata.getResourceMetadata(),
                            PiazzaLogger.DEBUG);

                    builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl() + "?" + paramValue);
                    coreLogger.log("Builder URL is " + builder.toUriString(), PiazzaLogger.DEBUG);

                } else {
                    builder.queryParam(inputName, paramValue);
                    coreLogger.log("Input Name=" + inputName + " paramValue=" + paramValue, PiazzaLogger.DEBUG);
                }
            } else if (entry.getValue() instanceof BodyDataType) {
                BodyDataType bdt = (BodyDataType) entry.getValue();
                postString = bdt.getContent();
                requestMimeType = bdt.getMimeType();
                if ((requestMimeType == null) || (requestMimeType.length() == 0)) {
                    coreLogger.log("Body mime type not specified", PiazzaLogger.ERROR);
                    return new ResponseEntity<>("Body mime type not specified", HttpStatus.BAD_REQUEST);
                }
            } else {
                // Default behavior for other inputs, put them in list of objects
                // which are transformed into JSON consistent with default requestMimeType
                coreLogger.log("inputName =" + inputName + "entry Value=" + entry.getValue(),
                        PiazzaLogger.INFO);
                postObjects.put(inputName, entry.getValue());
            }
        }

        coreLogger.log("Final Builder URL" + builder.toUriString(), PiazzaLogger.INFO);
        if (postString.length() > 0 && postObjects.size() > 0) {
            coreLogger.log("String Input not consistent with other Inputs", PiazzaLogger.ERROR);
            return new ResponseEntity<>("String Input not consistent with other Inputs",
                    HttpStatus.BAD_REQUEST);
        } else if (postObjects.size() > 0) {
            ObjectMapper mapper = makeObjectMapper();
            try {
                postString = mapper.writeValueAsString(postObjects);
            } catch (JsonProcessingException e) {
                coreLogger.log(e.getMessage(), PiazzaLogger.ERROR);
                return new ResponseEntity<>("Could not marshal post requests", HttpStatus.BAD_REQUEST);
            }
        }

        URI url = URI.create(builder.toUriString());
        if (sMetadata.getMethod().equals("GET")) {
            coreLogger.log("GetForEntity URL=" + url, PiazzaLogger.INFO);
            responseEntity = template.getForEntity(url, String.class);

        } else {
            HttpHeaders headers = new HttpHeaders();

            // Set the mimeType of the request
            MediaType mediaType = createMediaType(requestMimeType);
            headers.setContentType(mediaType);
            HttpEntity<String> requestEntity = makeHttpEntity(headers, postString);

            coreLogger.log("PostForEntity URL=" + url, PiazzaLogger.INFO);
            responseEntity = template.postForEntity(url, requestEntity, String.class);
        }

    } else {
        return new ResponseEntity<>("Service Id" + data.getServiceId() + "not found", HttpStatus.NOT_FOUND);

    }
    return responseEntity;
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {

    UriComponentsBuilder template = UriComponentsBuilder.newInstance();
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
    URI redirectUri;// ww w.ja  v a  2 s.c  o  m
    try {
        // assume it's encoded to start with (if it came in over the wire)
        redirectUri = builder.build(true).toUri();
    } catch (Exception e) {
        // ... but allow client registrations to contain hard-coded non-encoded values
        redirectUri = builder.build().toUri();
        builder = UriComponentsBuilder.fromUri(redirectUri);
    }
    template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
            .userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());

    if (fragment) {
        StringBuilder values = new StringBuilder();
        if (redirectUri.getFragment() != null) {
            String append = redirectUri.getFragment();
            values.append(append);
        }
        for (String key : query.keySet()) {
            if (values.length() > 0) {
                values.append("&");
            }
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            values.append(name + "={" + key + "}");
        }
        if (values.length() > 0) {
            template.fragment(values.toString());
        }
        UriComponents encoded = template.build().expand(query).encode();
        builder.fragment(encoded.getFragment());
    } else {
        for (String key : query.keySet()) {
            String name = key;
            if (nonNull(keys) && keys.containsKey(key)) {
                name = keys.get(key);
            }
            template.queryParam(name, "{" + key + "}");
        }
        template.fragment(redirectUri.getFragment());
        UriComponents encoded = template.build().expand(query).encode();
        builder.query(encoded.getQuery());
    }

    return builder.build().toUriString();
}

From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java

/**
 * build the url using the path and query params
 * //from   w ww.  j av a 2 s  .c  o  m
 * @param path : the part after the baseUrl
 * @param queryParams this needs to be an even number of strings in the form of paramName,
 *        paramValue....
 */
public static URI createURI(String baseUrl, String path, String... queryParams) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl).path(path);

    if (queryParams != null) {
        if (queryParams.length % 2 != 0) {
            throw new IllegalArgumentException("invalid queryParams count");
        }
        for (int i = 0; i < queryParams.length; i += 2) {
            builder.queryParam(queryParams[i], queryParams[i + 1]);
        }
    }
    return builder.build().encode().toUri();
}

From source file:org.openlmis.auth.service.BaseCommunicationService.java

protected URI buildUri(String url, Map<String, ?> params) {
    UriComponentsBuilder builder = UriComponentsBuilder.newInstance().uri(URI.create(url));

    params.entrySet().forEach(e -> builder.queryParam(e.getKey(), e.getValue()));

    return builder.build(true).toUri();
}