Restlet server resource with constructor parameters needed
Asked Answered
G

2

10

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).

Gant answered 25/2, 2013 at 18:20 Comment(0)
E
11

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
}
Embody answered 5/3, 2013 at 8:50 Comment(0)
P
1

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

Predation answered 28/2, 2013 at 12:7 Comment(3)
Per the documentation it is not possible to attach an instance.Gant
Oh, you are right. You could attach Restlet instance, but not ServerResource. Could you use the Restlet when? If not, then just use doInit to wire the Connnection from the Context.Predation
Have you tried attaching it using a Filter (org.restlet.routing.Filter) ?Philbrook

© 2022 - 2024 — McMap. All rights reserved.