Skip to content

Instantly share code, notes, and snippets.

@devcsrj
Created November 2, 2015 01:25
Show Gist options
  • Save devcsrj/8c44193c510d4fb1cff3 to your computer and use it in GitHub Desktop.
Save devcsrj/8c44193c510d4fb1cff3 to your computer and use it in GitHub Desktop.

Revisions

  1. Reijhanniel Jearl Campos created this gist Nov 2, 2015.
    60 changes: 60 additions & 0 deletions ApplicationStartupListener.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    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<>();
    }
    }

    }