List of usage examples for org.springframework.web.util UriComponentsBuilder build
@Override
public URI build(Map<String, ?> uriVariables)
From source file:org.openlmis.fulfillment.service.request.RequestHelper.java
/** * Creates a {@link URI} from the given string representation and with the given parameters. *///w ww . java 2 s . co m public static URI createUri(String url, RequestParameters parameters) { UriComponentsBuilder builder = UriComponentsBuilder.newInstance().uri(URI.create(url)); RequestParameters.init().setAll(parameters).forEach(e -> e.getValue().forEach(one -> { try { builder.queryParam(e.getKey(), UriUtils.encodeQueryParam(String.valueOf(one), StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException ex) { throw new EncodingException(ex); } })); return builder.build(true).toUri(); }
From source file:org.openlmis.notification.web.BaseWebIntegrationTest.java
private 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(); }
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;//from 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.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken, Authentication authUser) {//from w w w. j ava 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(); }
From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java
@Test @Ignore// w ww . ja v a 2 s. c om public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception { useTestWorkspace("brouder_sylvie"); login("george.washington", "1234"); /* * upload the test workflow */ MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE, new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE)); MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload( "/workflows/import").accept(MediaType.ALL).session(httpSession); mockMultipartHttpServletRequestBuilder.file(mockMultipartFile); ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString()); Map<String, Object> workflow = Helper.deserialize(content, Map.class); assertNotNull("workflow is null", workflow); Integer workflowId = (Integer) workflow.get("id"); /* * create a project and an experiment to associate the job for the workflow with * while doing that, make sure we save all the IDs associated to post it with the job */ MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects") .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); Map<String, Object> map = Helper.deserialize(content, Map.class); Integer projectId = (Integer) map.get("id"); mockHttpServletRequestBuilder = post("/experiments") .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); map = Helper.deserialize(content, Map.class); Integer experimentId = (Integer) map.get("id"); /* * create a job associated with the project, experiment and workflow we just created */ mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString()) .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString()) .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); /* * forwarded to job/submit/jobId */ String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl(); mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * redirected to jobs/task/jobId */ String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * we're at UT1 in the workflow */ String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1); TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task"); String taskId = task.getId(); String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28"; String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654"; // For buttton 1 UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); //uriBuilder.queryParam("redirect_uri", "code"); uriBuilder.queryParam("client_id", username); URL url = new URL(uriBuilder.build(true).toUriString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String userpass = username + ":" + password; String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); String res = IOUtils.toString(connection.getInputStream()); Map<String, Object> responseMap = Helper.deserialize(res, Map.class); String code = (String) responseMap.get("code"); uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); String uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // For Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); uriBuilder.queryParam("client_id", username); url = new URL(uriBuilder.build(true).toUriString()); connection = (HttpsURLConnection) url.openConnection(); userpass = username + ":" + password; basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); res = IOUtils.toString(connection.getInputStream()); responseMap = Helper.deserialize(res, Map.class); code = (String) responseMap.get("code"); // For button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // Getting accessToken only from one button String accessToken = ""; String[] urlParts = redirectedUrl.split("&"); for (String urlPart : urlParts) { if (urlPart.contains("accessToken")) { String[] accessTokenPair = urlPart.split("="); accessToken = accessTokenPair[1]; break; } } //Button 1 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //For getting Storage Files (an abstract button called browsefile3) uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("multiple", true); uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); //FileSelect uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam("fileId", 1); uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri, "UTF-8"); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1"; MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder( multipartBoundary); multiPartFileContentBuilder.addField("autoGenerated", "true"); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); multiPartFileContentBuilder.addField("isIframe", "true"); multiPartFileContentBuilder.addField("experimentId", ""); multiPartFileContentBuilder.addField("projectId", ""); multiPartFileContentBuilder .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", ""); String taskContent = multiPartFileContentBuilder.build(); // /rest/objectus post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/") .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "") .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR"; multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); taskContent = multiPartFileContentBuilder.build(); // /jobs/task post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task") .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); deleteDatasetEntries(templateId); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) { if (authorizationCode == null) { throw new IllegalStateException("No authorization code found in the current request scope."); }/*from ww w .ja va 2s. com*/ UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri()); template.queryParam("code", encode(authorizationCode)); String state = authorizationRequest.getState(); if (state != null) { template.queryParam("state", encode(state)); } return template.build(true).toUriString(); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, boolean fragment) { if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) { // we have no redirect for the user. very sad. throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure);/*www. java 2 s . c o m*/ } UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri()); StringBuilder values = new StringBuilder(); values.append("error=" + encode(failure.getOAuth2ErrorCode())); values.append("&error_description=" + encode(failure.getMessage())); if (authorizationRequest.getState() != null) { values.append("&state=" + encode(authorizationRequest.getState())); } if (failure.getAdditionalInformation() != null) { for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) { values.append("&" + encode(additionalInfo.getKey()) + "=" + encode(additionalInfo.getValue())); } } if (fragment) { template.fragment(values.toString()); } else { template.query(values.toString()); } return template.build(true).toUriString(); }
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(); }
From source file:org.springframework.security.oauth2.provider.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;/*from ww w .j a v a2 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 (keys != null && 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(); }