Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restlet server resource with constructor parameters needed

Getting this error in restlet:

ForwardUIApplication ; Exception while instantiating the target server resource.
java.lang.InstantiationException: me.unroll.forwardui.server.ForwardUIServer$UnsubscribeForwardUIResource

And I know exactly why. It's because my constructor looks like this:

public UnsubscribeForwardUIResource(MySQLConnectionPool connectionPool) {

And Restlet accesses the resource like so:

router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);

Problem is I actually need that ctor argument. How can I make it accessible? (Note I'm not using any IOC framework, just lots of ctor arguments but this is in fact an IOC pattern).

like image 849
djechlin Avatar asked Feb 25 '13 18:02

djechlin


2 Answers

If you are not using IoC you should do it manually, e.g. you could attach Restlet instance instead of the class. You could use the Context to retrieve attributes.

But maybe it has more sence to utilize a IoC container which will simplify it and reduce boilerplate code, e.g. this is for the Spring: http://pastebin.com/MnhWRKd0

like image 24
kan Avatar answered Oct 06 '22 23:10

kan


You can use the context to pass context atributes to your resource instance.

From the ServerResource API doc:

After instantiation using the default constructor, the final Resource.init(Context, Request, Response) method is invoked, setting the context, request and response. You can intercept this by overriding the Resource.doInit() method.

So, at attachment time:

router.getContext().getAttributes().put(CONNECTION_POOL_KEY, connectionPool);
router.attach(Config.unsubscribeUriPattern(), UnsubscribeForwardUIResource.class);

At your UnsubscribeForwardUIResource class you'll have to move the initialization code from the constructor to de doInit method:

public UnsubscribeForwardUIResource() {
    //default constructor can be empty
}

protected void doInit() throws ResourceException {

     MySQLConnectionPool connectionPool = (MySQLConnectionPool) getContext().getAttributes().get(CONNECTION_POOL_KEY);

    // initialization code goes here
}
like image 136
Tomas Narros Avatar answered Oct 07 '22 00:10

Tomas Narros