Commits

Anonymous committed c4507c5

Worked out authentication. First pass at using Jetty as an embedded web server

Comments (0)

Files changed (32)

Source/org/xnat/xnatfs/webdav/Bundle.java

 import java.util.ArrayList;
 import java.util.HashMap;
 
-import net.sf.ehcache.Element;
-
 import org.apache.http.HttpEntity;
 import org.apache.log4j.Logger;
 import org.json.JSONArray;
 import org.json.JSONObject;
 import org.json.JSONTokener;
 
+import com.bradmcevoy.http.Auth;
 import com.bradmcevoy.http.Resource;
 
 /**
       s = getFileMap ( mElementURL, "Name", l );
     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
+      e.printStackTrace ();
     }
-    if ( s.containsKey ( childName ) ) {
-      long size = Long.valueOf ( s.get ( childName ).get ( 1 ) ).longValue ();
-      RemoteFile remote = new RemoteFile ( xnatfs, mAbsolutePath, childName, mURL + "files/" + childName, size );
+    if ( true || s.containsKey ( childName ) ) {
+      // long size = Long.valueOf ( s.get ( childName ).get ( 1 ) ).longValue
+      // ();
+      RemoteFile remote = new RemoteFile ( xnatfs, mAbsolutePath, childName, mURL + "files/" + childName, 0l );
       return remote;
     }
     return null;
   }
 
+  protected synchronized HashMap<String, ArrayList<String>> getFileMap ( String url, String inKey, ArrayList<String> valueFields ) throws IOException {
+    return getFileMap ( url, inKey, valueFields, mCredentials );
+  }
+
   @SuppressWarnings("unchecked")
-  protected synchronized HashMap<String, ArrayList<String>> getFileMap ( String url, String inKey, ArrayList<String> valueFields ) throws IOException {
+  public static HashMap<String, ArrayList<String>> getFileMap ( String url, String inKey, ArrayList<String> valueFields, Auth mCredentials ) throws IOException {
     // Get the subjects code
-    String elementKey = mCredentials.user + "::" + mCredentials.password + "::ElementList::" + url;
-    Element element = XNATFS.sContentCache.get ( elementKey );
+    // String elementKey = mCredentials.user + "::" + mCredentials.password +
+    // "::ElementList::" + url;
+    // Element element = null; // XNATFS.sContentCache.get ( elementKey );
     HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>> ();
-    if ( element == null ) {
-      HttpEntity entity = null;
-      try {
-        entity = Connection.getInstance ().getEntity ( url, mCredentials );
-        InputStreamReader reader = new InputStreamReader ( entity.getContent () );
-        JSONTokener tokenizer = new JSONTokener ( reader );
-        JSONObject json = new JSONObject ( tokenizer );
-        JSONArray subjects = json.getJSONObject ( "ResultSet" ).getJSONArray ( "Result" );
-        logger.debug ( "Found: " + subjects.length () + " elements" );
-        for ( int idx = 0; idx < subjects.length (); idx++ ) {
-          if ( subjects.isNull ( idx ) ) {
-            continue;
-          }
-          String key = subjects.getJSONObject ( idx ).getString ( inKey );
-          ArrayList<String> values = new ArrayList<String> ();
-          for ( String value : valueFields ) {
-            values.add ( subjects.getJSONObject ( idx ).getString ( value ) );
-          }
-          map.put ( key, values );
+    // if ( element == null ) {
+    HttpEntity entity = null;
+    try {
+      entity = Connection.getInstance ().getEntity ( url, mCredentials );
+      InputStreamReader reader = new InputStreamReader ( entity.getContent () );
+      JSONTokener tokenizer = new JSONTokener ( reader );
+      JSONObject json = new JSONObject ( tokenizer );
+      JSONArray subjects = json.getJSONObject ( "ResultSet" ).getJSONArray ( "Result" );
+      logger.debug ( "Found: " + subjects.length () + " elements" );
+      for ( int idx = 0; idx < subjects.length (); idx++ ) {
+        if ( subjects.isNull ( idx ) ) {
+          continue;
         }
-      } catch ( Exception e ) {
-        logger.error ( "Caught exception reading " + url, e );
-        throw new IOException ( "Caught exception reading " + url );
-      } finally {
-        if ( entity != null ) {
-          entity.consumeContent ();
+        String key = subjects.getJSONObject ( idx ).getString ( inKey );
+        ArrayList<String> values = new ArrayList<String> ();
+        for ( String value : valueFields ) {
+          values.add ( subjects.getJSONObject ( idx ).getString ( value ) );
         }
+        map.put ( key, values );
       }
-      element = new Element ( elementKey, map );
-      XNATFS.sContentCache.put ( element );
+    } catch ( Exception e ) {
+      logger.error ( "Caught exception reading " + url, e );
+      throw new IOException ( "Caught exception reading " + url );
+    } finally {
+      if ( entity != null ) {
+        entity.consumeContent ();
+      }
     }
-    map = (HashMap<String, ArrayList<String>>) element.getObjectValue ();
     return map;
+    // element = new Element ( elementKey, map );
+    // XNATFS.sContentCache.put ( element );
+    // }
+    // map = (HashMap<String, ArrayList<String>>) element.getObjectValue ();
+    // return map;
   }
 }

Source/org/xnat/xnatfs/webdav/Experiment.java

     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
     }
-    if ( s.contains ( childName ) ) {
+    if ( true || s.contains ( childName ) ) {
       return new Scan ( xnatfs, mAbsolutePath, childName, mURL + "scans/" + childName + "/" );
     }
     return null;

Source/org/xnat/xnatfs/webdav/Project.java

     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
     }
-    if ( s.contains ( childName ) ) {
+    if ( true || s.contains ( childName ) ) {
       // Look up in the cache
       return new Subject ( xnatfs, mAbsolutePath, childName, mURL + "subjects/" + childName + "/" );
     }

Source/org/xnat/xnatfs/webdav/RemoteFile.java

 import java.io.RandomAccessFile;
 import java.nio.ByteBuffer;
 import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.Future;
 import org.apache.http.protocol.BasicHttpContext;
 import org.apache.log4j.Logger;
 
+import com.bradmcevoy.http.Auth;
 import com.bradmcevoy.http.Range;
+import com.bradmcevoy.http.Request;
+import com.bradmcevoy.http.Request.Method;
 import com.bradmcevoy.http.exceptions.NotAuthorizedException;
 
 public class RemoteFile extends VirtualFile {
     mContentLength = l;
   }
 
+  /*
+   * (non-Javadoc)
+   * 
+   * @see com.bradmcevoy.http.Resource#authorise(com.bradmcevoy.http.Request,
+   * com.bradmcevoy.http.Request.Method, com.bradmcevoy.http.Auth)
+   */
+  public boolean authorise ( Request request, Method method, Auth auth ) {
+    boolean b = super.authorise ( request, method, auth );
+    if ( b ) {
+      // Get the size from the parent
+      String parent = dirname ( mURL );
+      // Remove the trailing / if any
+      if ( parent.endsWith ( "/" ) ) {
+        parent = parent.substring ( 0, parent.length () - 2 );
+      }
+      HashMap<String, ArrayList<String>> s = null;
+      try {
+        ArrayList<String> l = new ArrayList<String> ();
+        l.add ( "URI" );
+        l.add ( "Size" );
+        s = Bundle.getFileMap ( parent + "?format=json", "Name", l, mCredentials );
+      } catch ( Exception e ) {
+        logger.error ( "Failed to get child element list: " + e );
+        e.printStackTrace ();
+        return false;
+      }
+      if ( s.containsKey ( mName ) ) {
+        mContentLength = Long.valueOf ( s.get ( mName ).get ( 1 ) ).longValue ();
+      }
+    }
+
+    return b;
+  }
+
   public Long getContentLength () {
     return mContentLength;
   }

Source/org/xnat/xnatfs/webdav/Root.java

     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
     }
-    if ( s.contains ( childName ) ) {
+    if ( true || s.contains ( childName ) ) {
+      logger.debug ( "child: Creating child " + childName );
       return new Project ( xnatfs, mAbsolutePath, childName, mURL + "projects/" + childName + "/" );
     }
     return null;

Source/org/xnat/xnatfs/webdav/Scan.java

     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
     }
-    if ( s.contains ( childName ) ) {
+    if ( true || s.contains ( childName ) ) {
       return new Bundle ( xnatfs, mAbsolutePath, childName, mURL + "resources/" + childName + "/" );
     }
     return null;

Source/org/xnat/xnatfs/webdav/StartJettyServer.java

+/**
+ * 
+ */
+package org.xnat.xnatfs.webdav;
+
+import java.io.File;
+
+import org.apache.log4j.Logger;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+
+import com.martiansoftware.jsap.FlaggedOption;
+import com.martiansoftware.jsap.JSAP;
+import com.martiansoftware.jsap.JSAPResult;
+import com.martiansoftware.jsap.SimpleJSAP;
+import com.martiansoftware.jsap.UnflaggedOption;
+import com.martiansoftware.jsap.defaultsources.PropertyDefaultSource;
+
+/**
+ * @author blezek
+ * 
+ */
+public class StartJettyServer {
+  static Logger logger = Logger.getLogger ( StartJettyServer.class );
+
+  /**
+   * @param args
+   */
+  public static void main ( String[] args ) {
+
+    JSAPResult config = parseArguments ( args );
+
+    Connection.getInstance ().setUsername ( config.getString ( "username" ) );
+    Connection.getInstance ().setPassword ( config.getString ( "password" ) );
+    Connection.getInstance ().setHost ( config.getString ( "server" ) );
+    Connection.getInstance ().setPort ( Integer.toString ( config.getInt ( "port" ) ) );
+
+    Server server = new Server ( config.getInt ( "serverport" ) );
+
+    ServletContextHandler context = new ServletContextHandler ( ServletContextHandler.SESSIONS );
+    context.setContextPath ( "/" );
+    server.setHandler ( context );
+    ServletHolder holder = new ServletHolder ( new xnatfsServlet () );
+    holder.setInitParameter ( "resource.factory.class", "org.xnat.xnatfs.webdav.XNATFS" );
+    holder.setInitParameter ( "response.handler.class", "com.bradmcevoy.http.MsOfficeResponseHandler" );
+    context.addServlet ( holder, "/*" );
+
+    try {
+      server.start ();
+    } catch ( Exception e ) {
+      logger.error ( "Error starting Jetty server: ", e );
+      e.printStackTrace ();
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  static JSAPResult parseArguments ( String[] args ) {
+    JSAPResult config = null;
+    try {
+      SimpleJSAP jsap = new SimpleJSAP ( "xnatfs", "xnatfs is a WebDAV server.  xnatfs allows "
+          + " local mounting of an XNAT instance.  Users of the system can browse projects, experiments, subjects and data using the " + " a WebDAV filesystem, rather than the web interface." );
+
+      FlaggedOption username = new FlaggedOption ( "username" ).setStringParser ( JSAP.STRING_PARSER ).setDefault ( JSAP.NO_DEFAULT ).setRequired ( true ).setShortFlag ( 'u' ).setLongFlag (
+          "username" );
+      jsap.registerParameter ( username );
+      username.setHelp ( "XNAT username for connection to the XNAT server." );
+
+      FlaggedOption password = new FlaggedOption ( "password" ).setStringParser ( JSAP.STRING_PARSER ).setDefault ( JSAP.NO_DEFAULT ).setRequired ( true ).setShortFlag ( 'p' ).setLongFlag (
+          "password" );
+      jsap.registerParameter ( password );
+      password.setHelp ( "Password for XNAT username for connection to the XNAT server." );
+
+      FlaggedOption server = new FlaggedOption ( "server" ).setStringParser ( JSAP.STRING_PARSER ).setDefault ( "central.xnat.org" ).setRequired ( true ).setShortFlag ( 's' ).setLongFlag ( "server" );
+      jsap.registerParameter ( server );
+      server.setHelp ( "XNAT server.  Should be in the form of a web site address, i.e. central.xnat.org." );
+
+      FlaggedOption port = new FlaggedOption ( "port" ).setStringParser ( JSAP.INTEGER_PARSER ).setDefault ( "80" ).setRequired ( false ).setShortFlag ( 'o' ).setLongFlag ( "port" );
+      jsap.registerParameter ( port );
+      port.setHelp ( "port to use on the XNAT server, defaults to 80" );
+
+      // Get a list of remaining options
+      UnflaggedOption serverPort = new UnflaggedOption ( "serverport" ).setStringParser ( JSAP.INTEGER_PARSER ).setDefault ( "8081" ).setRequired ( false ).setGreedy ( false );
+      serverPort.setHelp ( "Port number to run the local server on, default is 8081" );
+      jsap.registerParameter ( serverPort );
+
+      // Register the default sources. First in the application directory, next
+      // in the local directory
+      File defaultsFile = new File ( XNATFS.getApplicationResourceDirectory ( "xnatfs" ), "xnatfs.props" );
+      jsap.registerDefaultSource ( new PropertyDefaultSource ( defaultsFile.getAbsolutePath (), false ) );
+      defaultsFile = new File ( System.getProperty ( "user.dir", "." ), "xnatfs.props" );
+      jsap.registerDefaultSource ( new PropertyDefaultSource ( defaultsFile.getAbsolutePath (), false ) );
+
+      config = jsap.parse ( args );
+
+      if ( !config.success () ) {
+
+        System.err.println ();
+
+        // print out specific error messages describing the problems
+        // with the command line, THEN print usage, THEN print full
+        // help. This is called "beating the user with a clue stick."
+        System.err.println ( "The following errors were found while parsing the command line:" );
+        for ( java.util.Iterator errs = config.getErrorMessageIterator (); errs.hasNext (); ) {
+          System.err.println ( "Error: " + errs.next () );
+        }
+
+        System.err.println ();
+        System.err.println ( "Usage: java " + StartJettyServer.class.getName () );
+        System.err.println ( "                " + jsap.getUsage () );
+        System.err.println ();
+        System.err.println ( jsap.getHelp () );
+        System.exit ( 1 );
+      }
+    } catch ( Exception e ) {
+      System.err.println ( "parsing command line " + e );
+      System.exit ( 1 );
+    }
+    if ( config.userSpecified ( "help" ) ) {
+      System.exit ( 0 );
+    }
+    return config;
+  }
+
+}

Source/org/xnat/xnatfs/webdav/Subject.java

     } catch ( Exception e ) {
       logger.error ( "Failed to get child element list: " + e );
     }
-    if ( s.contains ( childName ) ) {
+    if ( true || s.contains ( childName ) ) {
       return new Experiment ( xnatfs, mAbsolutePath, childName, mURL + "experiments/" + childName + "/" );
     }
     return null;

Source/org/xnat/xnatfs/webdav/VirtualDirectory.java

     }
     ArrayList<Resource> list = new ArrayList<Resource> ();
     for ( String child : s ) {
-      logger.debug ( "got Child " + child );
+      // logger.debug ( "got Child " + child );
       list.add ( child ( child ) );
     }
     Collections.sort ( list, new Comparator<Resource> () {

Source/org/xnat/xnatfs/webdav/VirtualResource.java

         mAbsolutePath = path + "/" + mName;
       }
     }
-    logger.debug ( "Created virtual resource with name " + mName + " path " + mPath + " absolute Path " + mAbsolutePath );
+    // mCredentials = new Auth ( new String ( Base64.encodeBase64 ( new String (
+    // "blezek:throwaway" ).getBytes () ) ) );
+    // logger.debug ( "Created virtual resource with name " + mName + " path " +
+    // mPath + " absolute Path " + mAbsolutePath );
   }
 
   public Auth getCredentials () {
       return false;
     }
     mCredentials = auth;
+    logger.debug ( "authorise " + auth.user + " for class " + this.getClass ().getName () );
     // return xnatfs.getSecurityManager ().authorise ( request, method, auth,
     // this );
     return true;

Source/org/xnat/xnatfs/webdav/xnatfs.java

       return false;
     }
     logger.debug ( "authorise: " + auth.user + "/" + auth.password );
+    if ( resource instanceof VirtualResource ) {
+      VirtualResource r = (VirtualResource) resource;
+      r.authenticate ( auth.user, auth.password );
+    }
     return true;
   }
 

Source/org/xnat/xnatfs/webdav/xnatfsServlet.java

   }
 
   public String getServletInfo () {
-    return "MiltonServlet";
+    return "xnatfs";
   }
 
   public ServletConfig getServletConfig () {

lib/jetty-ajp-7.0.0.RC5.jar

Binary file added.

lib/jetty-annotations-7.0.0.RC5.jar

Binary file added.

lib/jetty-client-7.0.0.RC5.jar

Binary file added.

lib/jetty-continuation-7.0.0.RC5.jar

Binary file added.

lib/jetty-deploy-7.0.0.RC5.jar

Binary file added.

lib/jetty-http-7.0.0.RC5.jar

Binary file added.

lib/jetty-io-7.0.0.RC5.jar

Binary file added.

lib/jetty-jmx-7.0.0.RC5.jar

Binary file added.

lib/jetty-jndi-7.0.0.RC5.jar

Binary file added.

lib/jetty-plus-7.0.0.RC5.jar

Binary file added.

lib/jetty-policy-7.0.0.RC5.jar

Binary file added.

lib/jetty-rewrite-7.0.0.RC5.jar

Binary file added.

lib/jetty-security-7.0.0.RC5.jar

Binary file added.

lib/jetty-server-7.0.0.RC5.jar

Binary file added.

lib/jetty-servlet-7.0.0.RC5.jar

Binary file added.

lib/jetty-servlets-7.0.0.RC5.jar

Binary file added.

lib/jetty-util-7.0.0.RC5.jar

Binary file added.

lib/jetty-webapp-7.0.0.RC5.jar

Binary file added.

lib/jetty-xml-7.0.0.RC5.jar

Binary file added.

lib/servlet-api-2.5.jar

Binary file added.