@Override public VaultServiceInfo createServiceInfo(String id, String uri) { UriComponents uriInfo = UriComponentsBuilder.fromUriString(uri).build(); String address = UriComponentsBuilder.newInstance() // .scheme(uriInfo.getScheme()) // .host(uriInfo.getHost()) // .port(uriInfo.getPort()) // .build().toString(); MultiValueMap<String, String> queryParams = uriInfo.getQueryParams(); String token = queryParams.getFirst("token"); Assert.hasText(token, "Token (token=…) must not be empty"); Map<String, String> backends = getBackends(queryParams, backendPattern); Map<String, String> sharedBackends = getBackends(queryParams, sharedBackendPattern); return new VaultServiceInfo(id, address, token.toCharArray(), backends, sharedBackends); }
/** * Return a {@link ResourceSupport} object containing the resources * served by the Data Flow server. * * @return {@code ResourceSupport} object containing the Data Flow server's resources */ @RequestMapping("/") public ResourceSupport info() { ResourceSupport resourceSupport = new ResourceSupport(); resourceSupport.add(new Link(dashboard(""), "dashboard")); resourceSupport.add(entityLinks.linkToCollectionResource(AppRegistrationResource.class).withRel("apps")); resourceSupport.add(entityLinks.linkToCollectionResource(AppStatusResource.class).withRel("runtime/apps")); resourceSupport.add(unescapeTemplateVariables(entityLinks.linkForSingleResource(AppStatusResource.class, "{appId}").withRel("runtime/apps/app"))); resourceSupport.add(unescapeTemplateVariables(entityLinks.linkFor(AppInstanceStatusResource.class, UriComponents.UriTemplateVariables.SKIP_VALUE).withRel("runtime/apps/instances"))); resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDefinitionResource.class).withRel("applications/definitions")); resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDefinitionResource.class, "{name}").withRel("applications/definitions/definition"))); resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDeploymentResource.class).withRel("applications/deployments")); resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDeploymentResource.class, "{name}").withRel("applications/deployments/deployment"))); String completionStreamTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/stream{?start,detailLevel}"); resourceSupport.add(new Link(completionStreamTemplated).withRel("completions/stream")); String completionTaskTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/task{?start,detailLevel}"); resourceSupport.add(new Link(completionTaskTemplated).withRel("completions/task")); return resourceSupport; }
private UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) { CompositeUriComponentsContributor contributor = defaultUriComponentsContributor; int paramCount = method.getParameterTypes().length; int argCount = args.length; if (paramCount != argCount) { throw new IllegalArgumentException("方法参数量为" + paramCount + " 与真实参数量不匹配,真实参数量为" + argCount); } final Map<String, Object> uriVars = new HashMap<>(8); for (int i = 0; i < paramCount; i++) { MethodParameter param = new SynthesizingMethodParameter(method, i); param.initParameterNameDiscovery(parameterNameDiscoverer); contributor.contributeMethodArgument(param, args[i], builder, uriVars); } // We may not have all URI var values, expand only what we have return builder.build().expand(name -> uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE); }
/** * Create Uri Components * @param path for uri * @param queryParams for uri * @param pathParams for uri * @return UriComponents from supplied path, queryParams and pathParams */ public UriComponents createUriComponents(String path, MultiValueMap<String, String> queryParams, Object... pathParams) { UriComponents uriComponentsWithOutQueryParams = UriComponentsBuilder.newInstance() .scheme(config.getScheme()) .host(config.getHost()) .port(config.getPort()) .path(path) .buildAndExpand(pathParams); // Have to build UriComponents for query parameters separately as Expand interprets braces in JSON query string // values as URI template variables to be replaced. UriComponents uriComponents = UriComponentsBuilder.newInstance() .uriComponents(uriComponentsWithOutQueryParams) .queryParams(queryParams) .build() .encode(); return uriComponents; }
/** * Convert model to request parameters and redirect to the given URL. * @see #appendQueryProperties * @see #sendRedirect */ @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException { String targetUrl = createTargetUrl(model, request); targetUrl = updateTargetUrl(targetUrl, model, request, response); FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request); if (!CollectionUtils.isEmpty(flashMap)) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build(); flashMap.setTargetRequestPath(uriComponents.getPath()); flashMap.addTargetRequestParams(uriComponents.getQueryParams()); FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request); if (flashMapManager == null) { throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set"); } flashMapManager.saveOutputFlashMap(flashMap, request, response); } sendRedirect(request, response, targetUrl, this.http10Compatible); }
/** * Whether the given FlashMap matches the current request. * Uses the expected request path and query parameters saved in the FlashMap. */ protected boolean isFlashMapForRequest(FlashMap flashMap, HttpServletRequest request) { String expectedPath = flashMap.getTargetRequestPath(); if (expectedPath != null) { String requestUri = getUrlPathHelper().getOriginatingRequestUri(request); if (!requestUri.equals(expectedPath) && !requestUri.equals(expectedPath + "/")) { return false; } } UriComponents uriComponents = ServletUriComponentsBuilder.fromRequest(request).build(); MultiValueMap<String, String> actualParams = uriComponents.getQueryParams(); MultiValueMap<String, String> expectedParams = flashMap.getTargetRequestParams(); for (String expectedName : expectedParams.keySet()) { List<String> actualValues = actualParams.get(expectedName); if (actualValues == null) { return false; } for (String expectedValue : expectedParams.get(expectedName)) { if (!actualValues.contains(expectedValue)) { return false; } } } return true; }
/** * Initialize a builder with a scheme, host,and port (but not path and query). */ private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) { HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); String scheme = uriComponents.getScheme(); String host = uriComponents.getHost(); int port = uriComponents.getPort(); ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder(); builder.scheme(scheme); builder.host(host); if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) { builder.port(port); } return builder; }
@Test public void fromRequestWithForwardedHostAndPort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setScheme("http"); request.setServerName("localhost"); request.setServerPort(80); request.setRequestURI("/mvc-showcase"); request.addHeader("X-Forwarded-Proto", "https"); request.addHeader("X-Forwarded-Host", "84.198.58.199"); request.addHeader("X-Forwarded-Port", "443"); HttpRequest httpRequest = new ServletServerHttpRequest(request); UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build(); assertEquals("https://84.198.58.199/mvc-showcase", result.toString()); }
private void contextPath(MockHttpServletRequest request, UriComponents uriComponents) { if (this.contextPath == null) { List<String> pathSegments = uriComponents.getPathSegments(); if (pathSegments.isEmpty()) { request.setContextPath(""); } else { request.setContextPath("/" + pathSegments.get(0)); } } else { if (!uriComponents.getPath().startsWith(this.contextPath)) { throw new IllegalArgumentException(uriComponents.getPath() + " should start with contextPath " + this.contextPath); } request.setContextPath(this.contextPath); } }
private void params(MockHttpServletRequest request, UriComponents uriComponents) { for (Entry<String, List<String>> entry : uriComponents.getQueryParams().entrySet()) { String name = entry.getKey(); for (String value : entry.getValue()) { try { value = (value != null ? URLDecoder.decode(value, "UTF-8") : ""); request.addParameter(name, value); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } for (NameValuePair param : this.webRequest.getRequestParameters()) { request.addParameter(param.getName(), param.getValue()); } }
@Test public void requiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception { String redirect = mockMvc.perform(get("/sign/pivotal")) .andExpect(status().is3xxRedirection()) .andReturn().getResponse().getRedirectedUrl(); UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build(); assertThat(redirectComponent.getScheme()).isEqualTo("https"); assertThat(redirectComponent.getHost()).isEqualTo("github.com"); MultiValueMap<String, String> params = redirectComponent.getQueryParams(); assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId()); assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github"); assertThat(params.getFirst("state")).isNotNull(); String[] scopes = urlDecode(params.getFirst("scope")).split(","); assertThat(scopes).containsOnly("user:email"); }
@Test public void adminRequiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception { String redirect = mockMvc.perform(get("/admin/cla/link")).andExpect(status().is3xxRedirection()).andReturn() .getResponse().getRedirectedUrl(); UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build(); assertThat(redirectComponent.getScheme()).isEqualTo("https"); assertThat(redirectComponent.getHost()).isEqualTo("github.com"); MultiValueMap<String, String> params = redirectComponent.getQueryParams(); assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId()); assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github"); assertThat(params.getFirst("state")).isNotNull(); String[] scopes = urlDecode(params.getFirst("scope")).split(","); assertThat(scopes).containsOnly("user:email", "repo:status", "admin:repo_hook", "admin:org_hook", "read:org"); }
private void populateContextPath( Model model, HttpServletRequest request ) { UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build(); String contextPathString = contextPath.toString(); String xForwardedProto = request.getHeader( "X-Forwarded-Proto" ); if ( xForwardedProto != null ) { if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) ) { contextPathString = contextPathString.replace( "http://", "https://" ); } else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) ) { contextPathString = contextPathString.replace( "https://", "http://" ); } } model.addAttribute( "contextPath", contextPathString ); }
void copyQueryParams(UriComponents uriComponents, MockHttpServletRequest servletRequest){ try { if (uriComponents.getQuery() != null) { String query = UriUtils.decode(uriComponents.getQuery(), UTF_8); servletRequest.setQueryString(query); } for (Entry<String, List<String>> entry : uriComponents.getQueryParams().entrySet()) { for (String value : entry.getValue()) { servletRequest.addParameter( UriUtils.decode(entry.getKey(), UTF_8), UriUtils.decode(value, UTF_8)); } } } catch (UnsupportedEncodingException ex) { // shouldn't happen } }
String getRedirectUrl(HttpServletRequest request) { String requestUrl = request.getRequestURL().toString(); try { URI uri = new URI(requestUrl); UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("https") .host(uri.getHost()) .path(uri.getPath()) .query(uri.getQuery()) .fragment(uri.getFragment()) .build(); return uriComponents.toUriString(); } catch (URISyntaxException e) { throw new RuntimeException("Could not parse URL [" + requestUrl + "]", e); } }
Object fixLink(Object value) { if (!(value instanceof String)) { return value; } String href = (String) value; Matcher urlWithServiceNameMatcher = urlWithServiceNamePattern.matcher(href); Matcher standardUrlMatcher = standardUrlPattern.matcher(href); if (!standardUrlMatcher.matches() && urlWithServiceNameMatcher.matches()) { String possibleServiceName = urlWithServiceNameMatcher.group(1); log.debug("Possible service name: " + possibleServiceName); if (services.contains(possibleServiceName)) { log.debug("Service found"); String gatewayPath = serviceRouteMapper.apply(possibleServiceName); String originalRestPath = urlWithServiceNameMatcher.group(2); ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder.fromCurrentRequest(); UriComponents uriComponents = servletUriComponentsBuilder.replacePath(gatewayPath).path(originalRestPath).build(); log.debug("Mapping " + value + " to " + uriComponents); return uriComponents.toString(); } } return href; }
public static void populateContextPath( Model model, HttpServletRequest request ) { UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build(); String contextPathString = contextPath.toString(); String xForwardedProto = request.getHeader( "X-Forwarded-Proto" ); if ( xForwardedProto != null ) { if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) ) { contextPathString = contextPathString.replace( "http://", "https://" ); } else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) ) { contextPathString = contextPathString.replace( "https://", "http://" ); } } model.addAttribute( "contextPath", contextPathString ); }
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception { MockHttpServletRequestBuilder content = post(uriComponents.toUri()); if(mediaType!=null){ content.contentType(mediaType); } if(requestBodyCotnent!=null){ content.content(requestBodyCotnent); } MvcResult mvcResult = mockMvc.perform(content). andExpect(status().is(status)). andReturn(); String contentAsString = mvcResult.getResponse().getContentAsString(); return contentAsString; }
protected String genericGet(UriComponents uriComponents,MediaType mediaType,String requestBodyCotnent) throws Exception { MockHttpServletRequestBuilder content = get(uriComponents.toUri()); if(mediaType!=null){ content.contentType(mediaType); } if(requestBodyCotnent!=null){ content.content(requestBodyCotnent); } MvcResult mvcResult = mockMvc.perform(content). andExpect(status().isOk()). andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String contentAsString = response.getContentAsString(); LOGGER.info("post location header: " + response.getHeaderValue("LOCATION")); LOGGER.info("post contentAsString: " + contentAsString); return contentAsString; }
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception { MockHttpServletRequestBuilder content = post(uriComponents.toUri()); if(mediaType!=null){ content.contentType(mediaType); } if(requestBodyCotnent!=null){ content.content(requestBodyCotnent); } MvcResult mvcResult = mockMvc.perform(content). andExpect(status().is(status)). andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String contentAsString = response.getContentAsString(); LOGGER.info("post location header: " + response.getHeaderValue("LOCATION")); LOGGER.info("post contentAsString: " + contentAsString); return contentAsString; }
@Test public void updateFeedBackNotModifiedTest() throws Exception { FeedBack feedBack = createFeedBack(USER_NAME, BOOK_ID); FeedBack save = feedBackRepository.save(feedBack); feedBack.setFeedbackBody("new FeedBack body"); UriComponents updateFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/{feedBackId}").buildAndExpand(save.getId()); mockMvc.perform(put(updateFeedBackTestUriComponents.toUri()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(feedBack))) .andExpect(status().isNoContent()); List<FeedBack> feedBackAux = feedBackRepository.getFeedBack(USER_NAME, BOOK_ID); assertNotNull(feedBackAux); assertEquals(1, feedBackAux.size()); assertEquals(feedBackAux.get(0).getFeedbackBody(), feedBack.getFeedbackBody()); LOGGER.info(feedBackAux.toString()); }
@Test public void getFeedBackByBookIdWithFiltringTest() throws Exception { FeedBack feedBack = createFeedBack(USER_NAME, BOOK_ID); FeedBack save = feedBackRepository.save(feedBack); UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/bookId/{bookId}/data") .queryParam("filterQuery", "score") .buildAndExpand(save.getBookId()); String result = genericGet(getFeedBackTestUriComponents); List<Map<String,Object>> scores = new ArrayList<>(); Map<String,Object> resultMap = new HashMap<>(); resultMap.put("score",feedBack.getScore()); scores.add(resultMap); assertEquals(objectMapper.writeValueAsString(scores), result); }
@Test public void getFeedBackBatchWithoutFiltringTest() throws Exception { FeedBack save; Random random = new Random(); List<Map<String,String>> mapList = new ArrayList<>(); Map<String,String> stringStringMap; List<FeedBack> expectedFeedBackResult = new ArrayList<>(); for(int j = 0 ; j < 10 ; j++) { save = feedBackRepository.save(createFeedBack(USER_NAME, String.valueOf(random.nextLong()))); stringStringMap = new HashMap<>(); stringStringMap.put("userName", save.getUserName()); stringStringMap.put("bookId", save.getBookId()); expectedFeedBackResult.add(save); mapList.add(stringStringMap); } UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/batch").build(); String result = genericGet(getFeedBackTestUriComponents,MediaType.APPLICATION_JSON,objectMapper.writeValueAsString(mapList)); assertEquals(objectMapper.writeValueAsString(expectedFeedBackResult), result); }
@Test public void getFeedBackBatchWithoutFiltringTest() throws Exception { Random random = new Random(); List<Map<String,String>> mapList = new ArrayList<>(); Map<String,String> stringStringMap = new HashMap<>(); for(int j = 0 ; j < 10 ; j++) { stringStringMap.put("userName", String.valueOf(random.nextInt())); stringStringMap.put("bookId", String.valueOf(random.nextInt())); mapList.add(stringStringMap); } UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/batch").build(); String result = genericGet(getFeedBackTestUriComponents,MediaType.APPLICATION_JSON,objectMapper.writeValueAsString(mapList)); Assert.assertEquals(result, "[]"); }
@Test public void successfulSaveBookTest() throws Exception { PdfBookMaster activeMqPdfBookMaster = PdfBookMasterTestFactory.pdfBookMaster(BookTestFactory.testBookWithExtensions); UriComponents uriComponents = fromPath("/bookService/book").build(); mockMvc.perform(fileUpload(uriComponents.toUri()) .file((MockMultipartFile) activeMqPdfBookMaster.getBookFile()) .param("bookName", activeMqPdfBookMaster.getBookName()) .param("author", activeMqPdfBookMaster.getAuthor()) .param("contentType", activeMqPdfBookMaster.getBookFile().getContentType()) .param("description", activeMqPdfBookMaster.getDescription()) .accept(MediaType.MULTIPART_FORM_DATA)) .andExpect(status().isAccepted()); LOGGER.info("please wait for the job completes"); Message receiveMessage = jmsTemplate.receive("createBookResultQueue"); LOGGER.info(receiveMessage.toString()); }
protected String genericPost(UriComponents uriComponents, int status, MediaType mediaType, String requestBodyCotnent) throws Exception { MockHttpServletRequestBuilder content = post(uriComponents.toUri()); if (mediaType != null) { content.contentType(mediaType); } if (requestBodyCotnent != null) { content.content(requestBodyCotnent); } MvcResult mvcResult = mockMvc.perform(content). andExpect(status().is(status)). andReturn(); return mvcResult.getResponse().getContentAsString(); }
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception { MockHttpServletRequestBuilder content = post(uriComponents.toUri()); if(mediaType!=null){ content.contentType(mediaType); } if(requestBodyCotnent!=null){ content.content(requestBodyCotnent); } MvcResult mvcResult = mockMvc.perform(content). andExpect(status().is(status)). andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); LOGGER.info("post location header: " + response.getHeaderValue("LOCATION")); return response.getContentAsString(); }
private static void testConnection(VistaAccount vac, String rpcContext, String rpcName) throws Exception { System.out.println("Testing account: "+vac.name); UriComponents uri = UriComponentsBuilder.newInstance() .scheme(VISTA_RPC_BROKER_SCHEME) .userInfo(vac.accessCode + ";" + vac.verifyCode) .host(vac.host) .port(vac.port) .pathSegment(rpcContext, rpcName).build(); RpcTemplate t = new RpcTemplate(); try { RpcResponse r = t.execute(uri.toUriString()); System.out.println("CONNECTION SUCCESSFUL: elapsed millis=" + r.getElapsedMillis()); } catch (DataAccessException e) { System.out.println("CONNECTION FAILURE: " + e.getCause().getMessage()); } finally { t.destroy(); } }
private static String obtainUrlLocation(ServiceInstance instance, UriComponents current, String path, String swaggerHost){ String managementPath = ""; if (instance.getMetadata().containsKey("managementPath")) { managementPath = instance.getMetadata().get("managementPath"); } String hostUrl; if (swaggerHost!=null && swaggerHost.length()>0){ hostUrl=swaggerHost; }else { //tries to findout the host if (("https".equals(current.getScheme()) && 443 == current.getPort()) || ("http".equals(current.getScheme()) && 80 == current.getPort()) || -1 == current.getPort()) { //default ports hostUrl = String.format("%s://%s", current.getScheme(), current.getHost()); } else { //custom ports hostUrl = String.format("%s://%s:%d", current.getScheme(), current.getHost(), current.getPort()); } } return hostUrl + managementPath + path; }
/** {@inheritDoc} */ @Override @RequestMapping(value = "", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String orgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) { if (logger.isDebugEnabled()) { logger.debug("Redering suis report..."); } // 自動的にリダイレクトリンクを構築 UriComponents uriComponents = UriComponentsBuilder.fromUriString(Constants.SUIS_PATH + "/{orgCode}/{currentQuarter}").build(); String yearQuater = DateUtil.getCurrentQuarter(businessDay); URI uri = uriComponents.expand(proGNo, orgCode, yearQuater).encode().toUri(); logger.info("Redirect to suis screen with params in session..."); return "redirect:" + uri.toString(); }
@Test public void construct_uri_queryparmeter_spring () { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("http") .host("www.leveluplunch.com") .path("/{lanuage}/{type}/") .queryParam("test", "a", "b") .build() .expand("java", "examples") .encode(); assertEquals("http://www.leveluplunch.com/java/examples/?test=a&test=b", uriComponents.toUriString()); }
@Test public void replace_query_parameter () { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("primaryKey=987"); UriComponents ucb = ServletUriComponentsBuilder .fromRequest(request) .replaceQueryParam("primaryKey", "{id}") .build() .expand("123") .encode(); assertEquals("http://localhost?primaryKey=123", ucb.toString()); }
@Test public void replace_path () { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/java/examples"); UriComponents ucb = ServletUriComponentsBuilder .fromRequest(request) .replacePath("/java/exercises") .build() .encode(); URI uri = ucb.toUri(); assertEquals("http://localhost/java/exercises", uri.toString()); }
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequest protectedResourceRequest = new HttpRequestDecorator(request) { @Override public URI getURI() { String ts = Long.toString(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); String hash = DigestUtils.sha1Hex(sharedSecret + ts).toLowerCase(); UriComponentsBuilder builder = UriComponentsBuilder.fromUri(super.getURI()); builder.queryParam("api_key", apiKey); builder.queryParam("ts", ts); builder.queryParam("hash", hash); // all params are already encoded at this point UriComponents uriComponents = builder.build(true); logger.debug("requesting SlideShare API: " + uriComponents.toUriString()); return uriComponents.toUri(); } }; return execution.execute(protectedResourceRequest, body); }
/** * 회원 프로필 이미지 URL을 생성한다. * * @param sizeType size 타입 * @param id UserImage의 ID */ public String generateUserPictureUrl(Constants.IMAGE_SIZE_TYPE sizeType, String id) { if (StringUtils.isBlank(id)) return null; String urlPathUserPicture = null; switch (sizeType) { case LARGE: urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureLarge(); break; case SMALL: urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureSmall(); break; } UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getApiServerUrl()) .path("/{urlPathGallery}/{id}") .buildAndExpand(urlPathUserPicture, id); return uriComponents.toUriString(); }
private URI createUri(String uriTemplate, UriComponentsBuilder builder, UriComponents uriComponents) { String strUri = uriComponents.toUriString(); if (isCrossApp(uriTemplate, builder)) { int idx = strUri.indexOf('/', RestConst.URI_PREFIX.length()); strUri = strUri.substring(0, idx) + ":" + strUri.substring(idx + 1); } try { // Avoid further encoding (in the case of strictEncoding=true) return new URI(strUri); } catch (URISyntaxException ex) { throw new IllegalStateException("Could not create URI object: " + ex.getMessage(), ex); } }