Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients createDefault.

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:edu.harvard.hms.dbmi.i2b2.api.samples.TraversePaths.java

/**
 * Runs the traverse paths example.//  w ww.  j  av a 2 s.  c o m
 * 
 * Requires 6 parameters:
 * domain userName password ontologyCellURL project depth
 * 
 * @param args
 *            arguments
 */
public static void main(String[] args) {
    if (args.length != 6) {
        System.out.println("Invalid number of arguments.");
        System.out.println("java TraversePaths domain userName password ontologyCellURL project depth");
    }
    String domain = args[0];
    String userName = args[1];
    String password = args[2];
    String ontologyCellURL = args[3];
    String project = args[4];
    int depth = Integer.parseInt(args[5]);

    TraversePaths traversePaths = new TraversePaths();
    try {
        traversePaths.setup(userName, domain, password, ontologyCellURL, project);

        HttpClient httpClient = HttpClients.createDefault();

        traversePaths.printPath(httpClient, null, 0, depth);

    } catch (JAXBException | IOException | I2B2InterfaceException e) {
        System.out.println("An error occurred traverse the paths");
        e.printStackTrace();
    }
    System.out.println("\nFinished with " + traversePaths.getTotalCount() + " returned in total");
}

From source file:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;//from ww  w.java  2 s .com

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:edu.harvard.hms.dbmi.i2b2.api.samples.FactoryTraversePaths.java

/**
 * Runs the traverse paths example./*from  w w  w  . j  av a2s. c  o m*/
 * 
 * Requires 6 parameters:
 * domain userName password ontologyCellURL project depth
 * 
 * @param args
 *            arguments
 */
public static void main(String[] args) {
    if (args.length != 6) {
        System.out.println("Invalid number of arguments.");
        System.out.println("java TraversePaths domain userName password cellURL project depth");
    }
    String domain = args[0];
    String userName = args[1];
    String password = args[2];
    String ontologyCellURL = args[3];
    String project = args[4];
    int depth = Integer.parseInt(args[5]);

    FactoryTraversePaths traversePaths = new FactoryTraversePaths();
    try {
        traversePaths.setup(userName, domain, password, ontologyCellURL, project);

        HttpClient httpClient = HttpClients.createDefault();

        traversePaths.printPath(httpClient, null, 0, depth);

    } catch (I2B2InterfaceException | JAXBException | IOException e) {
        System.out.println("An error occurred traverse the paths");
        e.printStackTrace();
    }
    System.out.println("\nFinished with " + traversePaths.getTotalCount() + " returned in total");
}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/*w w w  .jav  a  2  s  .c  o m*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override//from   w w  w.  j a va2s . c om
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:edu.harvard.hms.dbmi.i2b2.api.samples.SimpleQuery.java

/**
 * Runs the simple query example// w  ww  .j a v  a2 s .c  o m
 * 
 * Requires 6 parameters:
 * domain userName password ontologyCellURL project path
 * 
 * @param args
 *            arguments
 */
public static void main(String[] args) {
    if (args.length != 6) {
        System.out.println("Invalid number of arguments.");
        System.out.println("java SimpleQuery domain userName password ontologyCellURL project path");
    }

    String domain = args[0];
    String userName = args[1];
    String password = args[2];
    String crcCellURL = args[3];
    String project = args[4];
    String path = args[5];

    SimpleQuery simpleQuery = new SimpleQuery();
    try {
        simpleQuery.setup(userName, domain, password, crcCellURL, project);
        HttpClient httpClient = HttpClients.createDefault();

        String queryMasterId = simpleQuery.runQuery(httpClient, path);
        simpleQuery.printResults(httpClient, queryMasterId);

    } catch (JAXBException | IOException | I2B2InterfaceException e) {
        System.out.println("An error occurred running the simple query");
        e.printStackTrace();
    }

}

From source file:isc_415_practica_1.ISC_415_Practica_1.java

/**
 * @param args the command line arguments
 *//*from  w  w w. ja  v  a2 s  .c o  m*/
public static void main(String[] args) {
    String urlString;
    Scanner input = new Scanner(System.in);
    Document doc;

    try {
        urlString = input.next();
        if (urlString.equals("servlet")) {
            urlString = "http://localhost:8084/ISC_415_Practica1_Servlet/client";
        }
        urlString = urlString.contains("http://") || urlString.contains("https://") ? urlString
                : "http://" + urlString;
        doc = Jsoup.connect(urlString).get();
    } catch (Exception ex) {
        System.out.println("El URL ingresado no es valido.");
        return;
    }

    ArrayList<NameValuePair> formInputParams;
    formInputParams = new ArrayList<>();
    String[] plainTextDoc = new TextNode(doc.html(), "").getWholeText().split("\n");
    System.out.println(String.format("Nmero de lineas del documento: %d", plainTextDoc.length));
    System.out.println(String.format("Nmero de p tags: %d", doc.select("p").size()));
    System.out.println(String.format("Nmero de img tags: %d", doc.select("img").size()));
    System.out.println(String.format("Nmero de form tags: %d", doc.select("form").size()));

    Integer index = 1;

    ArrayList<NameValuePair> urlParameters = new ArrayList<>();
    for (Element e : doc.select("form")) {
        System.out.println(String.format("Form %d: Nmero de Input tags %d", index, e.select("input").size()));
        System.out.println(e.select("input"));

        for (Element formInput : e.select("input")) {
            if (formInput.attr("id") != null && formInput.attr("id") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("id"), "PRACTICA1"));
            } else if (formInput.attr("name") != null && formInput.attr("name") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("name"), "PRACTICA1"));
            }
        }

        index++;
    }

    if (!urlParameters.isEmpty()) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, Consts.UTF_8);
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
        } catch (IOException ex) {
            Logger.getLogger(ISC_415_Practica_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:edu.harvard.hms.dbmi.i2b2.api.samples.FactorySimpleQuery.java

/**
 * Runs the simple query example/*from  w  w w  . j  a  v a2  s. c  o m*/
 * 
 * Requires 6 parameters:
 * domain userName password ontologyCellURL project path
 * 
 * @param args
 *            arguments
 */
public static void main(String[] args) {
    if (args.length != 6) {
        System.out.println("Invalid number of arguments.");
        System.out.println("java SimpleQuery domain userName password ontologyCellURL project path");
    }

    String domain = args[0];
    String userName = args[1];
    String password = args[2];
    String crcCellURL = args[3];
    String project = args[4];
    String path = args[5];

    FactorySimpleQuery simpleQuery = new FactorySimpleQuery();
    try {
        simpleQuery.setup(userName, domain, password, crcCellURL, project);
        HttpClient httpClient = HttpClients.createDefault();

        String queryMasterId = simpleQuery.runQuery(httpClient, path);
        simpleQuery.printResults(httpClient, queryMasterId);

    } catch (JAXBException | IOException | I2B2InterfaceException e) {
        System.out.println("An error occurred running the simple query");
        e.printStackTrace();
    }

}

From source file:adapter.tdb.sync.clients.GetVocabularyOfMagicDrawAdapterAndPushToStore.java

public static void main(String[] args) {

    Thread thread = new Thread() {
        public void start() {

            URI vocabURI = URI.create("http://localhost:8080/oslc4jmagicdraw/services/sysml-rdfvocabulary");

            // create an empty RDF model
            Model model = ModelFactory.createDefaultModel();

            // use FileManager to read OSLC Resource Shape in RDF
            //            String inputFileName = "file:C:/Users/Axel/git/EcoreMetamodel2OSLCSpecification/EcoreMetamodel2OSLCSpecification/Resource Shapes/Block.rdf";
            //            String inputFileName = "file:C:/Users/Axel/git/ecore2oslc/EcoreMetamodel2OSLCSpecification/RDF Vocabulary/sysmlRDFVocabulary of OMG.rdf";
            //            InputStream in = FileManager.get().open(inputFileName);
            //            if (in == null) {
            //               throw new IllegalArgumentException("File: " + inputFileName
            //                     + " not found");
            //            }

            // create TDB dataset
            String directory = TriplestoreUtil.getTriplestoreLocation();
            Dataset dataset = TDBFactory.createDataset(directory);
            Model tdbModel = dataset.getDefaultModel();
            try {

                HttpGet httpget = new HttpGet(vocabURI);
                httpget.addHeader("accept", "application/rdf+xml");
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpResponse response = httpClient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    model.read(inputStream, null);
                    tdbModel.add(model);
                }// w ww.j a  v  a  2 s .  c  o  m

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tdbModel.close();
            dataset.close();
        }
    };
    thread.start();
    try {
        thread.join();
        System.out.println("Vocabulary of OSLC MagicDraw SysML adapter added to triplestore");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.linkedin.pinotdruidbenchmark.PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//from  w w  w  .  j a va  2  s. com
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        String query = new BufferedReader(new FileReader(queryFiles[i])).readLine();
        httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}