List of usage examples for org.springframework.web.client RestTemplate exchange
@Override public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping("/cart") public @ResponseBody String getCartById(@RequestParam("cartId") String cartId) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); JSONObject jsonObj = new JSONObject(); try {// www. j a v a 2 s . c o m jsonObj.put("cartId", Integer.parseInt(cartId)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("param jsonObj=>" + jsonObj.toString()); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.GET_CART).queryParam("params", jsonObj); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); return returnString.getBody(); }
From source file:com.jvoid.quote.controller.JVoidQuoteController.java
public ProductsMaster getJVoidProduct(int productId) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); JSONObject jsonObj = new JSONObject(); try {//from w w w . j av a 2 s . c o m jsonObj.put("id", productId); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("param jsonObj=>" + jsonObj.toString()); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(PRODUCT_SERVER_URI + URIConstants.GET_PRODUCT).queryParam("params", jsonObj); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); System.out.println("returnString=>" + returnString); JSONObject returnJsonObj = null; try { returnJsonObj = new JSONObject(returnString.getBody()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray productsArr = null; ProductsMaster productsMaster = null; try { productsArr = returnJsonObj.getJSONArray("products"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } productsMaster = new ProductsMaster(); try { ObjectMapper mapper = new ObjectMapper(); try { productsMaster = mapper.readValue(productsArr.getJSONObject(0).toString(), ProductsMaster.class); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return productsMaster; }
From source file:com.javafxpert.wikibrowser.WikiVisGraphController.java
/** * Calls the Neo4j Transactional Cypher service and returns an object that holds results * @param neoCypherUrl/*from w ww . ja va2 s . c o m*/ * @param postString * @return */ private VisGraphResponseNear queryProcessSearchResponse(String neoCypherUrl, String postString) { log.info("neoCypherUrl: " + neoCypherUrl); log.info("postString: " + postString); RestTemplate restTemplate = new RestTemplate(); HttpHeaders httpHeaders = WikiBrowserUtils.createHeaders(wikiBrowserProperties.getCypherUsername(), wikiBrowserProperties.getCypherPassword()); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity request = new HttpEntity(postString, httpHeaders); GraphResponseFar graphResponseFar = null; VisGraphResponseNear visGraphResponseNear = new VisGraphResponseNear(); try { ResponseEntity<GraphResponseFar> result = restTemplate.exchange(neoCypherUrl, HttpMethod.POST, request, GraphResponseFar.class); graphResponseFar = result.getBody(); log.info("graphResponseFar: " + graphResponseFar); // Populate VisGraphResponseNear instance from GraphResponseFar instance HashMap<String, VisGraphNodeNear> visGraphNodeNearMap = new HashMap<>(); HashMap<String, VisGraphEdgeNear> visGraphEdgeNearMap = new HashMap<>(); List<ResultFar> resultFarList = graphResponseFar.getResultFarList(); if (resultFarList.size() > 0) { List<DataFar> dataFarList = resultFarList.get(0).getDataFarList(); Iterator<DataFar> dataFarIterator = dataFarList.iterator(); while (dataFarIterator.hasNext()) { GraphFar graphFar = dataFarIterator.next().getGraphFar(); List<GraphNodeFar> graphNodeFarList = graphFar.getGraphNodeFarList(); Iterator<GraphNodeFar> graphNodeFarIterator = graphNodeFarList.iterator(); while (graphNodeFarIterator.hasNext()) { GraphNodeFar graphNodeFar = graphNodeFarIterator.next(); VisGraphNodeNear visGraphNodeNear = new VisGraphNodeNear(); //visGraphNodeNear.setDbId(graphNodeFar.getId()); // Database ID for this node visGraphNodeNear.setDbId(graphNodeFar.getGraphNodePropsFar().getItemId().substring(1)); visGraphNodeNear.setTitle(graphNodeFar.getGraphNodePropsFar().getTitle()); visGraphNodeNear.setLabelsList(graphNodeFar.getLabelsList()); visGraphNodeNear.setItemId(graphNodeFar.getGraphNodePropsFar().getItemId()); String itemId = visGraphNodeNear.getItemId(); String articleTitle = visGraphNodeNear.getTitle(); // Retrieve the article's image String thumbnailUrl = null; String articleLang = "en"; // TODO: Add a language property to Item nodes stored in Neo4j that aren't currently in English, // and use that property to mutate articleTitleLang // First, try to get the thumbnail by ID from cache thumbnailUrl = ThumbnailCache.getThumbnailUrlById(itemId, articleLang); if (thumbnailUrl == null) { // If not available, try to get thumbnail by ID from ThumbnailService try { String thumbnailByIdUrl = this.wikiBrowserProperties .getThumbnailByIdServiceUrl(itemId, articleLang); thumbnailUrl = new RestTemplate().getForObject(thumbnailByIdUrl, String.class); if (thumbnailUrl != null) { visGraphNodeNear.setImageUrl(thumbnailUrl); } else { // If thumbnail isn't available by ID, try to get thumbnail by article title try { String thumbnailByTitleUrl = this.wikiBrowserProperties .getThumbnailByTitleServiceUrl(articleTitle, articleLang); thumbnailUrl = new RestTemplate().getForObject(thumbnailByTitleUrl, String.class); if (thumbnailUrl != null) { visGraphNodeNear.setImageUrl(thumbnailUrl); } else { visGraphNodeNear.setImageUrl(""); } //log.info("thumbnailUrl:" + thumbnailUrl); } catch (Exception e) { e.printStackTrace(); log.info("Caught exception when calling /thumbnail?title=" + articleTitle + " : " + e); } } //log.info("thumbnailUrl:" + thumbnailUrl); } catch (Exception e) { e.printStackTrace(); log.info("Caught exception when calling /thumbnail?id=" + itemId + " : " + e); } } else { visGraphNodeNear.setImageUrl(thumbnailUrl); } /* // Check cache for thumbnail thumbnailUrl = ThumbnailCache.getThumbnailUrlById(itemId, articleLang); if (thumbnailUrl != null && thumbnailUrl.length() > 0) { // Thumbnail image found in cache by ID, which is the preferred location visGraphNodeNear.setImageUrl(thumbnailUrl); } else { // Thumbnail image not found in cache by ID, so look with Wikimedia API by article title log.info("Thumbnail not found in cache for itemId: " + itemId + ", lang: " + articleLang + " so looking with Wikimedia API by article title"); try { String url = this.wikiBrowserProperties.getThumbnailByTitleServiceUrl(articleTitle, articleLang); thumbnailUrl = new RestTemplate().getForObject(url, String.class); if (thumbnailUrl != null && thumbnailUrl.length() > 0) { visGraphNodeNear.setImageUrl(thumbnailUrl); } else { log.info("Thumbnail not found for articleTitle: " + articleTitle + ", trying by itemId: " + itemId); try { String url = this.wikiBrowserProperties.getThumbnailByIdServiceUrl(itemId, articleLang); thumbnailUrl = new RestTemplate().getForObject(url, String.class); if (thumbnailUrl != null) { visGraphNodeNear.setImageUrl(thumbnailUrl); // Because successful, cache by article title ThumbnailCache.setThumbnailUrlByTitle(articleTitle, articleLang, thumbnailUrl); } else { visGraphNodeNear.setImageUrl(""); } //log.info("thumbnailUrl:" + thumbnailUrl); } catch (Exception e) { e.printStackTrace(); log.info("Caught exception when calling /thumbnail?id=" + itemId + " : " + e); } } //log.info("thumbnailUrl:" + thumbnailUrl); } catch (Exception e) { e.printStackTrace(); log.info("Caught exception when calling /thumbnail?title=" + articleTitle + " : " + e); } } */ // Note: The key in the graphNodeNearMap is the Neo4j node id, not the Wikidata item ID visGraphNodeNearMap.put(graphNodeFar.getId(), visGraphNodeNear); } List<GraphRelationFar> graphRelationFarList = graphFar.getGraphRelationFarList(); Iterator<GraphRelationFar> graphRelationFarIterator = graphRelationFarList.iterator(); while (graphRelationFarIterator.hasNext()) { GraphRelationFar graphRelationFar = graphRelationFarIterator.next(); VisGraphEdgeNear visGraphEdgeNear = new VisGraphEdgeNear(); // Use the Neo4j node ids from the relationship to retrieve the Wikidata Item IDs from the graphNodeNearMap String neo4jStartNodeId = graphRelationFar.getStartNode(); String wikidataStartNodeItemId = visGraphNodeNearMap.get(neo4jStartNodeId).getItemId(); String neo4jEndNodeId = graphRelationFar.getEndNode(); String wikidataEndNodeItemId = visGraphNodeNearMap.get(neo4jEndNodeId).getItemId(); //visGraphEdgeNear.setFromDbId(neo4jStartNodeId); visGraphEdgeNear.setFromDbId(wikidataStartNodeItemId.substring(1)); //visGraphEdgeNear.setToDbId(neo4jEndNodeId); visGraphEdgeNear.setToDbId(wikidataEndNodeItemId.substring(1)); visGraphEdgeNear.setLabel(graphRelationFar.getType()); visGraphEdgeNear.setArrowDirection("to"); visGraphEdgeNear.setPropId(graphRelationFar.getGraphRelationPropsFar().getPropId()); visGraphEdgeNear.setFromItemId(wikidataStartNodeItemId); visGraphEdgeNear.setToItemId(wikidataEndNodeItemId); // Note: The key in the graphLinkNearMap is the Neo4j node id, not the Wikidata item ID visGraphEdgeNearMap.put(graphRelationFar.getId(), visGraphEdgeNear); } } // Create and populate a List of nodes to set into the graphResponseNear instance List<VisGraphNodeNear> visGraphNodeNearList = new ArrayList<>(); visGraphNodeNearMap.forEach((k, v) -> { visGraphNodeNearList.add(v); }); visGraphResponseNear.setVisGraphNodeNearList(visGraphNodeNearList); // Create and populate a List of links to set into the graphResponseNear instance List<VisGraphEdgeNear> visGraphEdgeNearList = new ArrayList<>(); visGraphEdgeNearMap.forEach((k, v) -> { visGraphEdgeNearList.add(v); }); visGraphResponseNear.setVisGraphEdgeNearList(visGraphEdgeNearList); } } catch (Exception e) { e.printStackTrace(); log.info("Caught exception when calling Neo Cypher service " + e); } return visGraphResponseNear; }
From source file:org.cloudfoundry.identity.client.UaaContextFactory.java
protected UaaContext authenticateSaml2BearerAssertion(final TokenRequest request) { RestTemplate template = new RestTemplate(); if (request.isSkipSslValidation()) { template.setRequestFactory(getNoValidatingClientHttpRequestFactory()); }/*from w w w .ja va 2 s. c o m*/ HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(OAuth2Utils.CLIENT_ID, request.getClientId()); form.add("client_secret", request.getClientSecret()); form.add(OAuth2Utils.GRANT_TYPE, "urn:ietf:params:oauth:grant-type:saml2-bearer"); form.add("assertion", request.getAuthCodeAPIToken()); ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST, new HttpEntity<>(form, headers), CompositeAccessToken.class); return new UaaContextImpl(request, null, token.getBody()); }
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping(value = "/sign-up", method = RequestMethod.POST) public @ResponseBody String jvoidSignUpNewUser( @RequestParam(required = false, value = "params") JSONObject jsonParams) { System.out.println("sign-up:jsonParams=>" + jsonParams.toString()); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); String uri = ""; try {/*w w w . j a v a 2 s .c o m*/ if (jsonParams.getInt("id") > 0) { uri = ServerUris.CUSTOMER_SERVER_URI + URIConstants.UPDATE_CUSTOMER; } else { uri = ServerUris.CUSTOMER_SERVER_URI + URIConstants.ADD_CUSTOMER; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri).queryParam("params", jsonParams); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); return returnString.getBody(); }
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping("/remove-cart") public @ResponseBody String removeItemsFromCartById(@RequestParam("cartId") String cartId, @RequestParam("prodId") String prodId) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); JSONObject jsonObj = new JSONObject(); try {/*from ww w . j ava2 s.c om*/ jsonObj.put("cartId", Integer.parseInt(cartId)); jsonObj.put("productId", Integer.parseInt(prodId)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("param jsonObj=>" + jsonObj.toString()); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.DELETE_CART).queryParam("params", jsonObj); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); return returnString.getBody(); }
From source file:com.catalog.core.Api.java
@Override public StudentMark addStudentMark(int studentId, int stfcId, int grade, boolean finalExam, long date) { setStartTime();/*from ww w . j a v a 2 s . c o m*/ HttpEntity<?> requestEntity = getAuthHttpEntity(); RestTemplate restTemplate = new RestTemplate(); // Add the Jackson message converter restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); int finalExamInt = finalExam ? 1 : 0; String url = "http://" + IP + EXTENSION + "/teacher/formStudentMarkT/" + studentId + "," + stfcId + "," + grade + "," + finalExamInt + "," + date + ".json"; ResponseEntity<StudentMarkVM> responseEntity = null; StudentMarkVM response = null; try { responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, StudentMarkVM.class); response = responseEntity.getBody(); } catch (RestClientException e) { return null; } Log.d("TAAAG", response.toString()); getElapsedTime("addStudentMark - "); return response.getStudentMark(); }
From source file:com.epl.ticketws.services.QueryService.java
public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) { try {// w w w . j a v a 2 s . c om URI uri = new URL(url).toURI(); long timestamp = new Date().getTime(); HttpMethod httpMethod; if (method.equalsIgnoreCase("post")) { httpMethod = HttpMethod.POST; } else { httpMethod = HttpMethod.GET; } String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters); // logger.info("String to sign: " + stringToSign); String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license); // logger.info("Authorization string: " + authorization); // Setting Headers HttpHeaders headers = new HttpHeaders(); if (accept.equalsIgnoreCase("json")) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } else { headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); } headers.add("Authorization", authorization); headers.add("OB_DATE", "" + timestamp); headers.add("OB_Terminal", terminal); headers.add("OB_User", user); headers.add("OB_Channel", channel); headers.add("OB_POS", pos); headers.add("Content-Type", "application/x-www-form-urlencoded"); HttpEntity<String> entity; if (httpMethod == HttpMethod.POST) { // Adding post parameters to POST body String parameterStringBody = getParametersAsString(parameters); entity = new HttpEntity<String>(parameterStringBody, headers); // logger.info("POST Body: " + parameterStringBody); } else { entity = new HttpEntity<String>(headers); } RestTemplate restTemplate = new RestTemplate( new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new LoggingRequestInterceptor()); restTemplate.setInterceptors(interceptors); // Converting to UTF-8. OB Rest replies in windows charset. //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(UTF_8))); if (accept.equalsIgnoreCase("json")) { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter()); } else { restTemplate.getMessageConverters().add(0, new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter()); } ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc); if (!response.getStatusCode().is2xxSuccessful()) throw new HttpClientErrorException(response.getStatusCode()); return response.getBody(); } catch (HttpClientErrorException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (MalformedURLException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return null; }