Example usage for javax.net.ssl SSLContext getDefault

List of usage examples for javax.net.ssl SSLContext getDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getDefault.

Prototype

public static SSLContext getDefault() throws NoSuchAlgorithmException 

Source Link

Document

Returns the default SSL context.

Usage

From source file:com.amazonaws.client.service.AmazonHttpClient.java

/**
 * Disables the default strict hostname verification in this client and
 * instead uses a browser compatible hostname verification strategy (i.e.
 * cert hostname wildcards are evaulated more liberally).
 *//*from w  w w.  ja v  a2 s .  co  m*/
public void disableStrictHostnameVerification() {

    /*
     * If SSL cert checking for endpoints is disabled, we don't need
     * to do any changes to the SSL context.
     */
    if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        return;
    }

    try {
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException(
                "Unable to access default SSL context to disable strict hostname verification");
    }
}

From source file:com.liferay.sync.engine.session.Session.java

private static SSLConnectionSocketFactory _getDefaultSSLSocketFactory() throws Exception {

    if (_defaultSSLSocketFactory == null) {
        _defaultSSLSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault());
    }/* w w  w . j  a v a 2 s .  c  o  m*/

    return _defaultSSLSocketFactory;
}

From source file:org.microg.gms.gcm.McsService.java

private synchronized void connect() {
    try {/*w ww.j a  v a2s . c  o m*/
        closeAll();
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetworkPref = GcmPrefs.get(this).getNetworkPrefForInfo(cm.getActiveNetworkInfo());
        if (!GcmPrefs.get(this).isEnabledFor(cm.getActiveNetworkInfo())) {
            scheduleReconnect(this);
            return;
        }

        logd("Starting MCS connection...");
        Socket socket = new Socket(SERVICE_HOST, SERVICE_PORT);
        logd("Connected to " + SERVICE_HOST + ":" + SERVICE_PORT);
        sslSocket = SSLContext.getDefault().getSocketFactory().createSocket(socket, SERVICE_HOST, SERVICE_PORT,
                true);
        logd("Activated SSL with " + SERVICE_HOST + ":" + SERVICE_PORT);
        inputStream = new McsInputStream(sslSocket.getInputStream(), rootHandler);
        outputStream = new McsOutputStream(sslSocket.getOutputStream(), rootHandler);
        inputStream.start();
        outputStream.start();

        startTimestamp = System.currentTimeMillis();
        lastHeartbeatAckElapsedRealtime = SystemClock.elapsedRealtime();
        lastIncomingNetworkRealtime = SystemClock.elapsedRealtime();
        scheduleHeartbeat(this);
    } catch (Exception e) {
        Log.w(TAG, "Exception while connecting!", e);
        rootHandler.sendMessage(rootHandler.obtainMessage(MSG_TEARDOWN, e));
    }
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create connection manager for http client.
 *
 * @return The connection manager for http client.
 */// w  w w  .  j a v a2  s  .  co m
private HttpClientConnectionManager createHttpClientConnectionManager() {
    ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        throw new BceClientException("Fail to create SSLConnectionSocketFactory", e);
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), socketFactory)
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
    connectionManager.setDefaultSocketConfig(SocketConfig.custom()
            .setSoTimeout(this.config.getSocketTimeoutInMillis()).setTcpNoDelay(true).build());
    connectionManager.setMaxTotal(this.config.getMaxConnections());
    return connectionManager;
}

From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java

public void startSocketConnection() {
    final OnlineControllerFragment self = this;
    final GlobalUtils globalUtils = this.getGlobalUtils();
    if (this.socket != null && this.socket.connected()) {
        return;//from w w  w . j  av a  2  s  .  com
    }
    this.progressDialog.show();
    this.progressDialog.setText(R.string.connecting_socket_server);
    String url = this.getPreferencesEditor().getString("preference_server_address",
            this.getString(R.string.preference_value_address));
    Uri uri = Uri.parse(url).buildUpon().appendQueryParameter("token", this.token).build();
    try {
        if (url.contains("https://")) {
            IO.setDefaultSSLContext(SSLContext.getDefault());
        }
        IO.Options options = new IO.Options();
        options.forceNew = true;
        options.reconnection = true;
        this.socket = IO.socket(uri.toString(), options);

        /*
         *  When the socket is connected.
         */
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.removeAllClients();
                self.progressDialog.dismiss();
            }

            /*
             *  When the socket is disconnected.
             */
        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.removeAllClients();
            }

            /*
             *  When the socket receives an error.
             */
        }).on(Socket.EVENT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    String error = (String) args[0];
                    if (error.contains("JsonWebToken") || error.contains("TokenExpiredError")) {
                        self.getBaseActivity().getPreferencesEditor().saveString("preference_server_token", "");
                        globalUtils.showToast(R.string.restoring_token);
                        self.refreshFragment();
                        return;
                    }
                } catch (ClassCastException e) {
                    //e.printStackTrace();
                }
                self.progressDialog.dismiss();
                globalUtils.showToast(R.string.unknown_error);
            }

            /*
             *  When a new client is disconnected.
             */
        }).on("leave_member", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject members = ((JSONObject) args[0]).getJSONObject("members");
                    Iterator<String> membersList = members.keys();
                    while (membersList.hasNext()) {
                        String id = membersList.next();
                        Client client = Client.fromJSON(members.getJSONObject(id));
                        client.setId(id);
                        final int index = self.clientsAdapter.exists(client);
                        if (index == -1) {
                            continue;
                        }
                        if (self.calling != null
                                && self.calling.equals(self.clientsAdapter.get(index).getPeerId())) {
                            self.hideActions();
                            self.calling = "";
                            self.controlledBy = null;
                            self.getConnector().motorBC(0, 0, false, false);
                        }
                        self.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                self.clientsAdapter.remove(index);
                            }
                        });
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }

            /*
             *  When a new client is connected (also fired on first connection with all the active clients)
             */
        }).on("join_member", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject members = ((JSONObject) args[0]).getJSONObject("members");
                    Iterator<String> membersList = members.keys();
                    while (membersList.hasNext()) {
                        String id = membersList.next();
                        JSONObject member = members.getJSONObject(id);
                        final Client client = Client.fromJSON(member);
                        client.setId(id);
                        if (self.clientsAdapter.exists(client) > -1) {
                            continue;
                        }
                        self.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                self.clientsAdapter.add(client);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            /*
             *  When the client has answered our call request.
             */
        }).on("answered", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.progressDialog.dismiss();
                try {
                    JSONObject data = (JSONObject) args[0];
                    String from = data.getString("from");
                    boolean accepted = data.getBoolean("state");
                    if (from.equals(self.calling)) {
                        globalUtils.showToast(accepted ? R.string.call_accepted : R.string.call_rejected);
                        if (accepted) {
                            self.controlledBy = self.clientsAdapter.getByPeer(from);
                            self.showActions();
                        }
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }

            /*
             *  When the client sends us a motor order.
             */
        }).on("motors", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject data = (JSONObject) args[0];
                    String sender = data.getString("from");
                    if (!sender.equals(self.controlledBy.getPeerId()))
                        return;
                    double b = data.getDouble("b");
                    double c = data.getDouble("c");
                    self.getConnector().motorBC(c, b, false, false);
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }
        });/*.on("flash", new Emitter.Listener() {
           @Override
           public void call (Object... args) {
            try {
              JSONObject data = (JSONObject) args[0];
              String sender = data.getString("from");
              boolean state = data.getBoolean("state");
              if (!sender.equals(self.controlledBy.getPeerId())) return;
              if (!globalUtils.isFlashAvailable()) return;
              Camera camera = Camera.open();
              Camera.Parameters parameters = camera.getParameters();
              parameters.setFlashMode(state ? Camera.Parameters.FLASH_MODE_ON : Camera.Parameters.FLASH_MODE_OFF);
              camera.setParameters(parameters);
              camera.startPreview();
            } catch (JSONException e) {
              e.printStackTrace();
            }
           }
           });*/
        socket.connect();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        // We are fucked if this ends here!
    }
}

From source file:it.zero11.acme.Acme.java

protected Client getRestClient() {
    try {//from w  ww.j a  va  2s  .c  om
        Client client = ClientBuilder.newBuilder()
                .sslContext(
                        (trustAllCertificate) ? getTrustAllCertificateSSLContext() : SSLContext.getDefault())
                .build();

        if (debugHttpRequests) {
            try {
                Class<?> clazz = Class.forName("org.glassfish.jersey.filter.LoggingFilter");
                Constructor<?> contructor = clazz.getConstructor(Logger.class, boolean.class);
                client.register(contructor.newInstance(Logger.getLogger("it.zero11.acme"), true));
            } catch (Exception e) {

            }
        }

        return client;
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AcmeException(e);
    }
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java

private void initialize() {
    if (initialized.getAndSet(true)) {
        return;//from www  . j  a va2 s  .c  om
    }

    // HTTP parameters for the client
    final HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024));
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
            Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true")));
    params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0");

    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor;
    try {
        IOReactorConfig config = new IOReactorConfig();
        config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1));
        ioReactor = new DefaultConnectingIOReactor(config);
    } catch (IOReactorException e) {
        throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e);
    }

    // Create a default SSLSetupHandler that accepts any certificate
    if (sslContext == null) {
        try {
            sslContext = SSLContext.getDefault();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Create HTTP connection pool
    BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params);
    pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params);
    // Limit total number of connections to 500 by default
    pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500));
    pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500));

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                // Create client-side HTTP protocol handler
                HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
                // Create client-side I/O event dispatch
                IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext,
                        params);
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
        }

    }, "jsonrpc4j HTTP IOReactor");
    // Start the client thread
    t.setDaemon(true);
    t.start();

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });

    // Create HTTP requester
    requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params);
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

/**
 * Get list of supported Cipher Suites//from www.ja v a 2s  . com
 * @return Supported Cipher Suites
 */
public static List<String> getSupportedCipherSuites() {
    final String METHOD_NAME = "getSupportedCipherSuites(): ";

    try {
        final SSLContext sslContext = SSLContext.getDefault();
        final SSLSocketFactory sslsf = sslContext.getSocketFactory();
        return Arrays.asList(sslsf.getSupportedCipherSuites());

    } catch (NoSuchAlgorithmException exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + "Exception: " + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }

}