Java Code Examples for org.springframework.web.client.RestTemplate#getForObject()

The following examples show how to use org.springframework.web.client.RestTemplate#getForObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestClientProductLookup.java    From Java-9-Programming-By-Example with MIT License 6 votes vote down vote up
@Override
public ProductInformation byId(String id) {
    Map<String, String> uriParameters = new HashMap<>();
    uriParameters.put("id", id);
    RestTemplate rest = new RestTemplate();
    InventoryItemAmount amount =
            rest.getForObject(piSUBuilder.url("inventory"),
                    InventoryItemAmount.class,
                    uriParameters);
    log.info("amount {}.",amount);
    if ( amount.getAmount() > 0) {
        log.info("There items from {}. We are offering",id);
        return rest.getForObject(piSUBuilder.url("pi"),
                ProductInformation.class,
                uriParameters);
    } else {
        log.info("There are no items from {}. Amount is {}",id,amount);
        return ProductInformation.emptyProductInformation;
    }
}
 
Example 2
Source File: h2oService.java    From h2o-2 with Apache License 2.0 6 votes vote down vote up
public Double CalculateAUC( String actual, String vactual, String vpredict  )  {

        //http://localhost:54321/2/AUC.json?actual=prostate_csv.hex&vactual=CAPSULE&predict=predict_1&vpredict=1&thresholds=&threshold_criterion=maximum_F1
        Double AUC;
        String prediction_name = "Predict_GBM";
        String h2oUrlCalculateAUCEndPoint = H2O_HOST_URL + H2O_GBM_MODEL_AUC_URL + "actual=" + actual + "&vactual=" + vactual + "&predict=" + prediction_name + "&vpredict=" + vpredict +"&threshold_criterion=maximum_F1";
        System.out.println(h2oUrlCalculateAUCEndPoint);
        log.debug("@@@ Calling endpoint {}", h2oUrlCalculateAUCEndPoint);
        try {
            RestTemplate restTemplate = new RestTemplate();
            String responseBody = restTemplate.getForObject(h2oUrlCalculateAUCEndPoint, String.class);
            JSONObject jsonobject = new JSONObject(responseBody);
            JSONObject aucdata = (JSONObject)jsonobject.get("aucdata");
            AUC = (Double)aucdata.get("AUC");
            //status = (String).get("status");
            System.out.println("AUC: " + AUC);


        }catch(Exception ex){
            log.debug("!!!!!! Error Occurred while getting job status  {}", ex);
            ex.printStackTrace();
            return null;
        }
        return AUC;
    }
 
Example 3
Source File: ArticleController.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/re/{id}", method = RequestMethod.GET)
public Article findArticled(@PathVariable("id") Integer id) throws IOException {
    RestTemplate client= restTemplateBuilder.build();
    String uri = "http://localhost:8080/article/"+id;
    System.out.println(uri);
    Article article = client.getForObject (uri,Article.class,id) ;

    return article;
}
 
Example 4
Source File: RestTemplateIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test1() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    String forObject = restTemplate.getForObject(webServer.getCallHttpUrl(), String.class);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    verifier.verifyTrace(event("REST_TEMPLATE", RestTemplate.class.getConstructor()));
    verifier.verifyTrace(event("REST_TEMPLATE", AbstractClientHttpRequest.class.getMethod("execute"), annotation("http.status.code", 200)));
}
 
Example 5
Source File: RestRequests.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void getOneGreeting(RestTemplate restTemplate) {
   // We want Greeting at index=0
   Greeting aGreeting = restTemplate
         .getForObject("http://localhost:8080/greeting/0", Greeting.class);
   System.out.println("Get=0 -> " + aGreeting);

}
 
Example 6
Source File: MetricServiceHTTP.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
public void activateProcess(ProcessMetric processMetric) {
    log.info("Call activateProcess {}", processMetric);
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.getForObject(generatorConfiguration.getBackend() + "/metric/activate?idProcess=" + processMetric.getIdProcess(), String.class);
    } catch (Exception e) {
        log.error("status {}", e);
    }
}
 
Example 7
Source File: ContextPathIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void servletPathMapping() throws Exception {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
	context.register(WebAppConfig.class);
	context.refresh();

	File base = new File(System.getProperty("java.io.tmpdir"));
	TomcatHttpServer server = new TomcatHttpServer(base.getAbsolutePath());
	server.setContextPath("/app");
	server.setServletMapping("/api/*");

	HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context).build();
	server.setHandler(httpHandler);

	server.afterPropertiesSet();
	server.start();

	try {
		RestTemplate restTemplate = new RestTemplate();
		String actual;

		String url = "http://localhost:" + server.getPort() + "/app/api/test";
		actual = restTemplate.getForObject(url, String.class);
		assertEquals("Tested in /app/api", actual);
	}
	finally {
		server.stop();
	}
}
 
Example 8
Source File: StoreOrderController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "订单核销")
@PutMapping(value = "/yxStoreOrder/check")
@PreAuthorize("@el.check('admin','YXSTOREORDER_ALL','YXSTOREORDER_EDIT')")
public ResponseEntity check(@Validated @RequestBody YxStoreOrder resources) {
    if (StrUtil.isBlank(resources.getVerifyCode())) throw new BadRequestException("核销码不能为空");
    YxStoreOrderDto storeOrderDTO = generator.convert(yxStoreOrderService.getById(resources.getId()),YxStoreOrderDto.class);
    if(!resources.getVerifyCode().equals(storeOrderDTO.getVerifyCode())){
        throw new BadRequestException("核销码不对");
    }
    if(OrderInfoEnum.PAY_STATUS_0.getValue().equals(storeOrderDTO.getPaid())){
        throw new BadRequestException("订单未支付");
    }

    /**
    if(storeOrderDTO.getStatus() > 0) throw new BadRequestException("订单已核销");

    if(storeOrderDTO.getCombinationId() > 0 && storeOrderDTO.getPinkId() > 0){
        YxStorePinkDTO storePinkDTO = storePinkService.findById(storeOrderDTO.getPinkId());
        if(!OrderInfoEnum.PINK_STATUS_2.getValue().equals(storePinkDTO.getStatus())){
            throw new BadRequestException("拼团订单暂未成功无法核销");
        }
    }
     **/

    //远程调用API
    RestTemplate rest = new RestTemplate();
    String url = StrUtil.format(apiUrl+"/order/admin/order_verific/{}", resources.getVerifyCode());
    String text = rest.getForObject(url, String.class);


    JSONObject jsonObject = JSON.parseObject(text);

    Integer status = jsonObject.getInteger("status");
    String msg = jsonObject.getString("msg");

    if(status != 200) throw new BadRequestException(msg);


    return new ResponseEntity(HttpStatus.NO_CONTENT);
}
 
Example 9
Source File: CodeFirstRestTemplateSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void testFallback(RestTemplate template, String cseUrlPrefix) {
  long start = System.currentTimeMillis();
  String result = template.getForObject(cseUrlPrefix + "/fallback/returnnull/hello", String.class);
  TestMgr.check(result, "hello");
  result = template.getForObject(cseUrlPrefix + "/fallback/returnnull/throwexception", String.class);
  TestMgr.check(result, null);

  result = template.getForObject(cseUrlPrefix + "/fallback/throwexception/hello", String.class);
  TestMgr.check(result, "hello");
  try {
    result = template.getForObject(cseUrlPrefix + "/fallback/throwexception/throwexception", String.class);
    TestMgr.check(false, true);
  } catch (Exception e) {
    TestMgr.check(e.getCause().getMessage(),
        BizkeeperExceptionUtils.createBizkeeperException(BizkeeperExceptionUtils.SERVICECOMB_BIZKEEPER_FALLBACK,
            null,
            "springmvc.codeFirst.fallbackThrowException").getMessage());
  }

  result = template.getForObject(cseUrlPrefix + "/fallback/fromcache/hello", String.class);
  TestMgr.check(result, "hello");
  result = template.getForObject(cseUrlPrefix + "/fallback/fromcache/hello", String.class);
  TestMgr.check(result, "hello");
  result = template.getForObject(cseUrlPrefix + "/fallback/fromcache/throwexception", String.class);
  TestMgr.check(result, "hello");

  result = template.getForObject(cseUrlPrefix + "/fallback/force/hello", String.class);
  TestMgr.check(result, "mockedreslut");

  // This test case is fallback testing and will return null if failed.
  // In order to check if failed due to some unexpected timeout exception, check the time.
  TestMgr.check(System.currentTimeMillis() - start < 10000, true);
}
 
Example 10
Source File: BaremetalVlanManagerImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public BaremetalRctResponse addRct(AddBaremetalRctCmd cmd) {
    try {
        List<BaremetalRctVO> existings = rctDao.listAll();
        if (!existings.isEmpty()) {
            throw new CloudRuntimeException(String.format("there is some RCT existing. A CloudStack deployment accepts only one RCT"));
        }
        URL url = new URL(cmd.getRctUrl());
        RestTemplate rest = new RestTemplate();
        String rctStr = rest.getForObject(url.toString(), String.class);

        // validate it's right format
        BaremetalRct rct = gson.fromJson(rctStr, BaremetalRct.class);
        QueryBuilder<BaremetalRctVO> sc = QueryBuilder.create(BaremetalRctVO.class);
        sc.and(sc.entity().getUrl(), SearchCriteria.Op.EQ, cmd.getRctUrl());
        BaremetalRctVO vo =  sc.find();
        if (vo == null) {
            vo = new BaremetalRctVO();
            vo.setRct(gson.toJson(rct));
            vo.setUrl(cmd.getRctUrl());
            vo = rctDao.persist(vo);
        } else {
            vo.setRct(gson.toJson(rct));
            rctDao.update(vo.getId(), vo);
        }

        BaremetalRctResponse rsp = new BaremetalRctResponse();
        rsp.setUrl(vo.getUrl());
        rsp.setId(vo.getUuid());
        rsp.setObjectName("baremetalrct");
        return rsp;
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(String.format("%s is not a legal http url", cmd.getRctUrl()));
    }
}
 
Example 11
Source File: TransactionService.java    From jblockchain with Apache License 2.0 4 votes vote down vote up
/**
 * Download Transactions from other Node and them to the pool
 * @param node Node to query
 * @param restTemplate RestTemplate to use
 */
public void retrieveTransactions(Node node, RestTemplate restTemplate) {
    Transaction[] transactions = restTemplate.getForObject(node.getAddress() + "/transaction", Transaction[].class);
    Collections.addAll(transactionPool, transactions);
    LOG.info("Retrieved " + transactions.length + " transactions from node " + node.getAddress());
}
 
Example 12
Source File: BlockService.java    From jblockchain with Apache License 2.0 4 votes vote down vote up
/**
 * Download Blocks from other Node and them to the blockchain
 * @param node Node to query
 * @param restTemplate RestTemplate to use
 */
public void retrieveBlockchain(Node node, RestTemplate restTemplate) {
    Block[] blocks = restTemplate.getForObject(node.getAddress() + "/block", Block[].class);
    Collections.addAll(blockchain, blocks);
    LOG.info("Retrieved " + blocks.length + " blocks from node " + node.getAddress());
}
 
Example 13
Source File: CodeFirstRestTemplate.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private void testCodeFirstIsTrue(RestTemplate template, String cseUrlPrefix) {
  boolean result = template.getForObject(cseUrlPrefix + "istrue", boolean.class);
  TestMgr.check(true, result);
}
 
Example 14
Source File: TestSpringRestExample.java    From journaldev with MIT License 4 votes vote down vote up
private static void testGetEmployee() {
	RestTemplate restTemplate = new RestTemplate();
	Employee emp = restTemplate.getForObject(SERVER_URI+"/rest/emp/1", Employee.class);
	printEmpData(emp);
}
 
Example 15
Source File: TestSpringRestExample.java    From journaldev with MIT License 4 votes vote down vote up
private static void testGetDummyEmployee() {
	RestTemplate restTemplate = new RestTemplate();
	Employee emp = restTemplate.getForObject(SERVER_URI+EmpRestURIConstants.DUMMY_EMP, Employee.class);
	printEmpData(emp);
}
 
Example 16
Source File: ComputeController.java    From micro-service with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value="testServiceA",method=RequestMethod.GET)
public String testServiceB(@RequestParam Integer a,@RequestParam Integer b){
	RestTemplate restTemplate=new RestTemplate();
	return restTemplate.getForObject("http://localhost:7074/add?a="+a+"&b="+b, String.class);
}
 
Example 17
Source File: ScriptTemplateControllerIntegrationTests.java    From spring-boot-sample-web-handlebars with Apache License 2.0 4 votes vote down vote up
@Test
public void home() {
	RestTemplate restTemplate = new RestTemplate();
	String result = restTemplate.getForObject("http://localhost:" + port, String.class);
	assertTrue(result.contains("<li>author1 content1</li>"));
}
 
Example 18
Source File: ConfigurableHttpConnectionFactoryIntegrationTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
private void makeRequest(HttpClient httpClient, String url) {
	RestTemplate restTemplate = new RestTemplate(
			new HttpComponentsClientHttpRequestFactory(httpClient));
	restTemplate.getForObject(url, String.class);
}
 
Example 19
Source File: NodeService.java    From jblockchain with Apache License 2.0 4 votes vote down vote up
private String retrieveSelfExternalHost(Node node, RestTemplate restTemplate) {
    return restTemplate.getForObject(node.getAddress() + "/node/ip", String.class);
}
 
Example 20
Source File: ITTracingClientHttpRequestInterceptor.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected void get(ClientHttpRequestFactory client, String pathIncludingQuery) {
  RestTemplate restTemplate = new RestTemplate(client);
  restTemplate.setInterceptors(Collections.singletonList(interceptor));
  restTemplate.getForObject(url(pathIncludingQuery), String.class);
}