Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

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

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory./*from w  w  w. j  a va2 s.  com*/
 * 
 * @return SSL Context
 * @throws CertificateStoreException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws CertificateStoreException {
    try {
        loadKeyStore();
        KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509");
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

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

        return sslContext;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyStoreException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyManagementException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    }
}

From source file:org.opennms.protocols.vmware.VmwareConfigBuilder.java

public static void main(String[] args) throws ParseException {
    String hostname = null;/*from w w  w . ja  v  a  2s. c  om*/
    String username = null;
    String password = null;
    String rrdRepository = null;

    final Options options = new Options();

    options.addOption("rrdRepository", true,
            "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();

    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    if (cmd.hasOption("rrdRepository")) {
        rrdRepository = cmd.getOptionValue("rrdRepository");
    } else {
        rrdRepository = "/opt/opennms/share/rrd/snmp/";
    }

    TrustManager[] trustAllCerts = new TrustManager[1];

    trustAllCerts[0] = new TrustAllManager();

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    VmwareConfigBuilder vmwareConfigBuilder;

    vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);

    try {
        vmwareConfigBuilder.generateData(rrdRepository);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory/*from  w ww.ja  v a  2s  .  c o m*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                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() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:TestHTTPSource.java

public void doTestHttps(String protocol) throws Exception {
    Type listType = new TypeToken<List<JSONEvent>>() {
    }.getType();//w  w  w . ja va 2  s.co m
    List<JSONEvent> events = Lists.newArrayList();
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        Map<String, String> input = Maps.newHashMap();
        for (int j = 0; j < 10; j++) {
            input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i));
        }
        input.put("MsgNum", String.valueOf(i));
        JSONEvent e = new JSONEvent();
        e.setHeaders(input);
        e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8"));
        events.add(e);
    }
    Gson gson = new Gson();
    String json = gson.toJson(events, listType);
    HttpsURLConnection httpsURLConnection = null;
    try {
        TrustManager[] trustAllCerts = { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                // noop
            }

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

        SSLContext sc = null;
        javax.net.ssl.SSLSocketFactory factory = null;
        if (System.getProperty("java.vendor").contains("IBM")) {
            sc = SSLContext.getInstance("SSL_TLS");
        } else {
            sc = SSLContext.getInstance("SSL");
        }

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        sc.init(null, trustAllCerts, new SecureRandom());

        if (protocol != null) {
            factory = new DisabledProtocolsSocketFactory(sc.getSocketFactory(), protocol);
        } else {
            factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(factory);
        HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        URL sslUrl = new URL("https://0.0.0.0:" + sslPort);
        httpsURLConnection = (HttpsURLConnection) sslUrl.openConnection();
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setDoOutput(true);
        httpsURLConnection.setRequestMethod("POST");
        httpsURLConnection.getOutputStream().write(json.getBytes());

        int statusCode = httpsURLConnection.getResponseCode();
        Assert.assertEquals(200, statusCode);

        Transaction transaction = channel.getTransaction();
        transaction.begin();
        for (int i = 0; i < 10; i++) {
            Event e = channel.take();
            Assert.assertNotNull(e);
            Assert.assertEquals(String.valueOf(i), e.getHeaders().get("MsgNum"));
        }

        transaction.commit();
        transaction.close();
    } finally {
        httpsURLConnection.disconnect();
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void downloadInstaller(String downloadUrl) {
    String fileName = getInstallerName(downloadUrl);
    InputStream in;/*from  w  ww.  j  av  a  2 s.co m*/

    // 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(X509Certificate[] certs, String authType) {
            // here is the place to check client certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // here is the place to check server certs and throw an
            // exception if certs are wrong. When there is nothing all certs
            // accepted.
        }
    } };
    // Install the all-trusting trust manager
    try {
        final 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) {
                // Here is the palce to check host name against to
                // certificate owner
                return true;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
    }

    try {
        URL url = new URL(downloadUrl);
        in = url.openStream();
        FileOutputStream fos = new FileOutputStream(new File(fileName));

        int length = -1;
        ProgressMonitorInputStream pmis;
        pmis = new ProgressMonitorInputStream(null,
                "Downloading new version of installer for NBIA Data Retriever...", in);

        ProgressMonitor monitor = pmis.getProgressMonitor();
        monitor.setMillisToPopup(0);
        monitor.setMinimum(0);
        monitor.setMaximum((int) 200000000); // The actual size is much
        // smaller,
        // but we have no way to
        // know
        // the actual size so picked
        // this big number

        byte[] buffer = new byte[1024];// buffer for portion of data from
        // connection

        while ((length = pmis.read(buffer)) > 0) {
            fos.write(buffer, 0, length);
        }
        pmis.close();
        fos.flush();
        fos.close();
        in.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.codice.ddf.itests.common.cometd.CometDClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/* w w  w  . j a va  2s.  c o  m*/
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

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

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:org.jenkinsci.plugins.codefresh.CFApi.java

private void secureContext(boolean selfSignedCert) {
    this.https = true;
    trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*  ww  w  .  j av a2  s  .co  m*/

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        this.sf = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(this.sf);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
    if (selfSignedCert) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                return true;
            }
        });
    }
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory./* w w w.j  a v a2s . c  o  m*/
 * 
 * @return SSL Context
 * @throws ESCertificateException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws ESCertificateException {
    try {
        loadKeyStore();
        final KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        trustManagerFactory.init(keyStore);
        final SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

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

        return sslContext;
    } catch (final NoSuchAlgorithmException e) {
        throw new ESCertificateException(Messages.KeyStoreManager_29, e);
    } catch (final UnrecoverableKeyException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyStoreException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyManagementException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    }
}

From source file:com.arm.connector.bridge.transport.HttpTransport.java

@SuppressWarnings("empty-statement")
private String doHTTP(String verb, String url_str, String username, String password, String data,
        String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL,
        boolean use_api_token, String api_token) {
    String result = "";
    String line = "";
    URLConnection connection = null;
    SSLContext sc = null;// w  w  w. ja  v a 2s  . c o  m

    try {
        URL url = new URL(url_str);

        // Http Connection and verb
        if (doSSL) {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            // Install the all-trusting trust manager
            try {
                sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // do nothing
                ;
            }

            // open the SSL connction
            connection = (HttpsURLConnection) (url.openConnection());
            ((HttpsURLConnection) connection).setRequestMethod(verb);
            ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } else {
            connection = (HttpURLConnection) (url.openConnection());
            ((HttpURLConnection) connection).setRequestMethod(verb);
        }

        connection.setDoInput(doInput);
        if (doOutput && data != null && data.length() > 0) {
            connection.setDoOutput(doOutput);
        } else {
            connection.setDoOutput(false);
        }

        // enable basic auth if requested
        if (use_api_token == false && username != null && username.length() > 0 && password != null
                && password.length() > 0) {
            String encoding = Base64.encodeBase64String((username + ":" + password).getBytes());
            connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding);
            //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding);
        }

        // enable ApiTokenAuth auth if requested
        if (use_api_token == true && api_token != null && api_token.length() > 0) {
            // use qualification for the authorization header...
            connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token);
            //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token);

            // Always reset to the established default
            this.resetAuthorizationQualifier();
        }

        // ETag support if requested
        if (this.m_etag_value != null && this.m_etag_value.length() > 0) {
            // set the ETag header value
            connection.setRequestProperty("ETag", this.m_etag_value);
            //this.errorLogger().info("ETag Value: " + this.m_etag_value);

            // Always reset to the established default
            this.resetETagValue();
        }

        // If-Match support if requested
        if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) {
            // set the If-Match header value
            connection.setRequestProperty("If-Match", this.m_if_match_header_value);
            //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value);

            // Always reset to the established default
            this.resetIfMatchValue();
        }

        // specify content type if requested
        if (content_type != null && content_type.length() > 0) {
            connection.setRequestProperty("Content-Type", content_type);
            connection.setRequestProperty("Accept", "*/*");
        }

        // add Connection: keep-alive (does not work...)
        //connection.setRequestProperty("Connection", "keep-alive");

        // special gorp for HTTP DELETE
        if (verb != null && verb.equalsIgnoreCase("delete")) {
            connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE");
        }

        // specify domain if requested
        if (auth_domain != null && auth_domain.length() > 0) {
            connection.setRequestProperty("Domain", auth_domain);
        }

        // DEBUG dump the headers
        //if (doSSL) 
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); 
        //else
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); 

        // specify data if requested - assumes it properly escaped if necessary
        if (doOutput && data != null && data.length() > 0) {
            try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) {
                out.write(data);
            }
        }

        // setup the output if requested
        if (doInput) {
            try {
                try (InputStream content = (InputStream) connection.getInputStream();
                        BufferedReader in = new BufferedReader(new InputStreamReader(content))) {
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                }
            } catch (java.io.FileNotFoundException ex) {
                this.errorLogger().info("HTTP(" + verb + ") empty response (OK).");
                result = "";
            }
        } else {
            // no result expected
            result = "";
        }

        // save off the HTTP response code...
        if (doSSL)
            this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode());
        else
            this.saveResponseCode(((HttpURLConnection) connection).getResponseCode());

        // DEBUG
        //if (doSSL)
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode());
        //else
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode());
    } catch (IOException ex) {
        this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage());
        result = null;
    }

    // return the result
    return result;
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * /*from w ww .  ja  va2 s . c  o m*/
 */
public Agent(String propFileName) throws Exception {

    //------------
    //-- ??
    //------------

    //???
    AgentProperties.init(propFileName);

    // ?IP????
    getAgentInfo();
    m_log.info(getAgentStr());

    // log4j???
    String log4jFileName = System.getProperty("hinemos.agent.conf.dir") + File.separator + "log4j.properties";
    m_log.info("log4j.properties = " + log4jFileName);
    m_log4jFileName = log4jFileName;

    int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
    int requestTimeout = DEFAULT_REQUEST_TIMEOUT;

    // 
    String proxyHost = DEFAULT_PROXY_HOST;
    int proxyPort = DEFAULT_PROXY_PORT;
    String proxyUser = DEFAULT_PROXY_USER;
    String proxyPassword = DEFAULT_PROXY_PASSWORD;

    // ???hostnameVerifier?HTTPS????
    try {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
                return true;
            }
        };

        // Create the trust manager.
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        class AllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
        }
        javax.net.ssl.TrustManager tm = new AllTrustManager();
        trustAllCerts[0] = tm;
        // Create the SSL context
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        // Create the session context
        javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
        // Initialize the contexts; the session context takes the
        // trust manager.
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        // Use the default socket factory to create the socket for
        // the secure
        // connection
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Set the default host name verifier to enable the connection.
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

    } catch (Throwable e) {
        m_log.warn("hostname verifier (all trust) disable : " + e.getMessage(), e);
    }

    try {
        String strConnect = AgentProperties.getProperty("connect.timeout");
        if (strConnect != null) {
            connectTimeout = Integer.parseInt(strConnect);
        }
        String strRequest = AgentProperties.getProperty("request.timeout");
        if (strRequest != null) {
            requestTimeout = Integer.parseInt(strRequest);
        }
        String strProxyHost = AgentProperties.getProperty("http.proxy.host");
        if (strProxyHost != null) {
            proxyHost = strProxyHost;
        }
        String strProxyPort = AgentProperties.getProperty("http.proxy.port");
        if (strProxyPort != null) {
            proxyPort = Integer.parseInt(strProxyPort);
        }
        String strProxyUser = AgentProperties.getProperty("http.proxy.user");
        if (strProxyUser != null) {
            proxyUser = strProxyUser;
        }
        String strProxyPassword = AgentProperties.getProperty("http.proxy.password");
        if (strProxyPassword != null) {
            proxyPassword = strProxyPassword;
        }
    } catch (Exception e) {
        m_log.warn(e.getMessage());
    }

    if (!"".equals(proxyHost)) {
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", Integer.toString(proxyPort));
        BasicAuth basicAuth = new BasicAuth(proxyUser, proxyPassword);
        Authenticator.setDefault(basicAuth);
        m_log.info("proxy.host=" + System.getProperty("http.proxyHost") + ", proxy.port="
                + System.getProperty("http.proxyPort") + ", proxy.user=" + proxyUser);
    }

    // ?? ${ManagerIP} ?????????????
    // ??PING????????IP????FacilityID??????
    String managerAddress = AgentProperties.getProperty("managerAddress");
    URL url = new URL(managerAddress);
    boolean replacePropFileSuccess = true;
    String errMsg = "";
    if (REPLACE_VALUE_MANAGER_IP.equals((url.getHost()))) {
        try {

            // ???PING?????PING???????
            Map<String, String> discoveryInfoMap = new HashMap<String, String>();
            while (true) {
                m_log.info("waiting for manager connection...");
                String recvMsg = receiveManagerDiscoveryInfo();

                // ????key=value,key=value ??????Map??
                try {
                    discoveryInfoMap.clear();
                    String[] commaSplittedRecvMsgArray = recvMsg.split(",");
                    for (String keyvalueset : commaSplittedRecvMsgArray) {
                        String key = keyvalueset.split("=")[0];
                        String value = keyvalueset.split("=")[1];
                        discoveryInfoMap.put(key, value);
                    }
                } catch (Exception e) {
                    m_log.error("can't parse receive message : " + e.toString());
                    continue;
                }
                if (discoveryInfoMap.containsKey("agentFacilityId")
                        && discoveryInfoMap.containsKey("managerIp")) {
                    break;
                } else {
                    m_log.error("receive message is invalid");
                }
            }
            // Agent.properties?????????????
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "managerAddress";
                String value = url.getProtocol() + "://" + managerIp + ":" + url.getPort() + "/HinemosWS/";
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, managerAddress, value);
                AgentProperties.setProperty(key, value);
            }

            // Agent.properties?ID??????????
            {
                String key = "facilityId";
                String value = discoveryInfoMap.get("agentFacilityId");
                m_log.info("Rewrite property. key : " + key + ", value : " + value);
                PropertiesFileUtil.replacePropertyFile(propFileName, key, "", value);
                AgentProperties.setProperty(key, value);
            }

            // log4j.properties?????Windows??
            {
                String managerIp = discoveryInfoMap.get("managerIp");
                String key = "log4j.appender.syslog.SyslogHost";
                PropertiesFileUtil.replacePropertyFile(log4jFileName, "log4j.appender.syslog.SyslogHost",
                        REPLACE_VALUE_MANAGER_IP, managerIp);
                if (REPLACE_VALUE_MANAGER_IP.equals(AgentProperties.getProperty(key))) {
                    m_log.info("Rewrite property. key : " + key + ", value : " + managerIp);
                    PropertiesFileUtil.replacePropertyFile(log4jFileName, key, REPLACE_VALUE_MANAGER_IP,
                            managerIp);
                }
            }
        } catch (HinemosUnknown e) {
            // ????????????
            errMsg = e.getMessage();
            m_log.warn(errMsg, e);
            replacePropFileSuccess = false;
        } catch (Exception e) {
            m_log.warn(e.getMessage(), e);
            throw e;
        }
    }

    try {
        EndpointManager.init(AgentProperties.getProperty("user"), AgentProperties.getProperty("password"),
                AgentProperties.getProperty("managerAddress"), connectTimeout, requestTimeout);
    } catch (Exception e) {
        m_log.error("EndpointManager.init error : " + e.getMessage(), e);
        m_log.error("current-dir=" + (new File(".")).getAbsoluteFile().getParent());
        throw e;
    }

    if (!replacePropFileSuccess) {
        OutputBasicInfo output = new OutputBasicInfo();
        output.setPluginId("AGT_UPDATE_CONFFILE");
        output.setPriority(PriorityConstant.TYPE_WARNING);
        output.setApplication(MessageConstant.AGENT.getMessage());
        String[] args = { errMsg };
        output.setMessage(MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_MSG.getMessage());
        output.setMessageOrg(
                MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_ORIGMSG.getMessage(args));
        output.setGenerationDate(HinemosTime.getDateInstance().getTime());
        output.setMonitorId("SYS");
        output.setFacilityId(""); // ???
        output.setScopeText(""); // ???
        m_sendQueue.put(output);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            terminate();
            m_log.info("Hinemos agent stopped");
        }
    });
}