DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jammy has posted 1 posts at DZone. View Full User Profile

Get Tomcat Port Number from Java Code line

12.02.2012
| 2726 views |
  • submit to reddit
public static Integer getTomcatPortFromConfigXml(File serverXml) {
 
  Integer port;
  try {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(serverXml);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("/Server/Service[@name='Catalina']/Connector[count(@scheme)=0]/@port[1]");
    String result = (String) expr.evaluate(doc, XPathConstants.STRING);
    port =  result != null && result.length() > 0 ? Integer.valueOf(result) : null;
  } catch (Exception e) {
    port = null;
  }
  return port;
}

This code reads the port number defined in Server.XML of Tomcat, the code source is http://www.asjava.com/tomcat/how-to-get-tomcat-port-number-in-java/

    Tags: