package org.basex.api.webdav;

import static org.basex.api.webdav.BXResource.*;

import java.io.IOException;

import org.basex.api.HTTPSession;
import org.basex.server.LoginException;
import org.basex.server.Session;
import org.basex.util.Util;

import com.bradmcevoy.common.Path;
import com.bradmcevoy.http.Auth;
import com.bradmcevoy.http.HttpManager;
import com.bradmcevoy.http.Resource;
import com.bradmcevoy.http.ResourceFactory;

/**
 * WebDAV resource factory. Main class for generating WebDAV resources.
 *
 * @author BaseX Team 2005-11, BSD License
 * @author Rositsa Shadura
 * @author Dimitar Popov
 */
public class BXResourceFactory implements ResourceFactory {
  @Override
  public Resource getResource(final String host, final String dbpath) {
    final Auth a = HttpManager.request().getAuthorization();
    final String user = a != null ? a.getUser() : null;
    final String pass = a != null ? a.getPassword() : null;
    final HTTPSession session = new HTTPSession(user, pass);

    try {
      final Session s = session.login();
      try {
        // the root is requested
        final Path path = Path.path(dbpath).getStripFirst();
        if(path.isRoot()) return new BXRootResource(session);

        // only the database is requested
        final String db = path.getFirst();
        return path.getLength() == 1 ?
          listDBs(s).contains(db) ? new BXDatabase(db, session) : null :
          resource(s, db, path.getStripFirst().toString(), session);
      } finally {
        s.close();
      }
    } catch(final LoginException ex) {
      return BXNotAuthorizedResource.NOAUTH;
    } catch(final IOException ex) {
      Util.errln(ex);
    }
    return null;
  }
}

@@ -61,24 +61,92 @@
 ebdav.BX
-Resource
+NotAuthorizedResource.*;%0Aimport static org.basex.api.webdav.BXServletRequest
 .*;%0A%0Aimp
@@ -1133,76 +1133,170 @@
     
-// the root is requested%0A        final Path path = Path.path(dbpath)
+Path p = Path.path(dbpath);%0A        if(!getRequest().getContextPath().isEmpty()) p = p.getStripFirst();%0A        if(!getRequest().getServletPath().isEmpty()) p = p
 .get
@@ -1301,32 +1301,33 @@
 etStripFirst();%0A
+%0A
         if(path.
@@ -1322,19 +1322,16 @@
     if(p
-ath
 .isRoot(
@@ -1374,50 +1374,8 @@
 );%0A%0A
-        // only the database is requested%0A
     
@@ -1397,19 +1397,16 @@
 g db = p
-ath
 .getFirs
@@ -1426,19 +1426,16 @@
 return p
-ath
 .getLeng
@@ -1546,19 +1546,16 @@
 s, db, p
-ath
 .getStri
@@ -1686,32 +1686,8 @@
 urn 
-BXNotAuthorizedResource.
 NOAU

work independently of the servlet path (+ minor clean up)