In my web application, I have the following code:
if( context == null )
throw new WMSException( "Missing session context." );
String path = context.getRealPath("");
if( path == null )
throw new WMSException( "Missing context real path." );
WebSocket ws = new WebSocket();
String sep = "/";
int where = path.lastIndexOf( sep );
if( where < 0 ){
sep = "\\";
where = path.lastIndexOf( sep );
}
path = path.substring( 0, where );
where = path.lastIndexOf( sep );
path = path.substring( 0, where ) + "/conf/wms";
if( firstTime ){
firstTime = false;
System.out.println( "Getting configuration from " + path );
}
File docFile = new File(path, "socket.xml");
System.out.println( "Name " + docFile.getName() );
System.out.println( "Path " + docFile.getPath() );
In tomcat 6, because of how getRealPath seems to work, I get the following:
/usr/share/tomcat6/conf/wms/socket.xml
In tomcat 8, I get the following, for the same war file:
/opt/tomcat8/webapps/conf/wms/socket.xml
Why the difference in how getRealPath works and how do I fix?
Ok, the problem was solved by noting that Tomcat6 did not put a "/" at the end but Tomcat8 does. So my new code fixes it: LOGGER.info( "Get socket for client: " + client );
if( context == null )
throw new WMSException( "Missing session context." );
String path = context.getRealPath("");
if( path == null )
throw new WMSException( "Missing context real path." );
LOGGER.info( "Path 1 '" + path + "'");
WebSocket ws = new WebSocket();
String sep = "/";
int where = path.lastIndexOf( sep );
if( where < 0 ){
sep = "\\";
where = path.lastIndexOf( sep );
}
String newPath = path.substring( 0, where );
if( newPath.equals(path.substring(0, path.length() - 1 )))
{
where = newPath.lastIndexOf( sep );
path = newPath.substring( 0, where );
LOGGER.info( "Path 2a '" + path + "'");
}
else
path = newPath;
LOGGER.info( "Path 2 '" + path + "'");
where = path.lastIndexOf( sep );
path = path.substring( 0, where ) + "/conf/wms";
LOGGER.info( "Path 3 '" + path + "'");
if( firstTime ){
firstTime = false;
LOGGER.info( "Getting configuration from " + path );
}
LOGGER.info( "Path 4 '" + path + "'");
File docFile = new File(path, "socket.xml");
LOGGER.info( "Name '" + docFile.getName() + "';Path '" + docFile.getPath() + "'");
The key was the if( newPath.equals(path.substring(0, path.length() - 1 )))
if section. Obviously, it could be solved in other ways. Also, this issue is implied in quite a few places online, I just missed the connection with regards to "/" at the end of the path, so it could not up the directory tree correctly.
There was no easy way to get the tomcat home directory ( where we have "conf" directory ), so this was how we did it. Not wishing to change things, just added that section of code to make it work.
There are other ways of solving it that I saw online.