List of usage examples for org.springframework.web.util UriComponentsBuilder build
public UriComponents build()
From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java
@Test public void obtainTokenFromOuth2LoginEndpoint() throws Exception { obtainAuthorizationCode();/* w w w . ja va2 s .com*/ UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath); // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in builder.queryParam("client_id", getClientId()); builder.queryParam("grant_type", "authorization_code"); builder.queryParam("code", authorizationCode); builder.queryParam("redirect_uri", "http://anywhere"); // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code) HttpHeaders headers = new HttpHeaders(); Encoder encoder = Base64.getEncoder(); headers.add("Authorization", "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes())); HttpEntity<String> entity = new HttpEntity<>("", headers); ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class); // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token. // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the // redirect_uri with the token after # assertEquals(HttpStatus.OK, result2.getStatusCode()); // Obtain and keep the token accessToken = result2.getBody().getValue(); assertNotNull(accessToken); refreshToken = result2.getBody().getRefreshToken().getValue(); assertNotNull(refreshToken); }
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 ww w . j a v a 2s.com 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.openmhealth.shim.ihealth.IHealthShim.java
@Override protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final IHealthDataTypes dataType; try {// ww w . j a va2 s.c om dataType = 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."); } OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime(); /* The physical activity point handles start and end datetimes differently than the other endpoints. It requires use to include the range until the beginning of the next day. */ if (dataType == PHYSICAL_ACTIVITY) { endDate = endDate.plusDays(1); } // SC and SV values are client-based keys that are unique to each endpoint within a project String scValue = getScValue(); List<String> svValues = getSvValues(dataType); List<JsonNode> responseEntities = newArrayList(); int i = 0; // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit // requests to each of these endpoints, map the responses separately and then combine them for (String endPoint : dataType.getEndPoint()) { UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL); // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using // getData to trigger Spring to conduct the OAuth exchange String userId = "uk"; if (shimDataRequest.getAccessParameters() != null) { OAuth2AccessToken token = SerializationUtils .deserialize(shimDataRequest.getAccessParameters().getSerializedToken()); userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID")); uriBuilder.queryParam("access_token", token.getValue()); } uriBuilder.path("/user/").path(userId + "/").path(endPoint) .queryParam("client_id", restTemplate.getResource().getClientId()) .queryParam("client_secret", restTemplate.getResource().getClientSecret()) .queryParam("start_time", startDate.toEpochSecond()) .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default") .queryParam("sc", scValue).queryParam("sv", svValues.get(i)); ResponseEntity<JsonNode> responseEntity; try { URI url = uriBuilder.build().encode().toUri(); responseEntity = restTemplate.getForEntity(url, JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for iHealth data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { IHealthDataPointMapper mapper; switch (dataType) { case PHYSICAL_ACTIVITY: mapper = new IHealthPhysicalActivityDataPointMapper(); break; case BLOOD_GLUCOSE: mapper = new IHealthBloodGlucoseDataPointMapper(); break; case BLOOD_PRESSURE: mapper = new IHealthBloodPressureDataPointMapper(); break; case BODY_WEIGHT: mapper = new IHealthBodyWeightDataPointMapper(); break; case BODY_MASS_INDEX: mapper = new IHealthBodyMassIndexDataPointMapper(); break; case STEP_COUNT: mapper = new IHealthStepCountDataPointMapper(); break; case SLEEP_DURATION: mapper = new IHealthSleepDurationDataPointMapper(); break; case HEART_RATE: // there are two different mappers for heart rate because the data can come from two endpoints if (endPoint == "bp.json") { mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper(); break; } else if (endPoint == "spo2.json") { mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper(); break; } case OXYGEN_SATURATION: mapper = new IHealthOxygenSaturationDataPointMapper(); break; default: throw new UnsupportedOperationException(); } responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody()))); } else { responseEntities.add(responseEntity.getBody()); } i++; } return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities)); }
From source file:org.openmhealth.shim.withings.WithingsShim.java
URI createWithingsRequestUri(ShimDataRequest shimDataRequest, String userid, WithingsDataType withingsDataType) { MultiValueMap<String, String> dateTimeMap = new LinkedMultiValueMap<>(); if (withingsDataType.usesUnixEpochSecondsDate || isPartnerAccessActivityMeasure(withingsDataType)) { //the partner access endpoints for activity also use epoch secs dateTimeMap.add("startdate", String.valueOf(shimDataRequest.getStartDateTime().toEpochSecond())); dateTimeMap.add("enddate", String.valueOf(shimDataRequest.getEndDateTime().plusDays(1).toEpochSecond())); } else {//from w w w .j a v a2s. c o m dateTimeMap.add("startdateymd", shimDataRequest.getStartDateTime().toLocalDate().toString()); dateTimeMap.add("enddateymd", shimDataRequest.getEndDateTime().toLocalDate().toString()); } UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL) .pathSegment(withingsDataType.getEndpoint()); String measureParameter; if (isPartnerAccessActivityMeasure(withingsDataType)) { // partner level access allows greater detail around activity, but uses a different endpoint measureParameter = PARTNER_ACCESS_ACTIVITY_ENDPOINT; } else { measureParameter = withingsDataType.getMeasureParameter(); } uriComponentsBuilder.queryParam("action", measureParameter).queryParam("userid", userid) .queryParams(dateTimeMap); // if it's a body measure if (Objects.equals(withingsDataType.getMeasureParameter(), "getmeas")) { /* The Withings API allows us to query for single body measures, which we take advantage of to reduce unnecessary data transfer. However, since blood pressure is represented as two separate measures, namely a diastolic and a systolic measure, when the measure type is blood pressure we ask for all measures and then filter out the ones we don't care about. */ if (withingsDataType != WithingsDataType.BLOOD_PRESSURE) { WithingsBodyMeasureType measureType = WithingsBodyMeasureType.valueOf(withingsDataType.name()); uriComponentsBuilder.queryParam("meastype", measureType.getMagicNumber()); } uriComponentsBuilder.queryParam("category", 1); //filter out goal datapoints } UriComponents uriComponents = uriComponentsBuilder.build(); return uriComponents.toUri(); }
From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java
/** * build the url using the path and query params * //from w w w. j a v a 2 s. c om * @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.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testGetTokenScopesNotInAuthentication() throws Exception { String basicDigestHeaderValue = "Basic " + new String( org.apache.commons.codec.binary.Base64.encodeBase64(("identity:identitysecret").getBytes())); ScimUser user = setUpUser(generator.generate() + "@test.org"); String zoneadmingroup = "zones." + generator.generate() + ".admin"; ScimGroup group = new ScimGroup(null, zoneadmingroup, IdentityZone.getUaa().getId()); group = groupProvisioning.create(group); ScimGroupMember member = new ScimGroupMember(user.getId()); groupMembershipManager.addMember(group.getId(), member); MockHttpSession session = getAuthenticatedSession(user); String state = generator.generate(); MockHttpServletRequestBuilder authRequest = get("/oauth/authorize") .header("Authorization", basicDigestHeaderValue).header("Accept", MediaType.APPLICATION_JSON_VALUE) .session(session).param(OAuth2Utils.GRANT_TYPE, "authorization_code") .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.STATE, state) .param(OAuth2Utils.CLIENT_ID, "identity").param(OAuth2Utils.REDIRECT_URI, "http://localhost/test"); MvcResult result = getMockMvc().perform(authRequest).andExpect(status().is3xxRedirection()).andReturn(); String location = result.getResponse().getHeader("Location"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(location); String code = builder.build().getQueryParams().get("code").get(0); authRequest = post("/oauth/token").header("Authorization", basicDigestHeaderValue) .header("Accept", MediaType.APPLICATION_JSON_VALUE) .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.RESPONSE_TYPE, "token") .param("code", code).param(OAuth2Utils.CLIENT_ID, "identity") .param(OAuth2Utils.REDIRECT_URI, "http://localhost/test"); result = getMockMvc().perform(authRequest).andExpect(status().is2xxSuccessful()).andReturn(); OAuthToken oauthToken = JsonUtils.readValue(result.getResponse().getContentAsString(), OAuthToken.class); OAuth2Authentication a1 = tokenServices.loadAuthentication(oauthToken.accessToken); assertEquals(4, a1.getOAuth2Request().getScope().size()); assertThat(a1.getOAuth2Request().getScope(), containsInAnyOrder( new String[] { zoneadmingroup, "openid", "cloud_controller.read", "cloud_controller.write" })); }
From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java
public static String getUserOAuthAccessTokenAuthCode(MockMvc mockMvc, String clientId, String clientSecret, String userId, String username, String password, String scope) throws Exception { String basicDigestHeaderValue = "Basic " + new String( org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + clientSecret).getBytes())); UaaPrincipal p = new UaaPrincipal(userId, username, "test@test.org", OriginKeys.UAA, "", IdentityZoneHolder.get().getId()); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(p, "", UaaAuthority.USER_AUTHORITIES); Assert.assertTrue(auth.isAuthenticated()); SecurityContextHolder.getContext().setAuthentication(auth); MockHttpSession session = new MockHttpSession(); session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, new MockSecurityContext(auth)); String state = new RandomValueStringGenerator().generate(); MockHttpServletRequestBuilder authRequest = get("/oauth/authorize") .header("Authorization", basicDigestHeaderValue).header("Accept", MediaType.APPLICATION_JSON_VALUE) .session(session).param(OAuth2Utils.GRANT_TYPE, "authorization_code") .param(OAuth2Utils.RESPONSE_TYPE, "code") .param(TokenConstants.REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE).param(OAuth2Utils.STATE, state) .param(OAuth2Utils.CLIENT_ID, clientId).param(OAuth2Utils.REDIRECT_URI, "http://localhost/test"); if (StringUtils.hasText(scope)) { authRequest.param(OAuth2Utils.SCOPE, scope); }// w w w.j ava2 s.c o m MvcResult result = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn(); String location = result.getResponse().getHeader("Location"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(location); String code = builder.build().getQueryParams().get("code").get(0); authRequest = post("/oauth/token").header("Authorization", basicDigestHeaderValue) .header("Accept", MediaType.APPLICATION_JSON_VALUE) .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.RESPONSE_TYPE, "token") .param("code", code).param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, "http://localhost/test"); if (StringUtils.hasText(scope)) { authRequest.param(OAuth2Utils.SCOPE, scope); } result = mockMvc.perform(authRequest).andExpect(status().is2xxSuccessful()).andReturn(); InjectedMockContextTest.OAuthToken oauthToken = JsonUtils .readValue(result.getResponse().getContentAsString(), InjectedMockContextTest.OAuthToken.class); return oauthToken.accessToken; }
From source file:org.dspace.app.rest.link.search.SearchFacetEntryHalLinkFactory.java
@Override protected void addLinks(SearchFacetEntryResource halResource, Pageable pageable, LinkedList<Link> list) throws Exception { SearchFacetEntryRest facetData = halResource.getFacetData(); DiscoveryResultsRest searchData = halResource.getSearchData(); String query = searchData == null ? null : searchData.getQuery(); String dsoType = searchData == null ? null : searchData.getDsoType(); String scope = searchData == null ? null : searchData.getScope(); UriComponentsBuilder uriBuilder = uriBuilder( getMethodOn().getFacetValues(facetData.getName(), null, query, dsoType, scope, null, null)); addFilterParams(uriBuilder, searchData); //If our rest data contains a list of values, construct the page links. Otherwise, only add a self link if (CollectionUtils.isNotEmpty(facetData.getValues())) { PageImpl page = new PageImpl<>(facetData.getValues(), new PageRequest(0, facetData.getFacetLimit()), facetData.getValues().size() + (BooleanUtils.isTrue(facetData.isHasMore()) ? 1 : 0)); halResource.setPageHeader(new EmbeddedPageHeader(uriBuilder, page, false)); } else {// ww w . j a va 2 s . c o m list.add(buildLink(Link.REL_SELF, uriBuilder.build().toUriString())); } }