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:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java

public CloudHarmonyCrawler() {
    /* json parser */
    this.jsonParser = new JSONParser();

    /* client init */
    this.httpclient = HttpClients.createDefault();

    /* mapping booleans */
    this.booleans = new Hashtable<String, String>();
    this.booleans.put("autoScaling", "auto_scaling");
    this.booleans.put("selfHostable", "self_hostable");
    this.booleans.put("apiRestricted", "api_restricted");
    this.booleans.put("autoFailover", "auto_failover");
    this.booleans.put("processPricing", "process_pricing");
    this.booleans.put("vmBased", "vm_based");

    /* mapping numbers */
    this.numbers = new Hashtable<String, String>();
    this.numbers.put("cpuCores", "num_cpus");
    this.numbers.put("localDisks", "num_disks");
    this.numbers.put("memory", "ram");
    this.numbers.put("localStorage", "disk_size");

    /* mapping strings */
    this.strings = new Hashtable<String, String>();
    this.strings.put("localDiskType", "disk_type");
}

From source file:Onlinedata.MainSendRequest.java

public void uploadData(String filename, String toBeUploaded) {
    upload = filename + ";" + toBeUploaded;
    uploadurl = baseurl;//from   w  w  w .  j a v a 2 s . com
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        StringEntity cliententity = new StringEntity(upload, ContentType.create("plain/text", Consts.UTF_8));
        HttpPost httppost = new HttpPost(uploadurl);
        httppost.setEntity(cliententity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity serverentity = response.getEntity();
            if (serverentity != null) {
                long len = serverentity.getContentLength();
                if (len != -1 && len < 2048) {
                    System.out.println(EntityUtils.toString(serverentity));
                } else {
                    // Stream content out
                }
            }
        } catch (IOException | ParseException ex) {
            Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:co.paralleluniverse.fibers.dropwizard.FiberDropwizardTest.java

public static void waitUrlAvailable(final String url) throws InterruptedException, IOException {
    for (;;) {//  w  w  w.  j  av  a 2  s.c o  m
        Thread.sleep(10);
        try {
            if (HttpClients.createDefault().execute(new HttpGet(url)).getStatusLine().getStatusCode() > -100)
                break;
        } catch (final HttpHostConnectException ignored) {
        }
    }
}

From source file:adalid.util.google.Translator.java

public static Properties translate(Properties properties) {
    if (properties == null || properties.isEmpty()) {
        return properties;
    }/*from   w w  w  . j a  va2s  .  c o m*/
    String arg, translation;
    URIBuilder builder = newURIBuilder();
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        Set<String> names = properties.stringPropertyNames();
        for (String name : names) {
            arg = properties.getProperty(name);
            logger.info(arg);
            translation = translate(arg, builder, client);
            logger.info(translation);
            if (translation != null) {
                properties.setProperty(name, translation);
            }
        }
    } catch (IOException | URISyntaxException ex) {
        logger.fatal(ex);
    }
    return properties;
}

From source file:io.hightide.TemplateFetcher.java

private static void httpGetTemplate(Path tempFile, String url) throws IOException {
    CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
    byte[] buffer = new byte[BUFFER];
    try (InputStream input = response.getEntity().getContent();
            OutputStream output = new FileOutputStream(tempFile.toFile())) {
        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }//from www  . ja va 2s  .  co m
    }
}

From source file:de.dfki.resc28.serendipity.client.RepresentationEnricher.java

public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    OutputStream originalStream = context.getOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    context.setOutputStream(baos);/*from w ww  .j a v a2 s.c  om*/

    try {
        context.proceed();
    } finally {
        // get the original responseModel
        final Model responseModel = ModelFactory.createDefaultModel();
        final String contentType = context.getMediaType().toString();
        RDFDataMgr.read(responseModel, new StringReader(baos.toString()), "",
                RDFLanguages.contentTypeToLang(contentType));
        baos.close();

        // ask serendipity for affordances to add
        Model affordances = ModelFactory.createDefaultModel();
        StringWriter writer = new StringWriter();
        responseModel.write(writer, contentType);
        StringEntity entity = new StringEntity(writer.toString(), ContentType.create(contentType));

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(this.serendipityURI);
        httpPost.setHeader("Accept", contentType);
        httpPost.setHeader("Content-type", contentType);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = client.execute(httpPost);
        //            RDFDataMgr.read(affordances, response.getEntity().getContent(), "", RDFLanguages.contentTypeToLang(response.getEntity().getContentType().getValue()));
        RDFDataMgr.read(affordances, response.getEntity().getContent(), "",
                RDFLanguages.contentTypeToLang(contentType));
        client.close();

        // add the instantiated action to the responseModel   
        responseModel.add(affordances);

        // overwrite the response
        ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
        RDFDataMgr.write(baos2, responseModel, RDFLanguages.contentTypeToLang(contentType));

        baos2.writeTo(originalStream);
        baos2.close();
        context.setOutputStream(originalStream);
    }

}

From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java

/**
 * Send request by post method./*from  w w w  .  jav  a2 s  . c  o m*/
 * 
 * @param uri:
 *            http://ip:port/demo
 * @param parames:
 *            new BasicNameValuePair("code", "200")
 * 
 *            new BasicNameValuePair("name", "smartloli")
 */
public static String doPostForm(String uri, List<BasicNameValuePair> parames) {
    String result = "";
    try {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Do post form request has error, msg is " + e.getMessage());
    }
    return result;
}

From source file:com.baifendian.swordfish.common.hadoop.YarnRestClient.java

/**
 * ??//www .  j  av  a  2 s.  c  om
 *
 * @param appId
 * @return ? null, ??
 * @throws JSONException
 * @throws IOException
 */
public FlowStatus getApplicationStatus(String appId) throws JSONException, IOException {
    if (StringUtils.isEmpty(appId)) {
        return null;
    }

    String url = ConfigurationUtil.getApplicationStatusAddress(appId);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);

    ResponseHandler<Pair<Integer, String>> rh = response -> {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            if (statusLine.getStatusCode() == 404 || statusLine.getStatusCode() == 330) {
                return null;
            }

            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        if (entity == null) {
            throw new ClientProtocolException("Response contains no content");
        }

        String content = EntityUtils.toString(entity);

        JSONObject o = null;
        try {
            o = new JSONObject(content);
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }

        if (!o.has("app") || o.isNull("app")) {
            throw new RuntimeException("Response content not valid " + content);
        }

        try {
            return Pair.of(statusLine.getStatusCode(), o.getJSONObject("app").getString("finalStatus"));
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }
    };

    Pair<Integer, String> pair = httpclient.execute(httpget, rh);

    if (pair == null) {
        return null;
    }

    switch (pair.getRight()) {
    case "FAILED":
        return FlowStatus.FAILED;
    case "KILLED":
        return FlowStatus.KILL;
    case "SUCCEEDED":
        return FlowStatus.SUCCESS;
    case "NEW":
    case "NEW_SAVING":
    case "SUBMITTED":
    case "ACCEPTED":
        return FlowStatus.INIT;
    case "RUNNING":
    default:
        return FlowStatus.RUNNING;
    }
}

From source file:org.sikuli.script.App.java

/**
 * create a HTTP Client (for use of wwGet, ... multiple times as session)
 * @return true on success, false otherwise
 *//*w ww . jav a2s. c  o  m*/
public static boolean wwwStart() {
    if (httpclient != null) {
        return true;
    }
    httpclient = HttpClients.createDefault();
    if (httpclient != null) {
        return true;
    }
    return false;
}