Create the resource factory

So now we've got our resource classes, we need a way for milton to find them to generate responses to user requests.

A typical browse request from a webdav client looks like this:

PROPFIND /milkyWay/Sol/

To answer this request milton first looks up the resource that corresponds to /milkyWay/Sol (ie a SolarSystem object) using the ResourceFactory implementation you have supplied, and milton then calls its getChildren method to list its children.

The ResourceFactory interface is very simple:

public interface ResourceFactory {
    Resource getResource(String host, String path) throws NotAuthorizedException, BadRequestException;       
}

How you implement this can have a big impact on performance and there are many ways for doing so. However the simplest way, which we'll use, is to just call the child method on each part of the path, walking along the path starting from the root, like this:

@Override
    public Resource getResource(String host, String url) throws NotAuthorizedException, BadRequestException {
        log.debug("getResource: url: " + url);
        Path path = Path.path(url);
        Resource r = find(path);
        log.debug("_found: " + r + " for url: " + url + " and path: " + path);
        return r;
    }

    private Resource find(Path path) throws NotAuthorizedException, BadRequestException {
        if (path.isRoot()) {
            RootUniverseResource r = (RootUniverseResource) HttpManager.request().getAttributes().get("rootResource");
            if( r == null ) {
                r = new RootUniverseResource(universeDao);
                HttpManager.request().getAttributes().put("rootResource", r);
            }
           
            return r;
        }
        Resource rParent = find(path.getParent());
        if (rParent == null) {
            return null;
        }
        if (rParent instanceof CollectionResource) {
            CollectionResource folder = (CollectionResource) rParent;
            return folder.child(path.getName());
        }
        return null;
    } 

So just copy and paste that into com.myastronomy.AstronomyResourceFactory

Also add the ChildUtils class, which has a little helper method to locate a child from the children collection. Note that this is not very good for performance, but will suffice for our purposes.

 

Next Article:

Run the project from maven