How to convert Java code to non-lambda expression?

89 Views Asked by At

I am trying to build (in Eclipse) and use the code in this older thread:

How do I pass the client certificate with HTTP client?

But I am having problems compiling it because this line is causing the compiler to flag an error:

SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(
    MutualHttpsMain.class.getResource(TEST_CLIENT_KEYSTORE_RESOURCE),
    storePassword, 
    keyPassword,
    (aliases, socket) -> aliases.keySet().iterator().next()
).build();

The error is:

error: lambda expressions are not supported in -source 1.7

My understanding is that lambda expressions were not supported in Java/JDK 1.7, so it seems like Eclipse (or Maven) thinks that the compiler is 1.8, but I've gone through my Eclipse configuration and everything appears to be configured for using JDK 1.8, so I don't know why I am still getting the error, so I am wondering: Is it possible to convert that line so it is no longer a lambda expression?

Can someone here help with that?

EDIT: Sorry, I had to correct the text of the error above... the correct error message says 1.7 and not 7.

1

There are 1 best solutions below

0
Nikolas Charalambidis On

You can't compile Java 8 features (lambda expression, method references) with the Java 7 compiler.

Assuming you use the method from the latest version of Apache HttpCore 4.4.16, just implement an instance of the anonymous class PrivateKeyStrategy:

SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(
    MutualHttpsMain.class.getResource(TEST_CLIENT_KEYSTORE_RESOURCE),
    storePassword,
    keyPassword,
    new PrivateKeyStrategy() {
        @Override
        public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
            return aliases.keySet().iterator().next();
        }
    }
).build();

A deprectaion note: If you use the deprecated Apache HttpClient org.apache.http.conn.ssl.SSLContextBuilder, consider moving to Apache HttpCore org.apache.http.ssl.SSLContextBuilder.