Index: src/edu/ucsb/nceas/metacat/dataone/CrudService.java
===================================================================
--- src/edu/ucsb/nceas/metacat/dataone/CrudService.java	(revision 5330)
+++ src/edu/ucsb/nceas/metacat/dataone/CrudService.java	(revision 5331)
@@ -94,12 +94,7 @@
     private HttpServletRequest request;
     private HttpServletResponse response;
 
-//    private Logger logMetacat;
     private MetacatHandler handler;
-//    private String username;
-//    private String password;
-//    private String sessionId;
-//    private String[] groupNames;
     private Hashtable<String, String[]> params;
     Logger logMetacat = null;
 
@@ -137,49 +132,6 @@
         }
     }
     
-    /**
-     * 
-     * Load user details of metacat session from the request 
-     * 
-     */
-//    private void loadSessionData() {
-//        SessionData sessionData = RequestUtil.getSessionData(request);
-//
-//        // TODO: validate the session before allowing these values to be set
-//        username = sessionData.getUserName();
-//        password = sessionData.getPassword();
-//        groupNames = sessionData.getGroupNames();
-//        sessionId = sessionData.getId();
-//
-//        if (username == null) {
-//            username = "public";
-//        }
-//    }
-    
-    /*
-     * Look up the information on the session using the token provided in
-     * the AuthToken.  The Session should have all relevant user information.
-     * If the session has expired or is invalid, the 'public' session will
-     * be returned, giving the user anonymous access.
-     */
-    private static SessionData getSessionData(AuthToken token) {
-        SessionData sessionData = null;
-        String sessionId = "PUBLIC";
-        if (token != null) {
-            sessionId = token.getToken();
-        }
-        
-        // if the session id is registered in SessionService, get the
-        // SessionData for it. Otherwise, use the public session.
-        if (SessionService.isSessionRegistered(sessionId)) {
-            sessionData = SessionService.getRegisteredSession(sessionId);
-        } else {
-            sessionData = SessionService.getPublicSession();
-        }
-        
-        return sessionData;
-    }
-    
     public Identifier create(AuthToken token, Identifier guid, 
             InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
             ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
@@ -207,91 +159,30 @@
                 "GUID is already in use by an existing object.");
         }
 
-        // generate guid/localId pair for object
-        logMetacat.debug("Generating a guid/localId mapping");
-        String localId = im.generateLocalId(guid.getValue(), 1);
-
         // Check if we are handling metadata or data
         boolean isScienceMetadata = isScienceMetadata(sysmeta);
         
         if (isScienceMetadata) {
-            // TODO: CASE METADATA:
-            // Setup and call handleInsertOrUpdate()
+            // CASE METADATA:
+            try {
+                String xml = IOUtils.toString(object);
+                this.insertDocument(xml, guid, sessionData);
+            } catch (IOException e) {
+                String msg = "Could not create string from XML stream: " +
+                    " " + e.getMessage();
+                logMetacat.debug(msg);
+                throw new ServiceFailure(1190, msg);
+            }
 
         } else {
-            // TODO: DEFAULT CASE: DATA (needs to be checked and completed)
-            try {
-                logMetacat.debug("Case DATA: starting to write to disk.");
-                if (DocumentImpl.getDataFileLockGrant(localId)) {
+            // DEFAULT CASE: DATA (needs to be checked and completed)
+            insertDataObject(object, guid, sessionData);
+            
+        }
 
-                    // Save the data file to disk using "localId" as the name
-                    try {
-                        String datafilepath = PropertyService.getProperty("application.datafilepath");
+        // For Metadata and Data, insert the system metadata into the object store too
+        insertSystemMetadata(sysmeta, sessionData);
 
-                        File dataDirectory = new File(datafilepath);
-                        dataDirectory.mkdirs();
-
-                        File newFile = writeStreamToFile(dataDirectory, localId, object);
-
-                        // TODO: Check that the file size matches SystemMetadata
-                        //                        long size = newFile.length();
-                        //                        if (size == 0) {
-                        //                            throw new IOException("Uploaded file is 0 bytes!");
-                        //                        }
-
-                        //register the file in the database (which generates an exception
-                        // if the docid is not acceptable or other untoward things happen
-                        try {
-                            logMetacat.debug("Registering document...");
-                            DocumentImpl.registerDocument(localId, "BIN", localId,
-                                    username, groups);
-                            logMetacat.debug("Registrtion step completed.");
-                        } catch (SQLException e) {
-                            //newFile.delete();
-                            logMetacat.debug("SQLE: " + e.getMessage());
-                            e.printStackTrace(System.out);
-                            throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
-                        } catch (AccessionNumberException e) {
-                            //newFile.delete();
-                            logMetacat.debug("ANE: " + e.getMessage());
-                            e.printStackTrace(System.out);
-                            throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
-                        } catch (Exception e) {
-                            //newFile.delete();
-                            logMetacat.debug("Exception: " + e.getMessage());
-                            e.printStackTrace(System.out);
-                            throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
-                        }
-
-                        logMetacat.debug("Logging the creation event.");
-                        EventLog.getInstance().log(request.getRemoteAddr(),
-                                username, localId, "create");
-
-                        // Force replication this data file
-                        // To data file, "insert" and update is same
-                        // The fourth parameter is null. Because it is notification 
-                        // server and this method is in MetaCatServerlet. It is
-                        // original command, not get force replication info from 
-                        // another metacat
-                        // TODO: note that GUID mapping is not being replicated
-                        logMetacat.debug("Scheduling replication.");
-                        ForceReplicationHandler frh = new ForceReplicationHandler(
-                                localId, "insert", false, null);
-
-                    } catch (PropertyNotFoundException e) {
-                        throw new ServiceFailure(1190, "Could not lock file for writing:" + e.getMessage());
-                    }
-
-                }
-            } catch (Exception e) {
-                // Could not get a lock on the document, so we can not update the file now
-                throw new ServiceFailure(1190, "Failed to lock file: " + e.getMessage());
-            }
-            
-            // Insert the system metadata into the object store
-            insertSystemMetadata(sysmeta, sessionData);
-        }
-        
         logMetacat.debug("Returning from CrudService.create()");
         return guid;
     }
@@ -398,11 +289,129 @@
         throw new NotImplemented(1000, "This method not yet implemented.");
     }
 
+    /*
+     * Look up the information on the session using the token provided in
+     * the AuthToken.  The Session should have all relevant user information.
+     * If the session has expired or is invalid, the 'public' session will
+     * be returned, giving the user anonymous access.
+     */
+    private static SessionData getSessionData(AuthToken token) {
+        SessionData sessionData = null;
+        String sessionId = "PUBLIC";
+        if (token != null) {
+            sessionId = token.getToken();
+        }
+        
+        // if the session id is registered in SessionService, get the
+        // SessionData for it. Otherwise, use the public session.
+        if (SessionService.isSessionRegistered(sessionId)) {
+            sessionData = SessionService.getRegisteredSession(sessionId);
+        } else {
+            sessionData = SessionService.getPublicSession();
+        }
+        
+        return sessionData;
+    }
+
+    /** 
+     * Determine if a given object should be treated as an XML science metadata
+     * object. 
+     * 
+     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
+     * 
+     * @param sysmeta the SystemMetadata describig the object
+     * @return true if the object should be treated as science metadata
+     */
+    private boolean isScienceMetadata(SystemMetadata sysmeta) {
+        boolean scimeta = false;
+        switch (sysmeta.getObjectFormat()) {
+            case EML_2_1_0: scimeta = true; break;
+            case EML_2_0_1: scimeta = true; break;
+            case EML_2_0_0: scimeta = true; break;
+            case FGDC_STD_001_1_1999: scimeta = true; break;
+            case FGDC_STD_001_1998: scimeta = true; break;
+            case NCML_2_2: scimeta = true; break;
+        }
+        
+        return scimeta;
+    }
+
+    private void insertDataObject(InputStream object, Identifier guid, 
+            SessionData sessionData) throws ServiceFailure {
+        
+        String username = sessionData.getUserName();
+        String[] groups = sessionData.getGroupNames();
+
+        // generate guid/localId pair for object
+        logMetacat.debug("Generating a guid/localId mapping");
+        IdentifierManager im = IdentifierManager.getInstance();
+        String localId = im.generateLocalId(guid.getValue(), 1);
+
+        try {
+            logMetacat.debug("Case DATA: starting to write to disk.");
+            if (DocumentImpl.getDataFileLockGrant(localId)) {
+    
+                // Save the data file to disk using "localId" as the name
+                try {
+                    String datafilepath = PropertyService.getProperty("application.datafilepath");
+    
+                    File dataDirectory = new File(datafilepath);
+                    dataDirectory.mkdirs();
+    
+                    File newFile = writeStreamToFile(dataDirectory, localId, object);
+    
+                    // TODO: Check that the file size matches SystemMetadata
+                    //                        long size = newFile.length();
+                    //                        if (size == 0) {
+                    //                            throw new IOException("Uploaded file is 0 bytes!");
+                    //                        }
+    
+                    // Register the file in the database (which generates an exception
+                    // if the localId is not acceptable or other untoward things happen
+                    try {
+                        logMetacat.debug("Registering document...");
+                        DocumentImpl.registerDocument(localId, "BIN", localId,
+                                username, groups);
+                        logMetacat.debug("Registration step completed.");
+                    } catch (SQLException e) {
+                        //newFile.delete();
+                        logMetacat.debug("SQLE: " + e.getMessage());
+                        e.printStackTrace(System.out);
+                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
+                    } catch (AccessionNumberException e) {
+                        //newFile.delete();
+                        logMetacat.debug("ANE: " + e.getMessage());
+                        e.printStackTrace(System.out);
+                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
+                    } catch (Exception e) {
+                        //newFile.delete();
+                        logMetacat.debug("Exception: " + e.getMessage());
+                        e.printStackTrace(System.out);
+                        throw new ServiceFailure(1190, "Registration failed: " + e.getMessage());
+                    }
+    
+                    logMetacat.debug("Logging the creation event.");
+                    EventLog.getInstance().log(request.getRemoteAddr(),
+                            username, localId, "create");
+    
+                    // Schedule replication for this data file
+                    logMetacat.debug("Scheduling replication.");
+                    ForceReplicationHandler frh = new ForceReplicationHandler(
+                            localId, "insert", false, null);
+    
+                } catch (PropertyNotFoundException e) {
+                    throw new ServiceFailure(1190, "Could not lock file for writing:" + e.getMessage());
+                }
+    
+            }
+        } catch (Exception e) {
+            // Could not get a lock on the document, so we can not update the file now
+            throw new ServiceFailure(1190, "Failed to lock file: " + e.getMessage());
+        }
+    }
+
     private File writeStreamToFile(File dir, String fileName, InputStream data) 
         throws ServiceFailure {
-//        logMetacat.debug("***********************************************");
-//        logMetacat.debug("** FILE TEST FROM CS                         **");
-//        logMetacat.debug("***********************************************");
         
         File newFile = new File(dir, fileName);
         logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
@@ -409,17 +418,11 @@
 
         try {
             if (newFile.createNewFile()) {
-//                logMetacat.debug("File doesn't yet exist, so write to it.");
-//                logMetacat.debug("Creating file stream...");
-                
                 // write data stream to desired file
                 OutputStream os = new FileOutputStream(newFile);
-//                logMetacat.debug("Copying file stream...");
                 long length = IOUtils.copyLarge(data, os);
                 os.flush();
-//                logMetacat.debug("Closing file stream...");
                 os.close();
-//                logMetacat.debug("Done with file stream...");
             } else {
                 logMetacat.debug("File creation failed, or file already exists.");
                 throw new ServiceFailure(1190, "File already exists: " + fileName);
@@ -434,36 +437,9 @@
                     + " " + e.getMessage());
         }
 
-//        logMetacat.debug("***********************************************");
-//        logMetacat.debug("** END FILE TEST                             **");
-//        logMetacat.debug("***********************************************");
-        
         return newFile;
     }
 
-    /** 
-     * Determine if a given object should be treated as an XML science metadata
-     * object. 
-     * 
-     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
-     * 
-     * @param sysmeta the SystemMetadata describig the object
-     * @return true if the object should be treated as science metadata
-     */
-    private boolean isScienceMetadata(SystemMetadata sysmeta) {
-        boolean scimeta = false;
-        switch (sysmeta.getObjectFormat()) {
-            case EML_2_1_0: scimeta = true; break;
-            case EML_2_0_1: scimeta = true; break;
-            case EML_2_0_0: scimeta = true; break;
-            case FGDC_STD_001_1_1999: scimeta = true; break;
-            case FGDC_STD_001_1998: scimeta = true; break;
-            case NCML_2_2: scimeta = true; break;
-        }
-        
-        return scimeta;
-    }
-
     private void insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
         throws ServiceFailure {
         logMetacat.debug("Starting to insert SystemMetadata...");
@@ -470,7 +446,8 @@
         IdentifierManager im = IdentifierManager.getInstance();
     
         // generate guid/localId pair for sysmeta
-        String sysMetaGuid = DocumentUtil.generateDocumentId(1);
+        Identifier sysMetaGuid = new Identifier();
+        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
         sysmeta.setDateSysMetadataModified(new Date());
 
         String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
@@ -477,23 +454,16 @@
         insertDocument(xml, sysMetaGuid, sessionData);
     }
     
-    private void insertDocument(String xml, String guid, SessionData sessionData) 
+    private void insertDocument(String xml, Identifier guid, SessionData sessionData) 
         throws ServiceFailure {
         logMetacat.debug("Starting to insert xml document...");
         IdentifierManager im = IdentifierManager.getInstance();
 
         // generate guid/localId pair for sysmeta
-        String localId = im.generateLocalId(guid, 1);
-        logMetacat.debug("Metadata guid|localId: " + guid + "|" +
+        String localId = im.generateLocalId(guid.getValue(), 1);
+        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
                 localId);
 
-        // TODO: insert system metadata to metacat (probably at end)
-        // TODO: can't pass in the out PrintWriter, as we don't want to write
-        // error info on this stream -- need to be able to return to process
-        // the real object.  So, need to:
-        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
-        // onto output stream, or alternatively, capture that and parse it to 
-        // generate the right exceptions
         String[] action = new String[1];
         action[0] = "insert";
         params.put("action", action);
@@ -504,6 +474,10 @@
         doctext[0] = xml;
         logMetacat.debug(doctext[0]);
         params.put("doctext", doctext);
+        
+        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
+        // onto output stream, or alternatively, capture that and parse it to 
+        // generate the right exceptions
         ByteArrayOutputStream output = new ByteArrayOutputStream();
         PrintWriter pw = new PrintWriter(output);
         handler.handleInsertOrUpdateAction(request.getRemoteAddr(), response, 
@@ -510,7 +484,7 @@
                 pw, params, sessionData.getUserName(),
                 sessionData.getGroupNames());
         logMetacat.debug(new String(output.toByteArray()));
-        logMetacat.debug("Finsihed inserting xml document.");
+        logMetacat.debug("Finsished inserting xml document.");
     }
     
     private ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
