As part of some work I have been undertaking to integrate the UK Government Notifications service into Mendix, I needed to be able to make API calls from behind a firewall using a proxy in a Java action.
Due to the lower level Java actions in Mendix run at, proxy settings are not automatically applied, and must be added manually. I wanted to explain how to get the proxy settings from Mendix, and use them a Java action.
I’ve previously explained how to add proxy settings to Mendix, so I assume this step has been completed.
In a Java action, we need to get these from the HttpConfiguration singleton.
import com.mendix.http.HttpConfiguration; import com.mendix.http.IHttpConfiguration; import com.mendix.http.IProxyConfiguration; IHttpConfiguration httpconf = com.mendix.http.HttpConfiguration.getInstance(); IProxyConfiguration proxyconf = httpconf.getProxyConfiguration().orElse(null);
We can now check if we have a proxy configuration set, if we don’t proxyconf
will be null
.
The username and password for the proxy can be retrieved using the getUser()
and getPassword()
methods.
String username = proxyconf.getUser().orElse(null); String password = proxyconf.getPassword().orElse(null);
If they are present we can build a Java Authenticator object and set it as the default authenticator.
import java.net.Authenticator; import java.net.PasswordAuthentication; if (username != null && password != null) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(username, password.toCharArray())); } }; Authenticator.setDefault(authenticator); }
Next we need to create the Proxy object. We need to get the host and port of our proxy server from Mendix using the getHost()
and getPort()
methods.
import java.net.InetSocketAddress; import java.net.Proxy; InetSocketAddress proxyLocation = new InetSocketAddress(proxyconf.getHost(), proxyconf.getPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
The proxy
can be used for Java network actions.
An example of using this would be the UK Government Notifications client. It has a second optional paramater in it’s constructor for a Proxy.
client = new NotificationClient('APIKey', proxy);