Implementing Copy

Webdav has a COPY method which corresponds to milton's CopyableResource method:

void copyTo(CollectionResource toCollection, String name) throws NotAuthorizedException, BadRequestException, ConflictException;

We will implement CopyableResource on our PlanetResource to allow planets to be copied within their own solar system to a different solar system. The method will throw an exception if the destination folder is not a SolarSystemResource

public class PlanetResource extends AbstractResource implements GetableResource, ReplaceableResource, MoveableResource, CopyableResource{

    private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(PlanetResource.class);
    private final SolarSystemResource parent;
    private final Planet planet;

    public PlanetResource(SolarSystemResource parent, Planet planet) {
        this.parent = parent;
        this.planet = planet;
    }

    @Override
    public void copyTo(CollectionResource toCollection, String name) throws NotAuthorizedException, BadRequestException, ConflictException {
        if( toCollection instanceof SolarSystemResource ) {
            throw new BadRequestException("Can only copy planet to a SolarSystemResource folder. Current parent=" +parent.getName() + " dest parent=" + toCollection.getName());
        }
        SolarSystemResource newSolarSystem = (SolarSystemResource) toCollection;
        Planet pNew = newSolarSystem.getSolarSystem().addPlanet(name);
        pNew.setRadius(planet.getRadius());
        pNew.setType(planet.getType());
        pNew.setYearLength(planet.getYearLength());
    }

Copying Collections

Note that when you implement the copy method on a folder it must be recursive, it your method should copy all of the files and folders within that folder - webdav clients won't do that for you.