Example usage for org.springframework.web.client RestTemplate RestTemplate

List of usage examples for org.springframework.web.client RestTemplate RestTemplate

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate RestTemplate.

Prototype

public RestTemplate() 

Source Link

Document

Create a new instance of the RestTemplate using default settings.

Usage

From source file:com.stackoverflow.so32806530.App.java

/**
 * Program EP.//from w w  w .ja  v a2 s  .  c om
 * @param args CLI args
 *
 * @throws URISyntaxException
 * @throws IOException
 */
public static void main(final String[] args) throws URISyntaxException, IOException {
    // ---------- Read response.xml -----
    final String xml = new String(
            Files.readAllBytes(Paths.get(App.class.getClassLoader().getResource("response.xml").toURI())),
            Charset.forName("UTF-8"));

    // ---------- starts fake API server -----
    final WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8089));
    wireMockServer.stubFor(get(urlMatching("/v2/discovery/events.*")).willReturn(
            aResponse().withHeader("Content-type", "application/xml").withStatus(200).withBody(xml)));
    wireMockServer.start();
    // ---------------------------------------

    try {
        final String name = "foo";
        final String APIKEY = "MYAPI";
        final String URL = "http://localhost:8089/v2/discovery/events?apikey=" + APIKEY;
        final String readyUrl = URL + "&what=" + name;
        final RestTemplate restTemplate = new RestTemplate();
        final EventsResponse eventResponse = restTemplate.getForObject(readyUrl, EventsResponse.class);

        log.info("Seatwave: {}", eventResponse.getEvents().size());

        for (final Event event : eventResponse.getEvents()) {
            log.info("EventID: {}", event.getId());
        }
    } catch (final Exception ex) {
        log.error("Something went wrong", ex);
    }

    // ---------- stops fake API server ------
    wireMockServer.stop();
    // ---------------------------------------
}

From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java

public static void main(String[] args) throws Exception {

    // Modify host and port below to match wherever StompWebSocketServer.java is running!!
    // When StompWebSocketServer starts it prints the selected available

    String host = "localhost";
    if (args.length > 0) {
        host = args[0];//w ww. j av  a  2  s .  c o  m
    }

    int port = 59984;
    if (args.length > 1) {
        port = Integer.valueOf(args[1]);
    }

    String url = "http://" + host + ":" + port + "/home";
    logger.debug("Sending warm-up HTTP request to " + url);
    HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode();
    Assert.state(status == HttpStatus.OK);

    final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS);
    final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS);

    final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();

    Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor);
    JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient);
    webSocketClient.start();

    HttpClient jettyHttpClient = new HttpClient();
    jettyHttpClient.setMaxConnectionsPerDestination(1000);
    jettyHttpClient.setExecutor(new QueuedThreadPool(1000));
    jettyHttpClient.start();

    List<Transport> transports = new ArrayList<>();
    transports.add(new WebSocketTransport(webSocketClient));
    transports.add(new JettyXhrTransport(jettyHttpClient));

    SockJsClient sockJsClient = new SockJsClient(transports);

    try {
        URI uri = new URI("ws://" + host + ":" + port + "/stomp");
        WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient);
        stompClient.setMessageConverter(new StringMessageConverter());

        logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users ");
        StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests");
        stopWatch.start();

        List<ConsumerStompMessageHandler> consumers = new ArrayList<>();
        for (int i = 0; i < NUMBER_OF_USERS; i++) {
            consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch,
                    messageLatch, disconnectLatch, failure));
            stompClient.connect(consumers.get(i));
        }

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users connected, remaining: " + connectLatch.getCount());
        }
        if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users ");
        stopWatch.start();

        ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT,
                failure);
        stompClient.connect(producer);

        if (failure.get() != null) {
            throw new AssertionError("Test failed", failure.get());
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            for (ConsumerStompMessageHandler consumer : consumers) {
                if (consumer.messageCount.get() < consumer.expectedMessageCount) {
                    logger.debug(consumer);
                }
            }
        }
        if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount());
        }

        producer.session.disconnect();
        if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) {
            logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount());
        }

        stopWatch.stop();
        logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis");

        System.out.println("\nPress any key to exit...");
        System.in.read();
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        webSocketClient.stop();
        jettyHttpClient.stop();
    }

    logger.debug("Exiting");
    System.exit(0);
}

From source file:org.cloudfoundry.workers.stocks.YahooPipesQuotesApiStockSymbolLookupClient.java

public static void main(String[] args) throws Throwable {
    RestTemplate restTemplate = new RestTemplate();
    YahooPipesQuotesApiStockSymbolLookupClient apiStockSymbolLookupClient = new YahooPipesQuotesApiStockSymbolLookupClient(
            restTemplate);/*  ww w  .j av a 2 s  .c  om*/
    StockSymbolLookup lookup = apiStockSymbolLookupClient.lookupSymbol("VMW");
    System.out.println(ToStringBuilder.reflectionToString(lookup));
}

From source file:com.mycompany.asyncreq.Main.java

public static void main(String[] args) throws JsonProcessingException, JSONException, IOException {

    Configuration config = new Configuration();
    // Name tables with lowercase_underscore_separated
    RestTemplate restTemplate = new RestTemplate();
    config.setNamingStrategy(new ImprovedNamingStrategy());
    try {// www  .  j  a v a 2s.c  o  m

        ArrayList<String> ArrReq = GenData();
        String addr;
        for (Iterator<String> i = ArrReq.iterator(); i.hasNext();) {
            try {
                addr = i.next();
                Thread.sleep(1000);
                Root tRoot = restTemplate.getForObject(addr, Root.class);
                tRoot.addr = addr;
                if (!tRoot.dataset.isEmpty())
                    if (tRoot.dataset.size() == tRoot.validation.count.value)
                        ObjToCsv(tRoot, "all");

                    else {
                        for (int reg = 1; reg < 5; reg++) {
                            Thread.sleep(1000);
                            addr = "http://comtrade.un.org/api/get?max=50000&type=C&freq=M&px=HS&ps=2014&r=804&p="
                                    + tRoot.dataset.get(0).getptCode() + "&rg=" + reg + "&cc=All&fmt=json";
                            Root tRootImp = restTemplate.getForObject(addr, Root.class);
                            tRootImp.addr = addr;
                            if (!tRootImp.dataset.isEmpty())
                                if (tRootImp.dataset.size() == tRootImp.validation.count.value)
                                    ObjToCsv(tRootImp, Integer.toString(reg));
                                else
                                    System.out.println("addr:  " + tRootImp.addr + "\n");
                        }
                    }
                else
                    System.out.println("addr:  " + tRoot.addr + ":null" + "\n");
            } catch (Exception e) {
                System.err.println(e.getMessage());

            }
        }

    } catch (Exception e) {
        System.err.println("Got an exception! ");
        System.err.println(e.getMessage());
    }
}

From source file:com.softtek.medicine.java.util.TestRestClient.java

private static void testPostIncidents() {
    // TODO Auto-generated method stub
    RestTemplate restTemplate = new RestTemplate();
    System.out.println("recover incidents\n");
    List<Incident> incidentList = new ArrayList<Incident>();
    incidentList = getAllIncidents();/*  ww w  .  j a  v  a 2 s. c o m*/
    //System.out.println("tentar post");
    //String result = restTemplate.postForObject(SERVER_URI + "/dr/incidents/update", incidentList, String.class);
    //System.out.println(result);

}

From source file:eu.falcon.semantic.client.DenaClient.java

public static String publishOntology(String fileClassPath, String format, String dataset) {

    RestTemplate restTemplate = new RestTemplate();
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    final String uri = "http://localhost:8090/api/v1/ontology/publish";
    //final String uri = "http://falconsemanticmanager.euprojects.net/api/v1/ontology/publish";

    map.add("file", new ClassPathResource(fileClassPath));
    map.add("format", format);
    map.add("dataset", dataset);
    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
            map, headers);/*from w  ww . ja  v  a 2 s  . c om*/

    String result = restTemplate.postForObject(uri, entity, String.class);

    return result;

}

From source file:it.inserpio.mapillary.gopro.importer.upload.UploadToMapillary.java

public static void upload(File imageFile, String url, String usr, String pwd) {
    RestTemplate restTemplate = new RestTemplate();

}

From source file:com.softtek.medicine.java.util.MedicineRestClientUtil.java

private static void testPostIncidents() throws ParseException {
    // TODO Auto-generated method stub
    RestTemplate restTemplate = new RestTemplate();
    System.out.println("recover incidents\n");
    List<Incident> incidentList = new ArrayList<Incident>();
    incidentList = getAllIncidents();//  ww w . ja  va2 s.c  o m
    //System.out.println("tentar post");
    //String result = restTemplate.postForObject(SERVER_URI + "/dr/incidents/update", incidentList, String.class);
    //System.out.println(result);

}

From source file:com.softtek.medicine.java.util.TestRestClient.java

private static List<Incident> getAllIncidents() {
    List<Incident> incList = new ArrayList<Incident>();
    RestTemplate restTemplate = new RestTemplate();
    List<LinkedHashMap> emps = restTemplate.getForObject(SERVER_URI + "/dr/incidents/request", List.class);
    System.out.println(emps.size());

    /**// ww  w. j  a v  a2  s. c o  m
     * Trecho comentado para no fazer uppdate de todos incidentes durante
     * os testes
     */
    //      for (LinkedHashMap map : emps) {
    //         System.out.println("incidentNumber=" + map.get("incidentNumber"));
    //         Incident in = new Incident();
    //         in.setIncidentNumber(map.get("incidentNumber").toString());
    //         incList.add(in);
    //      }
    Incident in = new Incident();
    in.setIncidentNumber(emps.get(0).get("incidentNumber").toString());
    incList.add(in);

    return incList;
}

From source file:com.iflytek.rest.demo.UserServiceTest.java

public static void requestRestApi(String access_token) {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("method", "user.get");
    form.add("version", "1.0.0");
    form.add("locale", "zh_CN");
    form.add("format", "json");
    form.add("appkey", "Hb0YhmOo"); //-Dexcludes.appkey=Hb0YhmOo
    form.add("access_token", access_token);

    form.add("id", "10001");
    String result = restTemplate.postForObject("http://localhost:8090/api", form, String.class);
    System.out.println(result);/*  w  ww  .j  a va2  s  .c  o  m*/
}