ali
ali

Reputation: 1486

Context of RESTlet Application is null using internal RESTlet Server

I have a Restlet (2.0.10) application, I start with the following code:

public static void main(final String[] args) {
    try {
        // Create a new Component
        final Component component = new Component();

        // Add a new HTTP server listening on port 8182
        component.getServers().add(Protocol.HTTP, SERVER_PORT);

        // Add a client protocol connector for static files
        component.getClients().add(Protocol.FILE);

        // Attach the sample application.
        component.getDefaultHost().attach("/myApp", new MyApplication(Context.getCurrent()));

        // Start the component.
        component.start();

    } catch (Exception e) {
        LOGGER.error(e);
    }

}

Now I require the applications root (i.e. /myApp) inside the application and I try to get this according to Java accessing ServletContext from within restlet Resource:

Client serverDispatcher = context.getServerDispatcher();
ServletContext servletContext = (ServletContext)serverDispatcher.getContext().getAttributes()
                    .get("org.restlet.ext.servlet.ServletContext");
String contextPath = servletContext.getContextPath();

This works perfectly fine while deploying my application to a Tomcat Server, but as soon as I start the server using a Component as shown above, my Context is always null. Can someone please tell me how to get a properly initialized context using restlets internal server capabilities?

Upvotes: 4

Views: 1605

Answers (2)

Sundeep Tonse
Sundeep Tonse

Reputation: 11

You would need to pick up the context from the Component Class:

component.getDefaultHost().attach("/myApp", 
     new MyApplication(component.getContext().createChildContext());

That would just give you the Restlet context, but Servlet Context still won't be available since this is a standalone Java application.

Upvotes: 1

koma
koma

Reputation: 6566

Seems logic.

You want a servlet context but you are not running in a servlet container, so the servlet context is NULL.

When doing component.start() you are using the Restlet connectors to server HTTP/HTTPS requests, not a servlet container like Tomcat.

Upvotes: 2

Related Questions