Example usage for com.squareup.okhttp OkHttpClient OkHttpClient

List of usage examples for com.squareup.okhttp OkHttpClient OkHttpClient

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient OkHttpClient.

Prototype

public OkHttpClient() 

Source Link

Usage

From source file:com.nizlumina.utils.WebUnitMaster.java

License:Open Source License

private WebUnitMaster() {
    mainClient = new OkHttpClient();
    int cacheSize = 10 * 1024 * 1024; //10 MB
    try {//ww  w .  ja v  a2  s  .c o m
        mCache = new Cache(new File(cacheLocation), cacheSize);
        mainClient.setCache(mCache);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.nizlumina.utils.WebUnitMaster.java

License:Open Source License

public WebUnit() {
    mClient = new OkHttpClient();
}

From source file:com.northernwall.hadrian.HadrianBuilder.java

License:Apache License

public Hadrian builder() {
    client = new OkHttpClient();
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    client.setReadTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(2, TimeUnit.SECONDS);
    client.setFollowSslRedirects(false);
    client.setFollowRedirects(false);// w ww  . jav  a2s.co  m
    client.setConnectionPool(new ConnectionPool(5, 60 * 1000));

    if (metricRegistry == null) {
        metricRegistry = new MetricRegistry();

        final OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory
                .getOperatingSystemMXBean();
        metricRegistry.register("jvm.processCpuLoad", new Gauge<Double>() {
            @Override
            public Double getValue() {
                return osBean.getProcessCpuLoad();
            }
        });
        metricRegistry.register("jvm.systemCpuLoad", new Gauge<Double>() {
            @Override
            public Double getValue() {
                return osBean.getSystemCpuLoad();
            }
        });

        if (parameters.getBoolean("metrics.console", false)) {
            ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry)
                    .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
            reporter.start(1, TimeUnit.MINUTES);
        }

        String graphiteUrl = parameters.getString("metrics.graphite.url", null);
        int graphitePort = parameters.getInt("metrics.graphite.port", -1);
        if (graphiteUrl != null && graphitePort > -1) {
            Graphite graphite = new Graphite(new InetSocketAddress(graphiteUrl, graphitePort));
            GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
                    .prefixedWith(
                            parameters.getString("metrics.graphite.prefix", "hadrian") + "." + getHostname())
                    .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS)
                    .filter(MetricFilter.ALL).build(graphite);
            reporter.start(parameters.getInt("metrics.graphite.poll", 20), TimeUnit.SECONDS);
        }
    }

    if (dataAccess == null) {
        String factoryName = parameters.getString(Const.DATA_ACCESS_FACTORY_CLASS_NAME,
                Const.DATA_ACCESS_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find DataAccess class " + factoryName);
        }
        DataAccessFactory factory;
        try {
            factory = (DataAccessFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation DataAccess class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access DataAccess class " + factoryName);
        }
        dataAccess = factory.createDataAccess(parameters, metricRegistry);
    }

    if (moduleArtifactHelper == null) {
        String factoryName = parameters.getString(Const.MODULE_ARTIFACT_HELPER_FACTORY_CLASS_NAME,
                Const.MODULE_ARTIFACT_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find ModuleArtifactHelper class " + factoryName);
            }
            ModuleArtifactHelperFactory moduleArtifactHelperFactory;
            try {
                moduleArtifactHelperFactory = (ModuleArtifactHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation ModuleArtifactHelper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access ModuleArtifactHelper class " + factoryName);
            }
            moduleArtifactHelper = moduleArtifactHelperFactory.create(parameters, client);
        }
    }

    if (moduleConfigHelper == null) {
        String factoryName = parameters.getString(Const.MODULE_CONFIG_HELPER_FACTORY_CLASS_NAME, null);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find ModuleConfigHelper class " + factoryName);
            }
            ModuleConfigHelperFactory moduleConfigHelperFactory;
            try {
                moduleConfigHelperFactory = (ModuleConfigHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation ModuleConfigHelper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access ModuleConfigHelper class " + factoryName);
            }
            moduleConfigHelper = moduleConfigHelperFactory.create(parameters, client);
        }
    }

    configHelper = new ConfigHelper(parameters, moduleArtifactHelper, moduleConfigHelper);

    accessHelper = new AccessHelper(dataAccess);

    if (accessHandler == null) {
        String factoryName = parameters.getString(Const.ACCESS_HANDLER_FACTORY_CLASS_NAME,
                Const.ACCESS_HANDLER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("Could not build Hadrian, could not find Access class " + factoryName);
        }
        AccessHandlerFactory accessHanlderFactory;
        try {
            accessHanlderFactory = (AccessHandlerFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Access class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("Could not build Hadrian, could not access Access class " + factoryName);
        }
        accessHandler = accessHanlderFactory.create(accessHelper, parameters, metricRegistry);
    }

    if (hostDetailsHelper == null) {
        String factoryName = parameters.getString(Const.HOST_DETAILS_HELPER_FACTORY_CLASS_NAME,
                Const.HOST_DETAILS_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find Host Details Helper class " + factoryName);
        }
        HostDetailsHelperFactory hostDetailsHelperFactory;
        try {
            hostDetailsHelperFactory = (HostDetailsHelperFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Host Details Helper class "
                            + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access Host Details Helper class " + factoryName);
        }
        hostDetailsHelper = hostDetailsHelperFactory.create(client, parameters);
    }

    if (vipDetailsHelper == null) {
        String factoryName = parameters.getString(Const.VIP_DETAILS_HELPER_FACTORY_CLASS_NAME,
                Const.VIP_DETAILS_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        if (factoryName != null && !factoryName.isEmpty()) {
            Class c;
            try {
                c = Class.forName(factoryName);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not find VIP Details Helper class " + factoryName);
            }
            VipDetailsHelperFactory vipDetailsHelperFactory;
            try {
                vipDetailsHelperFactory = (VipDetailsHelperFactory) c.newInstance();
            } catch (InstantiationException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not instantiation VIP Details Helper class "
                                + factoryName);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(
                        "Could not build Hadrian, could not access VIP Details Helper class " + factoryName);
            }
            vipDetailsHelper = vipDetailsHelperFactory.create(client, parameters, configHelper);
        }
    }

    if (calendarHelper == null) {
        String factoryName = parameters.getString(Const.CALENDAR_HELPER_FACTORY_CLASS_NAME,
                Const.CALENDAR_HELPER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find Calendar Helper class " + factoryName);
        }
        CalendarHelperFactory calendarHelperFactory;
        try {
            calendarHelperFactory = (CalendarHelperFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation Calendar Helper class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access Calendar Helper class " + factoryName);
        }
        calendarHelper = calendarHelperFactory.create(parameters, client);
    }

    if (workItemSender == null) {
        String factoryName = parameters.getString(Const.WORK_ITEM_SENDER_FACTORY_CLASS_NAME,
                Const.WORK_ITEM_SENDER_FACTORY_CLASS_NAME_DEFAULT);
        Class c;
        try {
            c = Class.forName(factoryName);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not find WorkItemSender class " + factoryName);
        }
        WorkItemSenderFactory workItemSenderFactory;
        try {
            workItemSenderFactory = (WorkItemSenderFactory) c.newInstance();
        } catch (InstantiationException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not instantiation WorkItemSender class " + factoryName);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(
                    "Could not build Hadrian, could not access WorkItemSender class " + factoryName);
        }
        workItemSender = workItemSenderFactory.create(parameters, dataAccess, client, metricRegistry);
    }

    WorkItemProcessor workItemProcessor = new WorkItemProcessorImpl(dataAccess, workItemSender, metricRegistry);
    workItemSender.setWorkItemProcessor(workItemProcessor);

    DataAccessUpdater.update(dataAccess);

    return new Hadrian(parameters, client, configHelper, dataAccess, moduleArtifactHelper, moduleConfigHelper,
            accessHelper, accessHandler, hostDetailsHelper, vipDetailsHelper, calendarHelper, workItemProcessor,
            workItemSender, metricRegistry);
}

From source file:com.northernwall.hadrian.MessagingCoodinatorTest.java

License:Apache License

public MessagingCoodinatorTest() {
    client = new OkHttpClient();
    client.setConnectTimeout(2, TimeUnit.SECONDS);
    client.setReadTimeout(2, TimeUnit.SECONDS);
    client.setWriteTimeout(2, TimeUnit.SECONDS);
    client.setFollowSslRedirects(false);
    client.setFollowRedirects(false);//from w w  w.ja v  a  2  s .  c om
    client.setConnectionPool(new ConnectionPool(5, 60 * 1000));
}

From source file:com.nuvolect.securesuite.webserver.WebService.java

License:Open Source License

public static OkHttpClient getOkHttpClient() {

    if (okHttpClient == null) {

        okHttpClient = new OkHttpClient();
        okHttpClient.setHostnameVerifier(WebUtil.NullHostNameVerifier.getInstance());
        okHttpClient.setSslSocketFactory(sslSocketFactory);
    }/*w  ww  .  j  ava  2 s .c  o m*/
    return okHttpClient;
}

From source file:com.onaio.steps.helper.UploadFileTask.java

License:Apache License

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        try {/*from   w  w  w. j a va 2s.com*/
            OkHttpClient client = new OkHttpClient();

            final MediaType MEDIA_TYPE = MediaType.parse("text/csv");

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addFormDataPart("file", files[0].getName(), RequestBody.create(MEDIA_TYPE, files[0]))
                    .build();

            Request request = new Request.Builder()
                    .url(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL)).post(requestBody)
                    .build();
            client.newCall(request).execute();
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}

From source file:com.oneops.crawler.ThanosClient.java

License:Apache License

public ThanosClient() {
    readConfig();
    gson = new Gson();
    client = new OkHttpClient();
}

From source file:com.onfido.ApiClient.java

License:Apache License

public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;//w  w w . jav a2 s .co  m

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Onfido/1.3.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put("Token", new ApiKeyAuth("header", "Authorization"));
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}

From source file:com.open.taogubaweex.adapter.DefaultWebSocketAdapter.java

License:Apache License

@Override
public void connect(String url, @Nullable String protocol, EventListener listener) {
    this.eventListener = listener;
    OkHttpClient okHttpClient = new OkHttpClient();

    Request.Builder builder = new Request.Builder();

    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }/*ww w  . jav  a  2  s  .com*/
    url = url + "?token=" + URLEncoder.encode("android_1262670&B05016B999132BC0C7C69297B1748CB6");
    builder.url(url);

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            //                public void checkClientTrusted(X509Certificate[] certs, String authType) {
            //                    System.out.println("checkClientTrusted1");
            //                }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkClientTrusted2");
            }

            //                public void checkServerTrusted(X509Certificate[] certs,
            //                                               String authType) {
            //                    System.out.println("checkServerTrusted1");
            //                }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkServerTrusted2");
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLSocketFactory factory = sslContext.getSocketFactory();
    okHttpClient.setSslSocketFactory(factory);

    WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() {
        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            eventListener.onMessage(payload.readUtf8());
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {

        }

        @Override
        public void onClose(int code, String reason) {
            eventListener.onClose(code, reason, true);
        }

        @Override
        public void onFailure(IOException e) {
            e.printStackTrace();
            if (e instanceof EOFException) {
                eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(),
                        WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
            } else {
                eventListener.onError(e.getMessage());
            }
        }
    });
}

From source file:com.oracle.bdcs.bdm.client.ApiClient.java

License:Apache License

public ApiClient() {
    httpClient = new OkHttpClient();

    verifyingSsl = true;// www. j  a v  a  2  s  .  com

    json = new JSON(this);

    /*
     * Use RFC3339 format for date and datetime.
     * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
     */
    this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // Always use UTC as the default time zone when dealing with date (without time).
    this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    initDatetimeFormat();

    // Be lenient on datetime formats when parsing datetime from string.
    // See <code>parseDatetime</code>.
    this.lenientDatetimeFormat = true;

    // Set default User-Agent.
    setUserAgent("Swagger-Codegen/1.0.0/java");

    // Setup authentications (key: authentication name, value: authentication).
    authentications = new HashMap<String, Authentication>();
    authentications.put(HttpBasicAuth.class.getName(), new HttpBasicAuth());
    authentications.put(ApiKeyAuth.class.getName(), new ApiKeyAuth(ApiKeyAuth.HEADER_LOCATION, API_KEY_NAME));
    // Prevent the authentications from being modified.
    authentications = Collections.unmodifiableMap(authentications);
}