Example usage for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.opcfoundation.ua.examples.TestStackExample.java

public static void main(String[] args) throws Exception {

    //////////////  SERVER  //////////////
    // Create UA Server Application
    Application myServerApplication = new Application();
    myServerApplication.getOpctcpSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myServerApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myServerApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    // Create UA Service Server
    Server myServer = new Server(myServerApplication);

    // Add a service to the server - TestStack echo
    myServer.addServiceHandler(new TestStackService());

    // Load Servers's Application Instance Certificate from file
    KeyPair myServerApplicationInstanceCertificate = ExampleKeys.getKeyPair("server", 2048);
    KeyPair myServerHttpsKey = ExampleKeys.getKeyPair("https_server", 2048);
    // Add application instance certificate      
    myServerApplication.addApplicationInstanceCertificate(myServerApplicationInstanceCertificate);
    myServerApplication.getHttpsSettings().setKeyPair(myServerHttpsKey);

    // Bind the endpoint for each network interface
    String hostname = EndpointUtil.getHostname();
    for (String addr : EndpointUtil.getInetAddressNames()) {
        String bindAddress = "opc.tcp://" + addr + ":6002/UAExample";
        String endpointAddress = "opc.tcp://" + hostname + ":6002/UAExample";
        myServer.bind(bindAddress, endpointAddress, SecurityMode.ALL);
    }//from ww w  .j av a 2s  . c o m
    //////////////////////////////////////

    //////////////  CLIENT  //////////////
    // Load Client's Application Instance Certificate from file
    KeyPair myClientApplicationInstanceCertificate = ExampleKeys.getKeyPair("client", 2048);
    // Create Client
    Client myClient = Client.createClientApplication(myClientApplicationInstanceCertificate);
    //////////////////////////////////////      

    /////////// DISCOVER ENDPOINT ////////
    // Discover server's endpoints, and choose one
    EndpointDescription[] endpoints = myClient.discoverEndpoints("opc.tcp://" + hostname + ":6002/"); //51210=Sample Server
    // Filter out all but opc.tcp protocol endpoints
    endpoints = EndpointUtil.selectByProtocol(endpoints, "opc.tcp");
    // Filter out all but Signed & Encrypted endpoints
    endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.SignAndEncrypt);
    // Filter out all but Basic128 cryption endpoints
    endpoints = EndpointUtil.selectBySecurityPolicy(endpoints, SecurityPolicy.BASIC128RSA15);
    // Sort endpoints by security level. The lowest level at the beginning, the highest at the end of the array
    endpoints = EndpointUtil.sortBySecurityLevel(endpoints);
    // Choose one endpoint
    EndpointDescription endpoint = endpoints[endpoints.length - 1];
    //////////////////////////////////////      

    ////////////  TEST-STACK  ////////////
    // Create Channel
    ServiceChannel myChannel = myClient.createServiceChannel(endpoint);
    // Create Test Request      
    TestStackRequest req = new TestStackRequest(null, null, null, new Variant("Hello World"));
    System.out.println("REQUEST: " + req);
    // Invoke service
    TestStackResponse res = myChannel.TestStack(req);
    // Print result
    System.out.println("RESPONSE: " + res);
    //////////////////////////////////////      

    /////////////  SHUTDOWN  /////////////
    // Close channel
    myChannel.closeAsync();
    // Unbind endpoint. This also closes the socket 6001 as it has no more endpoints.
    myServer.getApplication().close();
    //////////////////////////////////////      

}

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ///*from w  w  w .j  a v  a 2s  .  com*/
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

From source file:pt.ua.tm.neji.web.test.TestREST.java

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/* ww w  .  j  a v  a2 s  . co m*/

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

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

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

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt";

    // POST
    CloseableHttpClient client = new DefaultHttpClient(ccm, params);

    HttpPost post = new HttpPost(url);
    //post.setHeader("Content-Type", "application/json");

    List<NameValuePair> keyValuesPairs = new ArrayList();
    //keyValuesPairs.add(new BasicNameValuePair("format", "neji"));
    keyValuesPairs.add(new BasicNameValuePair("fromFile", "false"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}"));
    keyValuesPairs.add(new BasicNameValuePair("text", text));
    keyValuesPairs.add(new BasicNameValuePair("crlf", "false"));
    post.setEntity(new UrlEncodedFormEntity(keyValuesPairs));

    HttpResponse response = client.execute(post);

    String result = IOUtils.toString(response.getEntity().getContent());

    System.out.println(result);
}

From source file:org.opcfoundation.ua.examples.SampleClient.java

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: SampleClient [server uri]");
        return;//w w w.ja  v  a 2  s  .co  m
    }
    String url = args[0];
    System.out.print("SampleClient: Connecting to " + url + " .. ");

    //////////////  CLIENT  //////////////
    // Create Client
    Application myApplication = new Application();
    Client myClient = new Client(myApplication);
    myApplication.addLocale(ENGLISH);
    myApplication.setApplicationName(new LocalizedText("Java Sample Client", Locale.ENGLISH));
    myApplication.setProductUri("urn:JavaSampleClient");

    CertificateUtils.setKeySize(1024); // default = 1024
    KeyPair pair = ExampleKeys.getCert("SampleClient");
    myApplication.addApplicationInstanceCertificate(pair);

    // The HTTPS SecurityPolicies are defined separate from the endpoint securities
    myApplication.getHttpsSettings().setHttpsSecurityPolicies(HttpsSecurityPolicy.ALL);

    // Peer verifier
    myApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    myApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);

    // The certificate to use for HTTPS
    KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("SampleClient");
    myApplication.getHttpsSettings().setKeyPair(myHttpsCertificate);

    // Connect to the given uri
    SessionChannel mySession = myClient.createSessionChannel(url);
    //      mySession.activate("username", "123");
    mySession.activate();
    //////////////////////////////////////      

    /////////////  EXECUTE  //////////////      
    // Browse Root
    BrowseDescription browse = new BrowseDescription();
    browse.setNodeId(Identifiers.RootFolder);
    browse.setBrowseDirection(BrowseDirection.Forward);
    browse.setIncludeSubtypes(true);
    browse.setNodeClassMask(NodeClass.Object, NodeClass.Variable);
    browse.setResultMask(BrowseResultMask.All);
    BrowseResponse res3 = mySession.Browse(null, null, null, browse);
    System.out.println(res3);

    // Read Namespace Array
    ReadResponse res5 = mySession.Read(null, null, TimestampsToReturn.Neither,
            new ReadValueId(Identifiers.Server_NamespaceArray, Attributes.Value, null, null));
    String[] namespaceArray = (String[]) res5.getResults()[0].getValue().getValue();
    System.out.println(Arrays.toString(namespaceArray));

    // Read a variable
    ReadResponse res4 = mySession.Read(null, 500.0, TimestampsToReturn.Source,
            new ReadValueId(new NodeId(6, 1710), Attributes.Value, null, null));
    System.out.println(res4);

    res4 = mySession.Read(null, 500.0, TimestampsToReturn.Source,
            new ReadValueId(new NodeId(6, 1710), Attributes.DataType, null, null));
    System.out.println(res4);

    /////////////  SHUTDOWN  /////////////
    mySession.close();
    mySession.closeAsync();
    //////////////////////////////////////   

}

From source file:org.opcfoundation.ua.examples.GenerateCertificateExample.java

public static void main(String[] args) throws Exception {

    //      //Add provider for certificate generator
    //      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());   

    //////////////  SERVER  //////////////
    // Create UA Server Application
    Application myServerApplication = new Application();
    // Create UA Service Server
    Server myServer = new Server(myServerApplication);
    // Add a service to the server - TestStack echo
    myServer.addServiceHandler(new TestStackService());

    // Check that certificates exists, if not -> create
    KeyPair myServerApplicationInstanceCertificate = null;
    // Create Application Instance Certificatge 
    {//from ww w  .j a  v  a  2s  .co  m
        String certificateCommonName = "UA Sample Server";
        System.out.println("Generating new Certificate for Server using CN: " + certificateCommonName);
        String applicationUri = myServerApplication.getApplicationUri();
        String organisation = "Sample Organisation";
        int validityTime = 365;
        String hostName = EndpointUtil.getHostname();
        myServerApplicationInstanceCertificate = CertificateUtils.createApplicationInstanceCertificate(
                certificateCommonName, organisation, applicationUri, validityTime, hostName);
    }
    // Add application instance certificate      
    myServerApplication.addApplicationInstanceCertificate(myServerApplicationInstanceCertificate);
    myServerApplication.getOpctcpSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myServerApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myServerApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    // Bind my server to my endpoint. This opens the port 6001 as well.
    String bindAddress = "opc.tcp://localhost:6001/UAExample";
    String endpointAddress = "opc.tcp://localhost:6001/UAExample";
    myServer.bind(bindAddress, endpointAddress, SecurityMode.ALL);
    //////////////////////////////////////

    //////////////  CLIENT  //////////////
    Application myClientApplication = new Application();
    // Load Client's Application Instance Certificate from file
    KeyPair myClientApplicationInstanceCertificate = null;

    // Create Client Application Instance Certificate
    {
        String certificateCommonName = "UA Sample Client";
        System.out.println("Generating new Certificate for Client using CN: " + certificateCommonName);
        String applicationUri = myClientApplication.getApplicationUri();
        String organisation = "Sample Organisation";
        int validityTime = 365;
        myClientApplicationInstanceCertificate = CertificateUtils.createApplicationInstanceCertificate(
                certificateCommonName, organisation, applicationUri, validityTime);
    }

    // Create Client
    Client myClient = new Client(myClientApplication);
    myClientApplication.addApplicationInstanceCertificate(myClientApplicationInstanceCertificate);
    //////////////////////////////////////      

    /////////// DISCOVER ENDPOINT ////////
    // Discover server's endpoints, and choose one
    EndpointDescription[] endpoints = myClient.discoverEndpoints("opc.tcp://localhost:8666/UAExample"); //51210=Sample Server
    // Filter out all but opc.tcp protocol endpoints
    endpoints = EndpointUtil.selectByProtocol(endpoints, "opc.tcp");
    // Filter out all but Signed & Encrypted endpoints
    endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.SignAndEncrypt);
    // Filter out all but Basic128 cryption endpoints
    endpoints = EndpointUtil.selectBySecurityPolicy(endpoints, SecurityPolicy.BASIC128RSA15);
    // Sort endpoints by security level. The lowest level at the beginning, the highest at the end of the array
    endpoints = EndpointUtil.sortBySecurityLevel(endpoints);
    // Choose one endpoint
    EndpointDescription endpoint = endpoints[endpoints.length - 1];
    //////////////////////////////////////      

    ////////////  TEST-STACK  ////////////
    // Create Channel
    ServiceChannel myChannel = myClient.createServiceChannel(endpoint);
    // Create Test Request      
    TestStackRequest req = new TestStackRequest(null, null, null, new Variant(new Short[32][256]));
    System.out.println("REQUEST: " + req);
    // Invoke service
    TestStackResponse res = myChannel.TestStack(req);
    // Print result
    System.out.println("RESPONSE: " + res);
    //////////////////////////////////////      

    //System.in.read();
    /////////////  SHUTDOWN  /////////////
    // Close channel
    myChannel.closeAsync();
    // Unbind endpoint. This also closes the socket 6001 as it has no more endpoints.
    myServer.getApplication().close();
    //////////////////////////////////////      

}

From source file:org.opcfoundation.ua.examples.ClientServerExample.java

public static void main(String[] args) throws Exception {
    // Create Logger
    Logger myLogger = LoggerFactory.getLogger(ClientServerExample.class);

    ///// Server Application /////////////      
    Application serverApplication = new Application();
    MyServerExample myServer = new MyServerExample(serverApplication);

    // Attach listener (debug logger) to each binding
    DebugLogger debugLogger = new DebugLogger(myLogger);
    for (EndpointServer b : myServer.getEndpointBindings().getEndpointServers())
        b.addConnectionListener(debugLogger);
    //////////////////////////////////////      

    //////////////  CLIENT  //////////////
    // Load Client's Application Instance Certificate from file
    KeyPair myClientApplicationInstanceCertificate = ExampleKeys.getCert("ClientServerExample");
    // Create Client
    Client myClient = Client.createClientApplication(myClientApplicationInstanceCertificate);
    Application myClientApplication = myClient.getApplication();
    myClientApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    myClientApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myClientApplication.getHttpsSettings().setHttpsSecurityPolicies(HttpsSecurityPolicy.ALL);

    //////////////////////////////////////      

    // Get Endpoints like this
    String uri;//from  ww w  .j  ava2s . c  o m
    uri = "opc.tcp://localhost:8666/UAExample";
    uri = "https://localhost:8443/UAExample";

    SessionChannel myChannel = null;
    try {
        myClient.setTimeout(10000);
        EndpointDescription[] endpoints = myClient.discoverEndpoints(uri, "");

        endpoints = EndpointUtil.selectByProtocol(endpoints, UriUtil.getTransportProtocol(uri));

        // Connect the application
        myChannel = myClient.createSessionChannel(endpoints[0]);
        // Activate session
        myChannel.activate();
        //////////////////////////////////////

        /////////////  EXECUTE  //////////////      
        CallRequest callRequest = new CallRequest();
        CallMethodRequest methodRequest = new CallMethodRequest();
        callRequest.setMethodsToCall(new CallMethodRequest[] { methodRequest });
        methodRequest.setMethodId(MyServerExample.LIST_SOLVERS);
        CallResponse res = myChannel.Call(callRequest);
        System.out.println(res);
        //////////////////////////////////////
    }

    finally {
        /////////////  SHUTDOWN  /////////////
        // Close client's channel
        if (myChannel != null)
            myChannel.close();
        // Close the server by unbinding all endpoints 
        myServer.getApplication().close();
        //////////////////////////////////////      
    }

}

From source file:org.opcfoundation.ua.examples.BigCertificateExample.java

public static void main(String[] args) throws Exception {
    // Create Logger
    Logger myLogger = LoggerFactory.getLogger(BigCertificateExample.class);

    ///// Server Application /////////////      
    Application serverApplication = new Application();
    MyServerExample2 myServer = new MyServerExample2(serverApplication);

    // Attach listener (debug logger) to each binding
    DebugLogger debugLogger = new DebugLogger(myLogger);
    for (EndpointServer b : myServer.getEndpointBindings().getEndpointServers())
        b.addConnectionListener(debugLogger);
    //////////////////////////////////////      

    //////////////  CLIENT  //////////////
    // Load Client's Application Instance Certificate from file
    KeyPair myClientOpcTcpKeyPair = ExampleKeys.getKeyPair("client", CLIENT_KEY_SIZE);
    KeyPair myClientHttpsKeyPair = ExampleKeys.getKeyPair("https_client", CLIENT_KEY_SIZE);
    // Create Client Application
    Application myClientApplication = new Application();
    myClientApplication.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    myClientApplication.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    myClientApplication.getHttpsSettings().setKeyPair(myClientHttpsKeyPair);
    myClientApplication.addApplicationInstanceCertificate(myClientOpcTcpKeyPair);
    // Create Client
    Client myClient = new Client(myClientApplication);
    //////////////////////////////////////      

    // Get Endpoints like this
    SecureChannel secureChannel = myClient.createSecureChannel(URL, URL, SecurityMode.NONE, null);
    ChannelService chan = new ChannelService(secureChannel);
    EndpointDescription[] endpoints;//  w w w  . ja v a  2 s.  c  om
    try {
        GetEndpointsRequest req = new GetEndpointsRequest(null, URL, new String[0], new String[0]);
        GetEndpointsResponse res = chan.GetEndpoints(req);
        endpoints = res.getEndpoints();
    } finally {
        secureChannel.close();
        secureChannel.dispose();
    }

    SessionChannel myChannel = null;
    try {
        // Select policy according to initial parameters
        String proto = UriUtil.getTransportProtocol(URL);
        endpoints = EndpointUtil.select(endpoints, CLIENT_KEY_SIZE, CLIENT_KEY_SIZE);
        endpoints = EndpointUtil.select(endpoints, null, proto, null, null, null);
        if (proto.equals("https")) {
            endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.None);
            myClient.getApplicationHttpsSettings().setHttpsSecurityPolicies(httpsSecurityPolicies);
        } else
            endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, MessageSecurityMode.SignAndEncrypt);
        if (endpoints.length == 0) {
            throw new IllegalArgumentException("No suitable endpoint found from " + URL);
        }

        /////////  DISCOVER SERVERS  /////////
        // Discover server applications
        //         ApplicationDescription[] servers = myClient.discoverApplications( new URI("https://localhost:6001/") );
        //         // Choose one application
        //         ApplicationDescription server = servers[0];
        // Connect the application         
        myChannel = myClient.createSessionChannel(endpoints[0]);
        //         myChannel = myClient.createSessionChannel( server );
        // Activate session
        myChannel.activate();
        //////////////////////////////////////

        /////////////  EXECUTE  //////////////      
        CallRequest callRequest = new CallRequest();
        CallMethodRequest methodRequest = new CallMethodRequest();
        callRequest.setMethodsToCall(new CallMethodRequest[] { methodRequest });
        methodRequest.setMethodId(MyServerExample2.LIST_SOLVERS);
        CallResponse res = myChannel.Call(callRequest);
        System.out.println(res);
        //////////////////////////////////////
    }

    finally {
        /////////////  SHUTDOWN  /////////////
        // Close client's channel
        if (myChannel != null)
            myChannel.close();
        // Close the server by unbinding all endpoints 
        myServer.getApplication().close();
        //////////////////////////////////////      
    }

}

From source file:com.dealoka.lib.net.HttpUtils.java

public static HttpClient getNewHttpClient() {
    try {//  www.j a  v a  2s . com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        HttpParams params = new BasicHttpParams();
        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);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.vmware.vcloudapi.FakeSSLSocketFactory.java

public static SSLSocketFactory getInstance()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    return new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(final X509Certificate[] chain, final String auth) throws CertificateException {
            // XXX register development / staging instances.
            return true;
        }/*from w ww .  j a v  a  2s  . com*/

    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:ru.elifantiev.yandex.SSLHttpClientFactory.java

public static HttpClient getNewHttpClient() {
    try {//  w  w  w .ja v a2 s .  c  o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        HttpParams params = new BasicHttpParams();
        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);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}