Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

In this page you can find the example usage for java.security KeyStore getDefaultType.

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:com.newrelic.agent.transport.DataSenderImpl.java

public static KeyStore getKeyStore()
        /* 183:    */ throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
/* 184:    */ {/* w w w. ja va2  s. c om*/
    /* 185:187 */ KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    /* 186:    */
    /* 187:189 */ InputStream in = DataSenderImpl.class.getResourceAsStream("/nrcerts");
    /* 188:190 */ if (null == in) {
        /* 189:191 */ Agent.LOG.fine("Unable to find NR trust store");
        /* 190:    */ } else {
        /* 191:    */ try
        /* 192:    */ {
            /* 193:194 */ keystore.load(in, null);
            /* 194:    */ }
        /* 195:    */ finally
        /* 196:    */ {
            /* 197:196 */ in.close();
            /* 198:    */ }
        /* 199:    */ }
    /* 200:200 */ Agent.LOG.finer("SSL Keystore Provider: " + keystore.getProvider().getName());
    /* 201:    */
    /* 202:202 */ return keystore;
    /* 203:    */ }

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for//  w w w .j  a  v a  2s . co  m
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a bad password to load the keystore.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithKeystoreIncorrectPassword(
        @Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore,
        @Mocked final FileInputStream file,
        @SuppressWarnings("unused") @Mocked final EncryptionServiceImpl asymetricCrypting) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";
        final String password = "password";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

            KeyStore.getInstance(KeyStore.getDefaultType());
            returns(keyStore);

            new FileInputStream(pathToKeystore);
            result = file;

            keyStoreDefinition.getPassword();
            returns(password);

            keyStore.load(file, password.toCharArray());
            result = new IOException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}

From source file:net.lamp.support.HttpManager.java

private static HttpClient getNewHttpClient() {
    try {/*w  w w.  j  a  v  a2s  .c om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) {
        // // ??APN?            // HttpHost proxy = NetStateManager.getAPN();
        // if (null != proxy) {
        // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
        // proxy);
        // }
        // }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:cn.edu.mju.Thriphoto.net.HttpManager.java

private static HttpClient getNewHttpClient() {
    try {// w  ww . jav  a 2  s  .c o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) {
        // // ??APN
        // HttpHost proxy = NetStateManager.getAPN();
        // if (null != proxy) {
        // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
        // proxy);
        // }
        // }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java

/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase/*from  w w  w .j a va2 s.  com*/
 */
public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase)
        throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath));

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);

        SSLServerSocketFactory res = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            res = ctx.getServerSocketFactory();

        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }

        SSLServerSocket ss = null;
        ss = (SSLServerSocket) res.createServerSocket();
        ss.setEnabledProtocols(ss.getSupportedProtocols());
        ss.setUseClientMode(false);
        ss.setWantClientAuth(false);
        ss.setNeedClientAuth(false);

        return ss;

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from   w w w.  jav  a 2s  .  c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Opens given keystore.//from   www.  j  a v  a 2 s  .com
 * 
 * @param aKsType
 * @param aKsFile
 * @param aKsPasswd
 * @return
 */
public static KeyStore loadKeyStore(String aKsType, final String aKsFile, final char[] aKsPasswd) {

    if (StringUtils.isEmpty(aKsType) && StringUtils.isEmpty(aKsFile)) {
        return loadCacertsKeyStore(null);
    }

    if (StringUtils.isEmpty(aKsType)) {
        aKsType = KeyStore.getDefaultType();
    }

    KeyStore tmpKs = null;
    InputStream tmpIS = null;
    try {
        tmpKs = KeyStore.getInstance(aKsType);
        if (StringUtils.isNotEmpty(aKsFile)) {
            tmpIS = new FileInputStream(aKsFile);
        }
        tmpKs.load(tmpIS, aKsPasswd);
        fixAliases(tmpKs);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (tmpIS != null)
            try {
                tmpIS.close();
            } catch (Exception e) {
            }
    }
    return tmpKs;
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

@Override
protected void setupCloudClient() throws IOException {
    // Get settings from the configuration
    bucketName = getProperty(BUCKET_NAME_PROPERTY);
    bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY);
    String bucketRegion = getProperty(BUCKET_REGION_PROPERTY);
    if (isBlank(bucketRegion)) {
        bucketRegion = DEFAULT_BUCKET_REGION;
    }//w ww .  java 2 s . c om
    String awsID = getProperty(AWS_ID_PROPERTY);
    String awsSecret = getProperty(AWS_SECRET_PROPERTY);

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY);
    int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY);
    int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY);
    int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY);

    String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY);
    String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY);
    String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY);
    String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY);
    String endpoint = getProperty(ENDPOINT_PROPERTY);
    String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY);
    if (isNotBlank(sseprop)) {
        userServerSideEncryption = Boolean.parseBoolean(sseprop);
    }

    // Fallback on default env keys for ID and secret
    if (isBlank(awsID)) {
        awsID = System.getenv(AWS_ID_ENV);
    }
    if (isBlank(awsSecret)) {
        awsSecret = System.getenv(AWS_SECRET_ENV);
    }

    if (isBlank(bucketName)) {
        throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY);
    }

    if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) {
        log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.",
                BUCKET_PREFIX_PROPERTY, bucketNamePrefix));
        bucketNamePrefix += "/";
    }
    // set up credentials
    if (isBlank(awsID) || isBlank(awsSecret)) {
        awsCredentialsProvider = new InstanceProfileCredentialsProvider();
        try {
            awsCredentialsProvider.getCredentials();
        } catch (AmazonClientException e) {
            throw new RuntimeException("Missing AWS credentials and no instance role found");
        }
    } else {
        awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret);
    }

    // set up client configuration
    clientConfiguration = new ClientConfiguration();
    if (isNotBlank(proxyHost)) {
        clientConfiguration.setProxyHost(proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        clientConfiguration.setProxyPort(Integer.parseInt(proxyPort));
    }
    if (isNotBlank(proxyLogin)) {
        clientConfiguration.setProxyUsername(proxyLogin);
    }
    if (proxyPassword != null) { // could be blank
        clientConfiguration.setProxyPassword(proxyPassword);
    }
    if (maxConnections > 0) {
        clientConfiguration.setMaxConnections(maxConnections);
    }
    if (maxErrorRetry >= 0) { // 0 is allowed
        clientConfiguration.setMaxErrorRetry(maxErrorRetry);
    }
    if (connectionTimeout >= 0) { // 0 is allowed
        clientConfiguration.setConnectionTimeout(connectionTimeout);
    }
    if (socketTimeout >= 0) { // 0 is allowed
        clientConfiguration.setSocketTimeout(socketTimeout);
    }

    // set up encryption
    encryptionMaterials = null;
    if (isNotBlank(keystoreFile)) {
        boolean confok = true;
        if (keystorePass == null) { // could be blank
            log.error("Keystore password missing");
            confok = false;
        }
        if (isBlank(privkeyAlias)) {
            log.error("Key alias missing");
            confok = false;
        }
        if (privkeyPass == null) { // could be blank
            log.error("Key password missing");
            confok = false;
        }
        if (!confok) {
            throw new RuntimeException("S3 Crypto configuration incomplete");
        }
        try {
            // Open keystore
            File ksFile = new File(keystoreFile);
            FileInputStream ksStream = new FileInputStream(ksFile);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(ksStream, keystorePass.toCharArray());
            ksStream.close();
            // Get keypair for alias
            if (!keystore.isKeyEntry(privkeyAlias)) {
                throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias");
            }
            PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray());
            Certificate cert = keystore.getCertificate(privkeyAlias);
            PublicKey pubKey = cert.getPublicKey();
            KeyPair keypair = new KeyPair(pubKey, privKey);
            // Get encryptionMaterials from keypair
            encryptionMaterials = new EncryptionMaterials(keypair);
            cryptoConfiguration = new CryptoConfiguration();
        } catch (IOException | GeneralSecurityException e) {
            throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias,
                    e);
        }
    }
    isEncrypted = encryptionMaterials != null;

    // Try to create bucket if it doesn't exist
    if (!isEncrypted) {
        amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);
    } else {
        amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider,
                new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration,
                cryptoConfiguration);
    }
    if (isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }

    // Set region explicitely for regions that reguire Version 4 signature
    ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>();
    V4_ONLY_REGIONS.add("eu-central-1");
    V4_ONLY_REGIONS.add("ap-northeast-2");
    if (V4_ONLY_REGIONS.contains(bucketRegion)) {
        amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion)));
    }

    try {
        if (!amazonS3.doesBucketExist(bucketName)) {
            amazonS3.createBucket(bucketName, bucketRegion);
            amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private);
        }
    } catch (AmazonClientException e) {
        throw new IOException(e);
    }

    // compat for NXP-17895, using "downloadfroms3", to be removed
    // these two fields have already been initialized by the base class initialize()
    // using standard property "directdownload"
    String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT);
    if (dd != null) {
        directDownload = Boolean.parseBoolean(dd);
    }
    int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT);
    if (dde >= 0) {
        directDownloadExpire = dde;
    }

    transferManager = new TransferManager(amazonS3);
    abortOldUploads();
}

From source file:mobile.tiis.appv2.LoginActivity.java

@Override
protected void onCreate(Bundle starter) {
    super.onCreate(starter);
    setContentView(R.layout.login_activity);

    // We load the KeyStore
    try {/*  w  w  w.j  ava 2s .c o  m*/
        /// We initialize a default Keystore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        // We initialize a new SSLSocketFacrory
        MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
        // We set that all host names are allowed in the socket factory
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        // We set the SSL Factory
        client.setSSLSocketFactory(socketFactory);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    client.setTimeout(DEFAULT_TIMEOUT);
    client.setMaxConnections(20);

    app = (BackboneApplication) getApplication();
    databaseHandler = app.getDatabaseInstance();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        if (isInternetAvailable()) {
            /**
             * registering the appv2 to Google Cloud Messaging
             */
            regId = getRegistrationId(getApplicationContext());
            Log.d(TAG, "regID = " + regId);
            if (regId.equals("")) {
                registerInBackground();
            }
        }
    } else {
        Log.i(TAG, "No valid Google Play Services APK found.");
    }

    //DatabaseHandler.getDBFile(this);
    //Delete vaccinationQueueRows that are not from today
    TextView titleText = (TextView) findViewById(R.id.login_screen_title);
    TextView ministryName = (TextView) findViewById(R.id.ministry_name);
    ministryName.setTypeface(BackboneActivity.Rosario_Regular);
    titleText.setTypeface(BackboneActivity.Rosario_Regular);
    //        getActionBar().setBackgroundDrawable(new ColorDrawable(this.getResources().getColor(R.color.light_blue_600)));

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
    }

    String dateNow = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    databaseHandler.deleteVaccinationQueueEntriesOfOtherDays(dateNow);

    app.LAST_FRAGMENT = "mobile.tiis.appv2.fragments.HomeFragment";
    app.LAST_FRAGMENT_TITLE = getString(R.string.home);

    //Starting the repeating synchronisation procedure that happens every 5 minutes
    login_preferences = getSharedPreferences(LOGINPREFERENCE, Context.MODE_PRIVATE);

    if (getIntent().hasExtra(BackboneActivity.LANGUAGELOGIN)) {
        languagePosition = getIntent().getIntExtra(BackboneActivity.LANGUAGELOGIN, 0);
        Log.d(TAGG, "Language Position before select = " + languagePosition + "");
    }

    progressDialog = new ProgressDialog(this, 0);
    language = (MaterialSpinner) findViewById(R.id.lang_spinner);
    listLanguage = new ArrayList<String>();
    listLanguage.add("Swahili");
    listLanguage.add("English");

    //Get username and password
    usernameEditText = (MaterialEditText) findViewById(R.id.username);
    usernameEditText.setFocusableInTouchMode(true);
    passwordEditText = (MaterialEditText) findViewById(R.id.password);
    passwordEditText.setFocusableInTouchMode(true);

    //Listen for a Login button click
    loginButton = (Button) findViewById(R.id.login_btn);
    SingleTextViewAdapter adapter = new SingleTextViewAdapter(this, R.layout.single_text_spinner_item_drop_down,
            listLanguage);
    language.setAdapter(adapter);

    language.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            switch (i) {
            case 0:
                languagePosition = 0;
                setLocale("sw");
                Log.d(TAGG, "selected position is " + i + " I put 0");
                break;
            case 1:
                languagePosition = 1;
                setLocale("en");
                Log.d(TAGG, "selected position is " + i + " I put 1");
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    loginButton.setOnClickListener(this);
    getSavedConfigurations();
}

From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java

public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort)
        throws Exception {

    CloseableHttpClient httpClient = null;
    try {//from  w  w  w.ja  va2s .  c  o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Authorization", "Negotiate " + ticket);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}