Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

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

Prototype

HostnameVerifier

Source Link

Usage

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/*from  w  ww. jav a2  s  .  c  o m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

From source file:com.gmobi.poponews.util.HttpHelper.java

static void disableSslCheck() {
    if (initialized)
        return;//w  w  w.jav a2 s.  com
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        initialized = true;
    } catch (Exception e) {
        Logger.error(e);
    }

}

From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Create SSL context that allows bad certificates.
 * /*from   w  w  w . j  a v a  2 s. c  o  m*/
 * @return
 */
protected SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.OAuthRequestInterceptor.java

public static Client getSSLClient() {
    boolean isIgnoreHostnameVerification = Boolean
            .parseBoolean(System.getProperty("org.wso2.ignoreHostnameVerification"));
    if (isIgnoreHostnameVerification) {
        return new Client.Default(getSimpleTrustedSSLSocketFactory(), new HostnameVerifier() {
            @Override/*from  w  w w.j  av a 2s  .  c  om*/
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } else {
        return new Client.Default(getTrustedSSLSocketFactory(), null);
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/*from  w w  w  .  j a  va 2 s .  c  om*/
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private HttpURLConnection GetConnection(String targetURL)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL url = new URL(targetURL);
    if (targetURL.startsWith("http://")) {
        return (HttpURLConnection) url.openConnection();
    }/*from   ww w .  j  a v  a 2  s.  co m*/

    //Create an all trusting SSL URL Connection
    //For in-house Stash servers with self-signed certs

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    return (HttpsURLConnection) url.openConnection();

}

From source file:org.apache.stratos.adc.mgt.cli.CommandLineService.java

public boolean login(String serverURL, String username, String password, boolean validateLogin)
        throws CommandException {
    try {//from www  .  ja va 2 s .co m
        // Following code will avoid validating certificate
        SSLContext sc;
        // Get SSL context
        sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        // Create a trust manager that does not validate certificate
        // chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        throw new RuntimeException("Error while authentication process!", e);
    }

    // Initialize Service Stub
    try {
        initializeApplicationManagementStub(serverURL, username, password);
    } catch (AxisFault e) {
        System.out.println("Error connecting to the back-end");
        throw new CommandException(e);
    }

    try {
        if (validateLogin) {
            String tenantDomain = stub.getTenantDomain();
            if (logger.isDebugEnabled()) {
                logger.debug("Tenant Domain {}", tenantDomain);
            }
            return (tenantDomain != null);
        } else {
            // Just return true as we don't need to validate
            return true;
        }
    } catch (RemoteException e) {
        System.out.println("Authentication failed!");
        throw new CommandException(e);
    }
}

From source file:it.serverSystem.HttpsTest.java

private void connectUntrusted() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from www. j a v a  2 s .  co m

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    // SSLv3 is disabled since SQ 4.5.2 : https://jira.codehaus.org/browse/SONAR-5860
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory untrustedSocketFactory = sc.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    URL url = new URL("https://localhost:" + httpsPort + "/sessions/login");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(true);
    connection.setSSLSocketFactory(untrustedSocketFactory);
    connection.setHostnameVerifier(allHostsValid);

    InputStream input = connection.getInputStream();
    checkCookieFlags(connection);
    try {
        String html = IOUtils.toString(input);
        assertThat(html).contains("<body");
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.alvexcore.share.ShareExtensionRegistry.java

public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes,
        String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion,
        String licenseId) throws Exception {
    // search for extension
    DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
    xmlFact.setNamespaceAware(true);/*from  w w w .  ja  va 2 s . c  o m*/
    xmlBuilder = xmlFact.newDocumentBuilder();

    // build query
    Document queryXML = xmlBuilder.newDocument();
    Element rootElement = queryXML.createElement("extension");
    queryXML.appendChild(rootElement);
    Element el = queryXML.createElement("license-id");
    el.appendChild(queryXML.createTextNode(licenseId));
    rootElement.appendChild(el);
    el = queryXML.createElement("id");
    el.appendChild(queryXML.createTextNode(extensionId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-version");
    el.appendChild(queryXML.createTextNode(shareVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-version");
    el.appendChild(queryXML.createTextNode(repoVersion));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-id");
    el.appendChild(queryXML.createTextNode(shareId));
    rootElement.appendChild(el);
    el = queryXML.createElement("repo-id");
    el.appendChild(queryXML.createTextNode(repoId));
    rootElement.appendChild(el);
    el = queryXML.createElement("share-files");
    rootElement.appendChild(el);
    for (String fileName : shareHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", shareHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    el = queryXML.createElement("repo-files");
    rootElement.appendChild(el);
    for (String fileName : repoHashes.keySet()) {
        Element fileElem = queryXML.createElement("file");
        fileElem.setAttribute("md5hash", repoHashes.get(fileName));
        fileElem.appendChild(queryXML.createTextNode(fileName));
        el.appendChild(fileElem);
    }
    // query server
    try {
        URL url = new URL(
                "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // disable host verification
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML),
                new StreamResult(wr));
        wr.close();
        // get response
        Document responseXML = xmlBuilder.parse(conn.getInputStream());
        XPath xpath = XPathFactory.newInstance().newXPath();

        // get version
        String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML,
                XPathConstants.NODE)).getNodeValue();
        NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML,
                XPathConstants.NODESET);
        Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            repoFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET);
        Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength());
        for (int i = 0; i < nl.getLength(); i++)
            shareFiles.put(nl.item(i).getTextContent(),
                    "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue()));
        String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE))
                .getNodeValue();
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion,
                shareLatestVersion, repoFiles, shareFiles, motd);
    } catch (Exception e) {
        return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "",
                new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), "");
    }
}