private String path(UriComponentsBuilder builder, Page page, boolean encode) { Map<String, Object> params = new HashMap<>(); PageTree pageTree = (PageTree) processingContext.getContext().getVariables().get("PAGE_TREE_ALL"); // PageTree pageTree = // defaultModelAttributeService.readPageTree(LocaleContextHolder.getLocale().getLanguage()); List<String> codes = new LinkedList<>(); Page parent = page.getParent(); while (parent != null) { codes.add(parent.getCode()); parent = (parent.getParent() != null) ? pageTree.getPageByCode(parent.getParent().getCode()) : null; } Collections.reverse(codes); codes.add(page.getCode()); for (int i = 0; i < codes.size(); i++) { String key = "code" + i; builder.path("/{" + key + "}"); params.put(key, codes.get(i)); } UriComponents components = builder.buildAndExpand(params); if (encode) { components = components.encode(); } return components.toUriString(); }
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; 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(); }
@Test public void test() { UriComponents uriComponentsBuilder = UriComponentsBuilder.fromUriString("http://localhost/{userId}/{age}") .build() .expand("lng1982", 32) .encode(); String test = uriComponentsBuilder.toString(); assertThat(test, is("http://localhost/lng1982/32")); }
// @Test public void testURI() throws Exception { UriComponents uriComponents = UriComponentsBuilder.newInstance() .path("/board/read") .queryParam("bno", 12) .queryParam("perPageNum", 20) .build(); logger.info("/board/read?bno=12&perPageNum=20"); logger.info(uriComponents.toString()); }
@Test public void usesBaseUriIfConfigured() { UriComponents baseUri = UriComponentsBuilder.fromUriString("http://foo:9090").build(); PagedResourcesAssembler<Person> assembler = new PagedResourcesAssembler<Person>(resolver, baseUri); PagedResources<Resource<Person>> resources = assembler.toResource(createPage(1)); assertThat(resources.getLink(Link.REL_PREVIOUS).getHref(), startsWith(baseUri.toUriString())); assertThat(resources.getLink(Link.REL_NEXT).getHref(), startsWith(baseUri.toUriString())); }
/** * Create a data group * * @param doi * @param webAddress * @param title * @return */ @POST @Authenticated @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Response mint( @FormParam("doi") String doi, @FormParam("webAddress") String webAddress, @FormParam("graph") String graph, @FormParam("title") String title, @FormParam("resourceType") String resourceTypeString, @FormParam("resourceTypesMinusDataset") Integer resourceTypesMinusDataset, @FormParam("finalCopy") @DefaultValue("false") Boolean finalCopy) { // If resourceType is specified by an integer, then use that to set the String resourceType. // If the user omits try { if (resourceTypesMinusDataset != null && resourceTypesMinusDataset > 0) { resourceTypeString = new ResourceTypes().get(resourceTypesMinusDataset).uri; } } catch (IndexOutOfBoundsException e) { throw new BadRequestException( "BCID System Unable to set resource type", "There was an error retrieving the resource type uri. Did you provide a valid resource type?"); } if (resourceTypeString == null || resourceTypeString.isEmpty()) { throw new BadRequestException("ResourceType is required"); } // Mint the Bcid if (title == null || title.isEmpty()) { title = resourceTypeString; } Bcid.BcidBuilder builder = new Bcid.BcidBuilder(resourceTypeString) .ezidRequest(Boolean.valueOf(settingsManager.retrieveValue("ezidRequests"))) .doi(doi) .title(title) .graph(graph) .finalCopy(finalCopy); if (!StringUtils.isEmpty(webAddress)) { UriComponents webAddressComponents = UriComponentsBuilder.fromUriString(webAddress).build(); builder.webAddress(webAddressComponents.toUri()); } Bcid bcid = builder.build(); bcidService.create(bcid, user.getUserId()); // TODO return the bcid object here return Response.ok("{\"identifier\": \"" + bcid.getIdentifier() + "\"}").build(); }
private String path(UriComponentsBuilder builder, Article article, boolean encode) { Map<String, Object> params = new HashMap<>(); builder.path("/{year}/{month}/{day}/{code}"); params.put("year", String.format("%04d", article.getDate().getYear())); params.put("month", String.format("%02d", article.getDate().getMonthOfYear())); params.put("day", String.format("%02d", article.getDate().getDayOfMonth())); params.put("code", article.getCode()); UriComponents components = builder.buildAndExpand(params); if (encode) { components = components.encode(); } return components.toUriString(); }
@Test public void testImplicitGrant() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("client_id", "cf"); postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf"); postBody.add("response_type", "token id_token"); postBody.add("source", "credentials"); postBody.add("username", user.getUserName()); postBody.add("password", secret); ResponseEntity<Void> responseEntity = restOperations.exchange( loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class); Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode()); UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build(); Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost()); Assert.assertEquals("/redirect/cf", locationComponents.getPath()); MultiValueMap<String, String> params = parseFragmentParams(locationComponents); Assert.assertThat(params.get("jti"), not(empty())); Assert.assertEquals("bearer", params.getFirst("token_type")); Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000)); String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" "); Assert.assertThat( Arrays.asList(scopes), containsInAnyOrder( "scim.userids", "password.write", "cloud_controller.write", "openid", "cloud_controller.read", "uaa.user")); validateToken("access_token", params.toSingleValueMap(), scopes, aud); validateToken("id_token", params.toSingleValueMap(), openid, new String[] {"cf"}); }
private MultiValueMap<String, String> parseFragmentParams(UriComponents locationComponents) { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); String[] tuples = locationComponents.getFragment().split("&"); for (String tuple : tuples) { String[] parts = tuple.split("="); params.add(parts[0], parts[1]); } return params; }
/* * (non-Javadoc) * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(java.lang.Object) */ @Override public ControllerLinkBuilder linkTo(Object invocationValue) { Assert.isInstanceOf(LastInvocationAware.class, invocationValue); LastInvocationAware invocations = (LastInvocationAware) invocationValue; MethodInvocation invocation = invocations.getLastInvocation(); Iterator<Object> classMappingParameters = invocations.getObjectParameters(); Method method = invocation.getMethod(); String mapping = DISCOVERER.getMapping(method); UriComponentsBuilder builder = ControllerLinkBuilder.getBuilder().path(mapping); UriTemplate template = new UriTemplate(mapping); Map<String, Object> values = new HashMap<String, Object>(); Iterator<String> names = template.getVariableNames().iterator(); while (classMappingParameters.hasNext()) { values.put(names.next(), classMappingParameters.next()); } for (BoundMethodParameter parameter : PATH_VARIABLE_ACCESSOR.getBoundParameters(invocation)) { values.put(parameter.getVariableName(), parameter.asString()); } for (BoundMethodParameter parameter : REQUEST_PARAM_ACCESSOR.getBoundParameters(invocation)) { Object value = parameter.getValue(); String key = parameter.getVariableName(); if (value instanceof Collection) { for (Object element : (Collection<?>) value) { builder.queryParam(key, element); } } else { builder.queryParam(key, parameter.asString()); } } UriComponents components = applyUriComponentsContributer(builder, invocation).buildAndExpand(values); return new ControllerLinkBuilder(UriComponentsBuilder.fromUri(components.toUri())); }
public CellLine getCellLine(String biosampleId) throws RestClientException { UriComponents uriComponents = UriComponentsBuilder.newInstance() .scheme("https") .host(apiHost) .pathSegment("api", "v0", "cell-lines", biosampleId) .build(); log.trace("URI = " + uriComponents.toUriString()); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "ApiKey " + apiUsername + ":" + apiKey); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<CellLine> responce = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, entity, CellLine.class); log.trace("HTTP code = " + responce.getStatusCode()); return responce.getBody(); }
public GoogleSearchResponse search(String searchString, String referer) { try { if (ValidatorUtil.isNull(referer)) { referer = "http://longfalcon.net"; } String v = "1.0"; String userip = "192.168.0.1"; HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Referer", referer); HttpEntity<?> requestEntity = new HttpEntity(httpHeaders); UriComponents uriComponents = UriComponentsBuilder.fromUriString(_SEARCH_URL) .queryParam("v", v) .queryParam("q", searchString) .queryParam("userip", userip) .build(); ResponseEntity<GoogleSearchResponse> responseEntity = restTemplate.exchange( uriComponents.toUri(), HttpMethod.GET, requestEntity, GoogleSearchResponse.class); HttpStatus statusCode = responseEntity.getStatusCode(); if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) { return responseEntity.getBody(); } else { _log.error( String.format( "Search request: \n%s\n failed with HTTP code %s : %s", uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase())); return null; } } catch (Exception e) { _log.error(e); } return null; }
/** * Returns the tempalte variables for the sort parameter. * * @param parameter must not be {@literal null}. * @return * @since 1.7 */ public TemplateVariables getSortTemplateVariables( MethodParameter parameter, UriComponents template) { String sortParameter = getSortParameter(parameter); MultiValueMap<String, String> queryParameters = template.getQueryParams(); boolean append = !queryParameters.isEmpty(); if (queryParameters.containsKey(sortParameter)) { return TemplateVariables.NONE; } String description = String.format("pagination.%s.description", sortParameter); VariableType type = append ? REQUEST_PARAM_CONTINUED : REQUEST_PARAM; return new TemplateVariables(new TemplateVariable(sortParameter, type, description)); }
// 재발송 로직, public Result resend(SendVO sendReq, HttpServletRequest request, boolean isReal) { // 상품정보와 거래번호를 받아서 나머지 정보를 세팅한다. SendVO sendVO = new SendVO(); // 상품 정보 확인 GoodsVO inGoods = new GoodsVO(); inGoods.setGoods_id(sendReq.getGoods_id()); inGoods.setReal(isReal); // 실상품 or 테스트 상품 구분 GoodsVO goods = adminService.getGoods(inGoods); sendVO.setGoods_id(goods.getGoods_id()); sendVO.setSell_price(goods.getSell_price()); // 발송정보 세팅 sendVO.setGoods_count("1"); // 상품 수량은 1로 고정 sendVO.setRecv_phone(sendReq.getRecv_phone()); sendVO.setSend_phone(sendReq.getSend_phone()); sendVO.setTr_id(sendReq.getTr_id()); sendVO.setMsg(sendReq.getMsg()); restTemplate = new RestTemplate(); params = new LinkedMultiValueMap<String, String>(); UriComponents uriComponents; String baseUrl = ""; // M12 handling, 아직 재발행 로직 없음 if (goods.getProvider() == 1) { } // Coup handling, 쿠프 문서 2.33 거래번호로 재발송 else if (goods.getProvider() == 2) { params.add("CODE", "0424"); params.add("PASS", "hlint123"); params.add("COUPONCODE", goods.getGoods_code()); params.add("SEQNUMBER", sendReq.getTr_id()); // params.add("QTY", sendVO.getGoods_count()); //상품수량은 1개 params.add("HP", sendReq.getRecv_phone()); params.add("CALLBACK", sendReq.getSend_phone()); params.add("TITLE", ""); params.add("ADDMSG", sendReq.getMsg()); // params.add("SELPRICE", goods.getSell_price()); //상품 가격 세팅 // logger.debug(params.toString()); if (isReal) { baseUrl = "http://v3api.inumber.co.kr/ServiceApi.aspx/ServiceCouponSendSeq"; } else { baseUrl = "http://issuev3apitest.m2i.kr:9999/ServiceApi.aspx/ServiceCouponSendSeq"; } try { uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); logger.debug(uriComponents.toUriString()); String strResult = restTemplate.getForObject(uriComponents.toUriString(), String.class); logger.debug("strResult:" + strResult); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(strResult)); Element rootNode = document.getRootElement(); String resultCode = rootNode.getChild("RESULTCODE", rootNode.getNamespace()).getText(); String resultMsg = rootNode.getChild("RESULTMSG", rootNode.getNamespace()).getText(); // 쿠폰 발송 상태 저장 sendVO.setResult_code(resultCode); sendVO.setStatus_code(resultMsg); // 재발송여부 저장 sendVO.setReal(isReal); logger.debug(sendVO.toString()); // adminService.addSend(sendVO); return new Result(Integer.parseInt(resultCode), resultMsg); } catch (Exception e) { e.printStackTrace(); return new Result(100, "Coupon failed"); } } return new Result(500, "내부 오류가 발생하였습니다."); }
public Result send(CouponReqVO couponReq, HttpServletRequest request, boolean isReal) { SendVO sendVO = new SendVO(); if (couponReq.getMid() == null || couponReq.getPassword() == null) { return new Result(100, "필수파라메터 부족"); } // 판매업체 mid와 password가 일치하는지 확인 SellerVO inSeller = new SellerVO(); inSeller.setMid(couponReq.getMid()); inSeller.setPassword(couponReq.getPassword()); SellerVO seller = adminService.getSeller(inSeller); if (seller == null) { return new Result(200, "등록된 판매업체가 아닙니다."); } sendVO.setSeller_id(seller.getSeller_id()); // 등록된 IP인지 확인 String allowed_ip = seller.getAllowed_ip(); if (!allowed_ip.contains(request.getRemoteAddr())) { logger.debug("ip:" + request.getRemoteAddr()); return new Result(300, "허용된 IP가 아닙니다."); } // 상품 정보 확인 GoodsVO inGoods = new GoodsVO(); inGoods.setGoods_code(couponReq.getGoods_code()); inGoods.setReal(isReal); // 실상품 or 테스트 상품 구분 GoodsVO goods = adminService.getGoods(inGoods); if (goods == null) { return new Result(400, "등록된 상품코드가 아닙니다."); } sendVO.setGoods_id(goods.getGoods_id()); // 판매가격은 상품정보의 sell_price로 세팅. 판매업체에게 제공받지 않는다. sendVO.setSell_price(goods.getSell_price()); // 발송정보 세팅 sendVO.setGoods_count("1"); // 상품 수량은 1로 고정 sendVO.setRecv_phone(couponReq.getRecv_phone()); sendVO.setSend_phone(couponReq.getSend_phone()); sendVO.setTr_id(couponReq.getTr_id()); sendVO.setMsg(couponReq.getMessage()); restTemplate = new RestTemplate(); params = new LinkedMultiValueMap<String, String>(); UriComponents uriComponents; String baseUrl = ""; // M12 handling if (goods.getProvider() == 1) { params.add("goods_code", couponReq.getGoods_code()); params.add("goods_count", sendVO.getGoods_count()); // 상품 수량 1로 고정 params.add("send_phone", couponReq.getSend_phone()); params.add("recv_phone", couponReq.getRecv_phone()); params.add("tr_id", couponReq.getTr_id()); params.add("userid", "hlint"); params.add("sell_price", sendVO.getSell_price()); // 상품 판매가격으로 고정 params.add("msg", couponReq.getMessage()); if (isReal) { baseUrl = "http://web6.m12.co.kr:12101/app/order_send.php"; } else { baseUrl = "http://web6.m12.co.kr:12101/app/dev/order_send.php"; } uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); String value = uriComponents.getQuery(); String key = "HLINTNLE54A3I2O1"; String initVector = "J0S9O8T7USJFDLSX"; logger.debug(value); try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes()); String strpara = Base64.encodeBase64String(encrypted); params.clear(); params.add("marketcode", "HLINTNL01"); params.add("strpara", strpara); uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); logger.debug(uriComponents.toUriString()); String strResult = restTemplate.getForObject(uriComponents.toUriString(), String.class); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(strResult)); Element rootNode = document.getRootElement(); logger.debug(rootNode.getName()); String resultCode = rootNode.getChild("RESULT_CODE", rootNode.getNamespace()).getText(); String statusCode = rootNode.getChild("STATUS_CODE", rootNode.getNamespace()).getText(); // 쿠폰 발송 상태 저장 sendVO.setResult_code(resultCode); sendVO.setStatus_code(statusCode); sendVO.setReal(isReal); logger.debug(sendVO.toString()); adminService.addSend(sendVO); return new Result(Integer.parseInt(resultCode), statusCode); } catch (Exception e) { e.printStackTrace(); return new Result(500, "내부 오류가 발생하였습니다."); } } // Coup handling, 문서 2.18 구현 else if (goods.getProvider() == 2) { params.add("CODE", "0424"); params.add("PASS", "hlint123"); params.add("COUPONCODE", couponReq.getGoods_code()); params.add("SEQNUMBER", couponReq.getTr_id()); params.add("QTY", sendVO.getGoods_count()); // 상품수량은 1개 params.add("HP", couponReq.getRecv_phone()); params.add("CALLBACK", couponReq.getSend_phone()); params.add("TITLE", ""); params.add("ADDMSG", couponReq.getMessage()); params.add("SELPRICE", sendVO.getSell_price()); // 상품 가격 세팅 // logger.debug(params.toString()); if (isReal) { baseUrl = "http://v3api.inumber.co.kr/serviceapi_02.asmx/ServiceCreateSendMuch"; } else { baseUrl = "http://issuev3apitest.m2i.kr:9999/serviceapi_02.asmx/ServiceCreateSendMuch"; } try { uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); logger.debug(uriComponents.toUriString()); String strResult = restTemplate.getForObject(uriComponents.toUriString(), String.class); logger.debug("strResult:" + strResult); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(strResult)); Element rootNode = document.getRootElement(); String resultCode = rootNode.getChild("RESULTCODE", rootNode.getNamespace()).getText(); String resultMsg = rootNode.getChild("RESULTMSG", rootNode.getNamespace()).getText(); // 쿠폰 발송 상태 저장 sendVO.setResult_code(resultCode); sendVO.setStatus_code(resultMsg); // 쿠폰번호와 핀번호 저장 if ("00".equals(resultCode)) { Element List = rootNode.getChild("LIST", rootNode.getNamespace()); List couponList = List.getChildren("GCOUPONLIST", rootNode.getNamespace()); // 한건만 보내므로 루프를 돌리지않고 한건만 저장 Element node = (Element) couponList.get(0); String couponNumber = node.getChildText("COUPONNUMBER", rootNode.getNamespace()); String pinNumber = node.getChildText("PINNUMBER", rootNode.getNamespace()); sendVO.setCouponnumber(couponNumber); sendVO.setPinnumber(pinNumber); } sendVO.setReal(isReal); logger.debug(sendVO.toString()); adminService.addSend(sendVO); return new Result(Integer.parseInt(resultCode), resultMsg); } catch (Exception e) { e.printStackTrace(); return new Result(100, "Coupon failed"); } } return new Result(500, "내부 오류가 발생하였습니다."); }