Example usage for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier

List of usage examples for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl AllowAllHostnameVerifier AllowAllHostnameVerifier.

Prototype

AllowAllHostnameVerifier

Source Link

Usage

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.StandardDirectorUtils.java

private static String getBoshDirectorUaaToken(String host, String directorName, String password)
        throws GeneralSecurityException {

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();/*w ww  .  j  a v a  2 s .  co m*/

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    String base64Passowrd = encodePassword(directorName, password);
    headers.add("Authorization", "Basic " + base64Passowrd);
    headers.add("Content-Type", "application/x-www-form-urlencoded");

    String postArgs = "grant_type=client_credentials";

    HttpEntity<String> requestEntity = new HttpEntity<String>(postArgs, headers);
    String uri = "https://" + host + ":8443/oauth/token";
    UaaToken response = restTemplate.postForObject(uri, requestEntity, UaaToken.class);

    log.info("Uaa token:" + response);
    return response.getAccess_token();
}

From source file:fr.bmartel.android.tictactoe.GameSingleton.java

private GameSingleton(Context context) {

    this.context = context.getApplicationContext();
    this.executor = Executors.newFixedThreadPool(1);

    //queue = Volley.newRequestQueue(context.getApplicationContext());
    HttpStack hurlStack = new HurlStack() {
        @Override/*w ww .j  a v a  2  s . c  om*/
        protected HttpURLConnection createConnection(URL url) throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            try {
                httpsURLConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
                httpsURLConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };
    queue = Volley.newRequestQueue(context, hurlStack);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    //load device id from shared preference
    DEVICE_ID = sharedPreferences.getString(RequestConstants.DEVICE_ID, "");
    deviceName = sharedPreferences.getString(RequestConstants.DEVICE_NAME, RequestConstants.DEFAULT_USERNAME);

    if (DEVICE_ID.equals("")) {
        //register deviceId in shared preference
        SharedPreferences.Editor editor = sharedPreferences.edit();
        DEVICE_ID = new RandomGen(DEVICE_ID_SIZE).nextString();
        editor.putString(RequestConstants.DEVICE_ID, DEVICE_ID);
        editor.commit();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/connect",
            RequestBuilder.buildConnectionRequest(DEVICE_ID, deviceName), new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "response received connect : " + response.toString());
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    error.printStackTrace();
                }
            });
    jsObjRequest.setShouldCache(false);

    queue.add(jsObjRequest);

    Log.i(TAG, "device id " + DEVICE_ID + " initialized");

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(context, RegistrationIntentService.class);
        context.startService(intent);
    }
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {// www .j  av  a 2 s  .  com
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

From source file:org.kontalk.client.ClientHTTPConnection.java

private void setupClient(HttpsURLConnection conn, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoInput(true);/*from   w  w w  .  ja  v a2 s . c o  m*/
    conn.setSSLSocketFactory(setupSSLSocketFactory(mContext, mPrivateKey, mCertificate, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
}

From source file:com.axibase.tsd.client.HttpClient.java

static PoolingHttpClientConnectionManager createConnectionManager(ClientConfiguration clientConfiguration,
        SslConfigurator sslConfig) {//from   w  w  w .  j ava 2s. c om
    SSLContext sslContext = sslConfig.createSSLContext();
    X509HostnameVerifier hostnameVerifier;
    if (clientConfiguration.isIgnoreSSLErrors()) {
        ignoreSslCertificateErrorInit(sslContext);
        hostnameVerifier = new AllowAllHostnameVerifier();
    } else {
        hostnameVerifier = new StrictHostnameVerifier();
    }

    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            hostnameVerifier);

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:com.spectralogic.ds3client.NetworkClientImpl.java

private static CloseableHttpClient createDefaultClient(final ConnectionDetails connectionDetails) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTION_TOTAL);

    if (connectionDetails.isHttps() && !connectionDetails.isCertificateVerification()) {
        try {/*w  ww.j  a va2 s .c o m*/

            final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).useTLS().build();

            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new AllowAllHostnameVerifier());
            return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf)
                    .build();

        } catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new SSLSetupException(e);
        }
    } else {
        return HttpClients.custom().setConnectionManager(connectionManager).build();
    }
}

From source file:com.mgmtp.perfload.core.client.web.config.HttpClientManagerModule.java

/**
 * If the property {@code ssl.trust.all} equals {@code true}, a {@link TrustAllManager} is
 * installed, i. e. all certificates are trusted, and host name verification is turned off.
 * Otherwise, {@link LtSSLSocketFactory} is registered for HTTPS, if either a key store, a trust
 * store or both are configured using the following properties:</p>
 * <p>/*www .  j  a v  a  2  s.  com*/
 * <ul>
 * <li>{@code javax.net.ssl.keyStore}</li>
 * <li>{@code javax.net.ssl.keyStorePassword}</li>
 * <li>{@code javax.net.ssl.keyStoreType}</li>
 * <li>{@code javax.net.ssl.trustStore}</li>
 * <li>{@code javax.net.ssl.trustStorePassword}</li>
 * <li>{@code javax.net.ssl.trustStoreType}</li>
 * </ul>
 * </p>
 * <p>
 * {@code javax.net.ssl.trustStore} and {@code javax.net.ssl.keyStore} must point to resources
 * on the classpath.
 * </p>
 * 
 * @param properties
 *            the properties
 * @return the {@link SchemeRegistry} the SchemeRegistry used for the HttpClient's
 *         {@link ClientConnectionManager} registered for HTTPS
 */
@Provides
@Singleton
protected SchemeRegistry provideSchemeRegistry(final PropertiesMap properties) {
    SchemeRegistry registry = SchemeRegistryFactory.createDefault();

    if (properties.getBoolean(SSL_TRUST_ALL)) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new TrustAllManager() }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, new AllowAllHostnameVerifier());
            registry.register(new Scheme("https", 443, ssf));
        } catch (GeneralSecurityException ex) {
            Throwables.propagate(ex);
        }
    } else {
        String keyStore = trimToNull(properties.get(KEY_STORE));
        String trustStore = trimToNull(properties.get(TRUST_STORE));

        if (keyStore != null || trustStore != null) {
            String keyStorePassword = trimToNull(properties.get(KEY_STORE_PASSWORD));
            String keyStoreType = trimToNull(properties.get(KEY_STORE_TYPE));

            String trustStorePassword = trimToNull(properties.get(TRUST_STORE_PASSWORD));
            String trustStoreType = trimToNull(properties.get(TRUST_STORE_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL keyStoreUrl = keyStore != null ? loader.getResource(keyStore) : null;
            URL trustStoreUrl = trustStore != null ? loader.getResource(trustStore) : null;

            LayeredSchemeSocketFactory socketFactory = new LtSSLSocketFactory(keyStoreUrl, keyStorePassword,
                    keyStoreType, trustStoreUrl, trustStorePassword, trustStoreType);

            registry.register(new Scheme(HTTPS, 443, socketFactory));
        }
    }
    return registry;
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Gets the http client.//from   www.  j  a  va 2 s. c om
 *
 * @param certificate the certificate
 * @param password the password
 * @return the http client
 */
public static CloseableHttpClient getPKCSKeyHttpClient(final String certificate, final String password) {

    try {
        final KeyStore keystore = KeyStore.getInstance("pkcs12");
        keystore.load(HTTPSClient.class.getClassLoader().getResourceAsStream(certificate),
                password.toCharArray());
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadKeyMaterial(keystore, password.toCharArray());
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setHostnameVerifier(new AllowAllHostnameVerifier()).build();
        return httpClient;
    } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException
            | CertificateException | IOException e) {
        LOGGER.error("Error processing SSL certificates in HTTPS method. Reason ::: " + e);
        return null;
    }
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);

    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);

    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }//from ww  w .  j a va2  s .  c  o m

    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);

    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);

    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);

    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK),
            DEFAULT_DISABLE_CERT_CHECK);

    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);

    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {/*from ww  w  . ja v a 2s .  co m*/
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}