Created
November 2, 2015 01:25
-
-
Save devcsrj/8c44193c510d4fb1cff3 to your computer and use it in GitHub Desktop.
Get server endpoint via ServletContextListener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.lang.management.ManagementFactory; | |
| import java.net.InetAddress; | |
| import java.net.UnknownHostException; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import java.util.Set; | |
| import javax.management.AttributeNotFoundException; | |
| import javax.management.InstanceNotFoundException; | |
| import javax.management.MBeanException; | |
| import javax.management.MBeanServer; | |
| import javax.management.MalformedObjectNameException; | |
| import javax.management.ObjectName; | |
| import javax.management.Query; | |
| import javax.management.ReflectionException; | |
| import javax.servlet.ServletContextEvent; | |
| import javax.servlet.ServletContextListener; | |
| /** | |
| * Taken from {@link http://stackoverflow.com/questions/3867197/get-the-server-port-number-from-tomcat-with-out-a-request} | |
| */ | |
| public class ApplicationStartupListener implements ServletContextListener { | |
| @Override | |
| public void contextInitialized( ServletContextEvent sce ) { | |
| List<String> endpoints = getEndpoints(); | |
| System.out.println( endpoints ); | |
| // prints [https://127.0.1.1:8443, http://127.0.1.1:8080] | |
| } | |
| @Override | |
| public void contextDestroyed( ServletContextEvent sce ) { | |
| } | |
| private List<String> getEndPoints() { | |
| try { | |
| MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); | |
| Set<ObjectName> objs = mbs.queryNames( new ObjectName( "*:type=Connector,*" ), | |
| Query.match( Query.attr( "protocol" ), Query.value( "HTTP/1.1" ) ) ); | |
| String hostname = InetAddress.getLocalHost().getHostName(); | |
| InetAddress[] addresses = InetAddress.getAllByName( hostname ); | |
| ArrayList<String> endPoints = new ArrayList<>(); | |
| for ( ObjectName obj : objs ) { | |
| String scheme = mbs.getAttribute( obj, "scheme" ).toString(); | |
| String port = obj.getKeyProperty( "port" ); | |
| for ( InetAddress addr : addresses ) { | |
| String host = addr.getHostAddress(); | |
| String ep = scheme + "://" + host + ":" + port; | |
| endPoints.add( ep ); | |
| } | |
| } | |
| return endPoints; | |
| } catch ( MalformedObjectNameException | UnknownHostException | MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException ex ) { | |
| ex.printStackTrace(); | |
| return new ArrayList<>(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment