initial commit of BRouter Version 0.98

This commit is contained in:
Arndt Brenschede 2014-01-18 15:29:05 +01:00
parent e4ae2b37d3
commit 91e62f1164
120 changed files with 15382 additions and 0 deletions

View file

@ -0,0 +1,132 @@
package btools.server;
import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import btools.router.OsmNodeNamed;
import btools.router.RoutingEngine;
import btools.router.RoutingContext;
import btools.router.OsmTrack;
public class BRouter
{
public static void main(String[] args) throws Exception
{
if ( args.length == 2) // cgi-input-mode
{
try
{
String queryString = args[1];
int sepIdx = queryString.indexOf( '=' );
if ( sepIdx >= 0 ) queryString = queryString.substring( sepIdx + 1 );
queryString = URLDecoder.decode( queryString, "ISO-8859-1" );
int ntokens = 1;
for( int ic = 0; ic<queryString.length(); ic++ )
{
if ( queryString.charAt(ic) == '_' ) ntokens++;
}
String[] a2 = new String[ntokens + 1];
int idx = 1;
int pos = 0;
for(;;)
{
int p = queryString.indexOf( '_', pos );
if ( p < 0 )
{
a2[idx++] = queryString.substring( pos );
break;
}
a2[idx++] = queryString.substring( pos, p );
pos = p+1;
}
// cgi-header
System.out.println( "Content-type: text/plain" );
System.out.println();
OsmNodeNamed from = readPosition( a2, 1, "from" );
OsmNodeNamed to = readPosition( a2, 3, "to" );
int airDistance = from.calcDistance( to );
String airDistanceLimit = System.getProperty( "airDistanceLimit" );
if ( airDistanceLimit != null )
{
int maxKm = Integer.parseInt( airDistanceLimit );
if ( airDistance > maxKm * 1000 )
{
System.out.println( "airDistance " + (airDistance/1000) + "km exceeds limit for online router (" + maxKm + "km)" );
return;
}
}
long maxRunningTime = 60000; // the cgi gets a 1 Minute timeout
String sMaxRunningTime = System.getProperty( "maxRunningTime" );
if ( sMaxRunningTime != null )
{
maxRunningTime = Integer.parseInt( sMaxRunningTime ) * 1000;
}
long startTime = System.currentTimeMillis();
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
wplist.add( from );
wplist.add( to );
RoutingEngine re = new RoutingEngine( null, null, args[0], wplist, readRoutingContext(a2) );
re.doRun( maxRunningTime );
if ( re.getErrorMessage() != null )
{
System.out.println( re.getErrorMessage() );
}
}
catch( Throwable e )
{
System.out.println( "unexpected exception: " + e );
}
System.exit(0);
}
System.out.println("BRouter 0.98 / 12012014 / abrensch");
if ( args.length < 6 )
{
System.out.println("Find routes in an OSM map");
System.out.println("usage: java -jar brouter.jar <segmentdir> <lon-from> <lat-from> <lon-to> <lat-to> <profile>");
return;
}
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
wplist.add( readPosition( args, 1, "from" ) );
wplist.add( readPosition( args, 3, "to" ) );
RoutingEngine re = new RoutingEngine( "mytrack", "mylog", args[0], wplist, readRoutingContext(args) );
re.doRun( 0 );
if ( re.getErrorMessage() != null )
{
System.out.println( re.getErrorMessage() );
}
}
private static OsmNodeNamed readPosition( String[] args, int idx, String name )
{
OsmNodeNamed n = new OsmNodeNamed();
n.name = name;
n.ilon = (int)( ( Double.parseDouble( args[idx ] ) + 180. ) *1000000. + 0.5);
n.ilat = (int)( ( Double.parseDouble( args[idx+1] ) + 90. ) *1000000. + 0.5);
return n;
}
private static RoutingContext readRoutingContext( String[] args )
{
RoutingContext c = new RoutingContext();
if ( args.length > 5 )
{
c.localFunction = args[5];
if ( args.length > 6 )
{
c.setAlternativeIdx( Integer.parseInt( args[6] ) );
}
}
return c;
}
}

View file

@ -0,0 +1,111 @@
package btools.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
public class CgiUpload
{
public static void main(String[] args)
{
try
{
_main(args);
}
catch( Exception e )
{
System.out.println( "unexpected exception: " + e );
}
}
private static void _main(String[] args) throws Exception
{
String htmlTemplate = args[0];
String customeProfileDir = args[1];
String id = "" + System.currentTimeMillis();
// cgi-header
System.out.println( "Content-type: text/html" );
System.out.println();
// write the post message to a file
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream( customeProfileDir + "/" + id + ".brf" ) ) );
BufferedReader ir = new BufferedReader( new InputStreamReader( System.in ) );
String postData = ir.readLine();
String[] coordValues = new String[4];
if( postData != null )
{
int coordsIdx = postData.indexOf( "coords=" );
if ( coordsIdx >= 0)
{
int coordsEnd = postData.indexOf( '&' );
if ( coordsEnd >= 0)
{
String coordsString = postData.substring( coordsIdx + 7, coordsEnd );
postData = postData.substring( coordsEnd+1 );
int pos = 0;
for(int idx=0; idx<4; idx++)
{
int p = coordsString.indexOf( '_', pos );
coordValues[idx] = coordsString.substring( pos, p );
pos = p+1;
}
}
}
int sepIdx = postData.indexOf( '=' );
if ( sepIdx >= 0 ) postData = postData.substring( sepIdx + 1 );
postData = URLDecoder.decode( postData, "ISO-8859-1" );
bw.write( postData );
}
bw.close();
// echo the template with a custom select item
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream( htmlTemplate ) ) );
for(;;)
{
String line = br.readLine();
if ( line == null ) break;
if ( line.indexOf( "<!-- sample profiles -->" ) >= 0 )
{
line = " <option value=\"../customprofiles/" + id + "\">custom</option>";
}
else if ( line.indexOf( "paste your profile here" ) >= 0 )
{
System.out.println( "<textarea type=\"text\" name=\"profile\" rows=30 cols=100>" );
System.out.println( postData );
line = "</textarea>";
}
else
{
line = replaceCoord( line, "lonfrom", coordValues[0] );
line = replaceCoord( line, "latfrom", coordValues[1] );
line = replaceCoord( line, "lonto", coordValues[2] );
line = replaceCoord( line, "latto", coordValues[3] );
}
System.out.println( line );
}
br.close();
}
private static String replaceCoord( String line, String name, String value )
{
String inputTag = "<td><input type=\"text\" name=\"" + name + "\"";
if ( line.indexOf( inputTag ) >= 0 )
{
return inputTag + " value=\"" + value + "\"></td>";
}
return line;
}
}

View file

@ -0,0 +1,267 @@
package btools.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import btools.router.OsmNodeNamed;
import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.router.RoutingEngine;
import btools.server.request.RequestHandler;
import btools.server.request.ServerHandler;
import btools.server.request.YoursHandler;
public class RouteServer extends Thread
{
public ServiceContext serviceContext;
public short port = 17777;
private boolean serverStopped = false;
private ServerSocket serverSocket = null;
public void close()
{
serverStopped = true;
try
{
ServerSocket ss = serverSocket;
serverSocket = null;
ss.close();
}
catch( Throwable t ) {}
}
private void killOtherServer() throws Exception
{
Socket socket = new Socket( "localhost", port );
BufferedWriter bw = null;
try
{
bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
bw.write( "EXIT\n" );
}
finally
{
bw.close();
socket.close();
}
}
public void run()
{
// first go an kill any other server on that port
for(;;)
{
try
{
killOtherServer();
System.out.println( "killed, waiting" );
try { Thread.sleep( 3000 ); } catch( InterruptedException ie ) {}
}
catch( Throwable t ) {
System.out.println( "not killed: " + t );
break;
}
}
try
{
serverSocket = new ServerSocket(port);
for(;;)
{
System.out.println("RouteServer accepting connections..");
Socket clientSocket = serverSocket.accept();
if ( !serveRequest( clientSocket ) ) break;
}
}
catch( Throwable e )
{
System.out.println("RouteServer main loop got exception (exiting): "+e);
if ( serverSocket != null )
{
try { serverSocket.close(); } catch( Throwable t ) {}
}
System.exit(0);
}
}
public boolean serveRequest( Socket clientSocket )
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader( new InputStreamReader( clientSocket.getInputStream() ) );
bw = new BufferedWriter( new OutputStreamWriter( clientSocket.getOutputStream() ) );
// we just read the first line
String getline = br.readLine();
if ( getline == null || getline.startsWith( "EXIT") )
{
throw new RuntimeException( "socketExitRequest" );
}
if ( getline.startsWith("GET /favicon.ico") )
{
return true;
}
String url = getline.split(" ")[1];
HashMap<String,String> params = getUrlParams(url);
long maxRunningTime = getMaxRunningTime();
long startTime = System.currentTimeMillis();
RequestHandler handler;
if ( params.containsKey( "lonlats" ) && params.containsKey( "profile" ) )
{
handler = new ServerHandler( serviceContext, params );
}
else
{
handler = new YoursHandler( serviceContext, params );
}
RoutingContext rc = handler.readRoutingContext();
List<OsmNodeNamed> wplist = handler.readWayPointList();
RoutingEngine cr = new RoutingEngine( null, null, serviceContext.segmentDir, wplist, rc );
cr.quite = true;
cr.doRun( maxRunningTime );
// http-header
bw.write( "HTTP/1.1 200 OK\n" );
bw.write( "Connection: close\n" );
bw.write( "Content-Type: text/xml; charset=utf-8\n" );
bw.write( "Access-Control-Allow-Origin: *\n" );
bw.write( "\n" );
if ( cr.getErrorMessage() != null )
{
bw.write( cr.getErrorMessage() );
bw.write( "\n" );
}
else
{
OsmTrack track = cr.getFoundTrack();
if ( track != null )
{
bw.write( handler.formatTrack(track) );
}
}
bw.flush();
}
catch (Throwable e)
{
if ( "socketExitRequest".equals( e.getMessage() ) )
{
return false;
}
System.out.println("RouteServer got exception (will continue): "+e);
e.printStackTrace();
}
finally
{
if ( br != null ) try { br.close(); } catch( Exception e ) {}
if ( bw != null ) try { bw.close(); } catch( Exception e ) {}
}
return true;
}
public static void main(String[] args) throws Exception
{
System.out.println("BRouter 0.98 / 12012014 / abrensch");
if ( args.length != 3 )
{
System.out.println("serve YOURS protocol for BRouter");
System.out.println("usage: java RouteServer <segmentdir> <profile-list> <port>");
System.out.println("");
System.out.println("serve BRouter protocol");
System.out.println("usage: java RouteServer <segmentdir> <profiledir> <port>");
return;
}
ServiceContext serviceContext = new ServiceContext();
serviceContext.segmentDir = args[0];
File profileMapOrDir = new File( args[1] );
if ( profileMapOrDir.isDirectory() )
{
System.setProperty( "profileBaseDir", args[1] );
}
else
{
serviceContext.profileMap = loadProfileMap( profileMapOrDir );
}
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[2]));
for (;;)
{
Socket clientSocket = serverSocket.accept();
RouteServer server = new RouteServer();
server.serviceContext = serviceContext;
server.serveRequest( clientSocket );
}
}
private static Map<String,String> loadProfileMap( File file ) throws IOException
{
Map<String,String> profileMap = new HashMap<String,String>();
BufferedReader pr = new BufferedReader( new InputStreamReader( new FileInputStream( file ) ) );
for(;;)
{
String key = pr.readLine();
if ( key == null ) break;
key = key.trim();
if ( key.length() == 0 ) continue;
String value = pr.readLine();
value = value.trim();
profileMap.put( key, value );
}
return profileMap;
}
private static HashMap<String,String> getUrlParams( String url )
{
HashMap<String,String> params = new HashMap<String,String>();
StringTokenizer tk = new StringTokenizer( url, "?&" );
while( tk.hasMoreTokens() )
{
String t = tk.nextToken();
StringTokenizer tk2 = new StringTokenizer( t, "=" );
if ( tk2.hasMoreTokens() )
{
String key = tk2.nextToken();
if ( tk2.hasMoreTokens() )
{
String value = tk2.nextToken();
params.put( key, value );
}
}
}
return params;
}
private static long getMaxRunningTime() {
long maxRunningTime = 60000;
String sMaxRunningTime = System.getProperty( "maxRunningTime" );
if ( sMaxRunningTime != null )
{
maxRunningTime = Integer.parseInt( sMaxRunningTime ) * 1000;
}
return maxRunningTime;
}
}

View file

@ -0,0 +1,16 @@
package btools.server;
import java.util.List;
import java.util.Map;
import btools.router.OsmNodeNamed;
/**
* Environment configuration that is initialized at server/service startup
*/
public class ServiceContext
{
public String segmentDir;
public Map<String,String> profileMap = null;
public List<OsmNodeNamed> nogoList;
}

View file

@ -0,0 +1,28 @@
package btools.server.request;
import java.util.HashMap;
import java.util.List;
import btools.router.OsmNodeNamed;
import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.server.ServiceContext;
public abstract class RequestHandler
{
protected ServiceContext serviceContext;
protected HashMap<String,String> params;
public RequestHandler( ServiceContext serviceContext, HashMap<String,String> params )
{
this.serviceContext = serviceContext;
this.params = params;
}
public abstract RoutingContext readRoutingContext();
public abstract List<OsmNodeNamed> readWayPointList();
public abstract String formatTrack(OsmTrack track);
}

View file

@ -0,0 +1,149 @@
package btools.server.request;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import btools.router.OsmNodeNamed;
import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.server.ServiceContext;
/**
* URL query parameter handler for web and standalone server. Supports all
* BRouter features without restrictions.
*
* Parameters:
*
* lonlats = lon,lat|... (unlimited list of lon,lat waypoints separated by |)
* nogos = lon,lat,radius|... (optional, radius in meters)
* profile = profile file name without .brf
* alternativeidx = [0|1|2|3] (optional, default 0)
* format = [kml|gpx] (optional, default gpx)
*
* Example URLs:
* http://localhost:17777/brouter?lonlats=8.799297,49.565883|8.811764,49.563606&nogos=&profile=trekking&alternativeidx=0&format=gpx
* http://localhost:17777/brouter?lonlats=1.1,1.2|2.1,2.2|3.1,3.2|4.1,4.2&nogos=-1.1,-1.2,1|-2.1,-2.2,2&profile=shortest&alternativeidx=1&format=kml
*
*/
public class ServerHandler extends RequestHandler {
public ServerHandler( ServiceContext serviceContext, HashMap<String, String> params )
{
super( serviceContext, params );
}
@Override
public RoutingContext readRoutingContext()
{
RoutingContext rc = new RoutingContext();
rc.localFunction = params.get( "profile" );
rc.setAlternativeIdx(Integer.parseInt(params.get( "alternativeidx" )));
List<OsmNodeNamed> nogoList = readNogoList();
if ( nogoList != null )
{
rc.prepareNogoPoints( nogoList );
rc.nogopoints = nogoList;
}
return rc;
}
@Override
public List<OsmNodeNamed> readWayPointList()
{
// lon,lat|...
String lonLats = params.get( "lonlats" );
if (lonLats == null) throw new IllegalArgumentException( "lonlats parameter not set" );
String[] coords = lonLats.split("\\|");
if (coords.length < 2) throw new IllegalArgumentException( "we need two lat/lon points at least!" );
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
for (int i = 0; i < coords.length; i++)
{
String[] lonLat = coords[i].split(",");
wplist.add( readPosition( lonLat[0], lonLat[1], "via" + i ) );
}
wplist.get(0).name = "from";
wplist.get(wplist.size()-1).name = "to";
return wplist;
}
@Override
public String formatTrack(OsmTrack track)
{
String result;
// optional, may be null
String format = params.get( "format" );
if (format == null || "gpx".equals(format))
{
result = track.formatAsGpx();
}
else if ("kml".equals(format))
{
result = track.formatAsKml();
}
else {
System.out.println("unknown track format '" + format + "', using default");
result = track.formatAsGpx();
}
return result;
}
private static OsmNodeNamed readPosition( String vlon, String vlat, String name )
{
if ( vlon == null ) throw new IllegalArgumentException( "lon " + name + " not found in input" );
if ( vlat == null ) throw new IllegalArgumentException( "lat " + name + " not found in input" );
return readPosition(Double.parseDouble( vlon ), Double.parseDouble( vlat ), name);
}
private static OsmNodeNamed readPosition( double lon, double lat, String name )
{
OsmNodeNamed n = new OsmNodeNamed();
n.name = name;
n.ilon = (int)( ( lon + 180. ) *1000000. + 0.5);
n.ilat = (int)( ( lat + 90. ) *1000000. + 0.5);
return n;
}
private List<OsmNodeNamed> readNogoList()
{
// lon,lat,radius|...
String nogos = params.get( "nogos" );
if ( nogos == null ) return null;
String[] lonLatRadList = nogos.split("\\|");
List<OsmNodeNamed> nogoList = new ArrayList<OsmNodeNamed>();
for (int i = 0; i < lonLatRadList.length; i++)
{
String[] lonLatRad = lonLatRadList[i].split(",");
nogoList.add(readNogo(lonLatRad[0], lonLatRad[1], lonLatRad[2]));
}
return nogoList;
}
private static OsmNodeNamed readNogo( String lon, String lat, String radius )
{
return readNogo(Double.parseDouble( lon ), Double.parseDouble( lat ), Integer.parseInt( radius ) );
}
private static OsmNodeNamed readNogo( double lon, double lat, int radius )
{
OsmNodeNamed n = new OsmNodeNamed();
n.name = "nogo" + radius;
n.ilon = (int)( ( lon + 180. ) *1000000. + 0.5);
n.ilat = (int)( ( lat + 90. ) *1000000. + 0.5);
n.isNogo = true;
return n;
}
}

View file

@ -0,0 +1,69 @@
package btools.server.request;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import btools.router.OsmNodeNamed;
import btools.router.OsmTrack;
import btools.router.RoutingContext;
import btools.server.ServiceContext;
public class YoursHandler extends RequestHandler {
public YoursHandler( ServiceContext serviceContext, HashMap<String,String> params )
{
super(serviceContext, params);
}
@Override
public RoutingContext readRoutingContext()
{
RoutingContext rc = new RoutingContext();
String profile_key = params.get( "v" ) + " " + params.get( "fast" );
if (serviceContext.profileMap == null) throw new IllegalArgumentException( "no profile map loaded" );
String profile_path = serviceContext.profileMap.get( profile_key );
if ( profile_path == null ) profile_path = serviceContext.profileMap.get( "default" );
if ( profile_path == null ) throw new IllegalArgumentException( "no profile for key: " + profile_key );
rc.localFunction = profile_path;
List<OsmNodeNamed> nogoList = serviceContext.nogoList;
if ( nogoList != null )
{
rc.prepareNogoPoints( nogoList );
rc.nogopoints = nogoList;
}
return rc;
}
@Override
public List<OsmNodeNamed> readWayPointList()
{
List<OsmNodeNamed> wplist = new ArrayList<OsmNodeNamed>();
wplist.add( readPosition( params, "flon", "flat", "from" ) );
wplist.add( readPosition( params, "tlon", "tlat", "to" ) );
return wplist;
}
@Override
public String formatTrack(OsmTrack track)
{
return track.formatAsKml();
}
private static OsmNodeNamed readPosition( HashMap<String,String> params, String plon, String plat, String name )
{
String vlon = params.get( plon );
if ( vlon == null ) throw new IllegalArgumentException( "param " + plon + " bot found in input" );
String vlat = params.get( plat );
if ( vlat == null ) throw new IllegalArgumentException( "param " + plat + " bot found in input" );
OsmNodeNamed n = new OsmNodeNamed();
n.name = name;
n.ilon = (int)( ( Double.parseDouble( vlon ) + 180. ) *1000000. + 0.5);
n.ilat = (int)( ( Double.parseDouble( vlat ) + 90. ) *1000000. + 0.5);
return n;
}
}