How to make Java class to initialize another class, and execute static java code block conditionally

38 Views Asked by At

I am using WireMock and managed to configure it to use SSL in JUnit 4 tests and disable throwing error if the hostname doesn't match the WireMock self signed certificate with CN=Tom Akehurst.

The code block I added to the JUnit test class:

    static {
        //for localhost testing only
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(newJavaKeyword javax.net.ssl.HostnameVerifier() {
            public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
                if (hostname.equals("localhost")) {
                    return true;
                }
                return false;
            }
        });
    }

Note: replace newJavaKeyword with new as it is not posting without doing that.

The following is the error thrown if the above code is not added:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found

Now, I need to move with testing from my local to the server, and I still need to use WireMock and all the configured JSON mappings. This time, the test cases will run from the main process not from JUnit, so I need to add the flag disableVerifyLocalHost to be passed to say class A which will initialize class B. In class B, I want to run the above static code block only if the the flag disableVerifyLocalHost is true.

I think I can put the code block above in a normal public method but I guess the purpose of the static code block is to ensure the code will run only once.

My understanding is the the static code block will run very early, so I need to ensure the flag disableVerifyLocalHost has been initialized before running the static code block above. Also, I think the flag disableVerifyLocalHost must be static as well.

Following is how I think this should be implemented, but not sure:

public class A {

   private static boolean disableVerifyLocalHost = false;
   public static setDisableVerifyLocalHost(...) {...}
   public static boolean getDisableVerifyLocalHost(.) {...}
   
   public callClassB() {
       B classB = new B()
   }
}


public class B {

    static {
        //for localhost testing only
        if (A.getDisableVerifyLocalHost()) {
            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(newJavaKeyword javax.net.ssl.HostnameVerifier() {
                public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
                    if (hostname.equals("localhost")) {
                        return true;
                    }
                    return false;
                }
            });
        }
    }
}

My question is how to ensure dependency between the code to initialize the flag disableVerifyLocalHost and the code to disable checking the hostname localhost? Or if you have a better suggestion, please let me know.

0

There are 0 best solutions below