Using Restlet component to run an application

If you have a look on the Restlet architecture, you will see Restlet framework composes virtual hosts and applications. Applications in turn compose resources. In this example, we will see how Restlet framework runs an application (a directory listing application) after receving a client request.

  1. Continue the precedent tutorials, create the third Java package name “thirdREST”, then, a Java class named “FileApplication”.
  2. Copy and paste the following codes to the created class (noted that you have to replace the [path to your restlet] by a correct path):

    package thirdREST;
     
    import org.restlet.Application;
    import org.restlet.Restlet;
    import org.restlet.resource.Directory;
     
    public class FileApplication extends Application{
            //use file://[your path]
            //on windows, make sure that you add enough slashes at the beginning, e.g. file:///C:/[your path]
    	public static final String ROOT_URI = "file:///[path to your restlet]/docs/api/";
    	//for example: public static final String ROOT_URI = "file:///C:/restlet-jee-2.0.6/docs/api/";
     
            //Create an inbound root Restlet that will receive all incoming calls
    	@Override  
    	public Restlet createInboundRoot() {  
                   //return the directory of local resources
                   //an instance of Directory is used as initial application Restlet
    	       return new Directory(getContext(), ROOT_URI);  
    	} 
    }
  3. The application is ready to list the Restlet API now. In the next step, we create a class that attach the client request to the FileApplication service.
  4. Create new Java class name RESTDistributor and add the following codes:

    package thirdREST;
     
    import org.restlet.Component;
    import org.restlet.data.Protocol;
     
    public class RESTDistributor {
     
    	/**
    	 * @param args
    	 * @throws Exception 
    	 */
    	public static void main(String[] args) throws Exception {
    		// TODO Auto-generated method stub
    		// Create a new Restlet component and add a HTTP server connector to it  
    		Component component = new Component();  
    		component.getServers().add(Protocol.HTTP, 8182); 
     
    		// add a Restlet client that run FILE protocol to the component
    		component.getClients().add(Protocol.FILE);
     
    		// Attach the application to the component and start it  
    		component.getDefaultHost().attach("/doc/",new FileApplication());  
    		component.start();  
    	}	 
     
    }
  5. Run this Java application (Alt+Shift+X,J) and naviage the URI: http://localhost:8182/doc/.
  6. Done.