tags:

views:

565

answers:

4

If I have a relative path to a static asset (flash/blah.swf), what is the best way to programmatically convert this to an absolute URL (http://localhost/app/flash/blah.swf)? Or what is the best way to get the base URL of the Wicket application? I've tried using RequestUtils.toAbsolutePath but it doesn't seem to work reliably and is frequently throwing exceptions. This needs to work on all servers the app is deployed to.

A: 

You can use some folders:

  1. The server root dir
  2. The working dir

So:

String hostAddress = "http://localhost/";
String serverRoot = "C:/path/to/my/root/";
String relativePath = "flash/blah.swf";
String workingDir = System.getProperty("user.dir"); // This returns the working dir ("C:/path/to/my/root/apps")
String absolute = hostAddress + workingDir.substring(serverRoot.length()) + relativePath;

I think you have to use something like this

Martijn Courteaux
I need to resolve the URL programmatically, so I can't hardcode hostAddress
Gilean
@Gilean: This code isn't ready, you have to change it. If you don't want to hardcode, you can save data in a file.
Martijn Courteaux
A: 

org.apache.wicket.protocol.http.servlet.ServletWebRequest has a method getRelativePathPrefixToContextRoot() (actually defined as abstract in a superclass).

A standard idiom for using it is

RequestCycle.get().getRequest().getRelativePathPrefixToContextRoot() + location;
Don Roby
A: 

I ended up using something like this after adding a base_url property to my MyApplication class that extends the wicket application.

MyApplication app = (MyApplication)getApplication();
String appBaseUrl = app.getBaseUrl(); 
if (StringUtils.isEmpty(appBaseUrl)) { 
    appBaseUrl = RequestUtils.toAbsolutePath(urlFor(app.getHomePage(), new PageParameters()).toString());
    app.setBaseUrl(appBaseUrl); 
} 

// Add base URL to <script wicket:id="base_url"></script> to use with Flash
add(new Label("base_url", "base_url = \"" + appBaseUrl + "\";").setEscapeModelStrings(false)); 
Gilean
+1  A: 

RequestUtils.toAbsolutePath(RequestCycle.get().getRequest().getRelativePathPrefixToWicketHandler());

Worked for me...

Richard Noble