Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: $'
7
 *     '$Date: 2009-06-13 15:28:13 +0300  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacat.dataone;
24

    
25
import java.io.ByteArrayOutputStream;
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33

    
34
import java.security.NoSuchAlgorithmException;
35

    
36
import java.sql.SQLException;
37

    
38
import java.text.DateFormat;
39

    
40
import java.util.Calendar;
41
import java.util.Date;
42
import java.util.Enumeration;
43
import java.util.Hashtable;
44
import java.util.List;
45
import java.util.TimeZone;
46
import java.util.Timer;
47
import java.util.TimerTask;
48
import java.util.Vector;
49

    
50
import javax.servlet.http.HttpServletRequest;
51

    
52
import javax.xml.parsers.ParserConfigurationException;
53
import javax.xml.xpath.XPathExpressionException;
54

    
55
import org.apache.commons.io.IOUtils;
56
import org.apache.log4j.Logger;
57

    
58
import org.dataone.eml.DataoneEMLParser;
59
import org.dataone.eml.EMLDocument;
60
import org.dataone.eml.EMLDocument.DistributionMetadata;
61

    
62
import org.dataone.service.exceptions.BaseException;
63
import org.dataone.service.exceptions.IdentifierNotUnique;
64
import org.dataone.service.exceptions.InsufficientResources;
65
import org.dataone.service.exceptions.InvalidRequest;
66
import org.dataone.service.exceptions.InvalidSystemMetadata;
67
import org.dataone.service.exceptions.InvalidToken;
68
import org.dataone.service.exceptions.NotAuthorized;
69
import org.dataone.service.exceptions.NotFound;
70
import org.dataone.service.exceptions.NotImplemented;
71
import org.dataone.service.exceptions.ServiceFailure;
72
import org.dataone.service.exceptions.UnsupportedType;
73

    
74
import org.dataone.service.mn.MemberNodeCrud;
75

    
76
import org.dataone.service.types.AuthToken;
77
import org.dataone.service.types.Checksum;
78
import org.dataone.service.types.ChecksumAlgorithm;
79
import org.dataone.service.types.DescribeResponse;
80
import org.dataone.service.types.Event;
81
import org.dataone.service.types.Identifier;
82
import org.dataone.service.types.Log;
83
import org.dataone.service.types.LogEntry;
84
import org.dataone.service.types.NodeReference;
85
import org.dataone.service.types.ObjectFormat;
86
import org.dataone.service.types.ObjectList;
87
import org.dataone.service.types.Subject;
88
import org.dataone.service.types.SystemMetadata;
89
import org.dataone.service.types.util.ServiceTypeUtil;
90

    
91
import org.jibx.runtime.BindingDirectory;
92
import org.jibx.runtime.IBindingFactory;
93
import org.jibx.runtime.IMarshallingContext;
94
import org.jibx.runtime.IUnmarshallingContext;
95
import org.jibx.runtime.JiBXException;
96

    
97
import org.xml.sax.SAXException;
98

    
99
import edu.ucsb.nceas.metacat.AccessionNumber;
100
import edu.ucsb.nceas.metacat.AccessionNumberException;
101
import edu.ucsb.nceas.metacat.DocumentImpl;
102
import edu.ucsb.nceas.metacat.EventLog;
103
import edu.ucsb.nceas.metacat.IdentifierManager;
104
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
105
import edu.ucsb.nceas.metacat.McdbException;
106
import edu.ucsb.nceas.metacat.MetacatHandler;
107
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
108
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
109
import edu.ucsb.nceas.metacat.properties.PropertyService;
110
import edu.ucsb.nceas.metacat.replication.ForceReplicationHandler;
111
import edu.ucsb.nceas.metacat.service.SessionService;
112
import edu.ucsb.nceas.metacat.util.DocumentUtil;
113
import edu.ucsb.nceas.metacat.util.SessionData;
114

    
115
import edu.ucsb.nceas.utilities.ParseLSIDException;
116
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
117

    
118
/**
119
 * 
120
 * Implements DataONE MemberNode CRUD API for Metacat. 
121
 * 
122
 * @author Matthew Jones
123
 */
124
public class CrudService implements MemberNodeCrud
125
{
126
    private static CrudService crudService = null;
127

    
128
    private MetacatHandler handler;
129
    private Hashtable<String, String[]> params;
130
    private Logger logMetacat = null;
131
    private Logger logCrud = null;
132
    
133
    private String metacatUrl;
134
    
135
    /**
136
     * singleton accessor
137
     */
138
    public static CrudService getInstance() 
139
    {
140
      if(crudService == null)
141
      {
142
        crudService = new CrudService();
143
      }
144
      
145
      return crudService;
146
    }
147
    
148
    /**
149
     * Constructor, private for singleton access
150
     */
151
    private CrudService() {
152
        logMetacat = Logger.getLogger(CrudService.class);
153
        logCrud = Logger.getLogger("DataOneLogger");
154
        try
155
        {
156
            String server = PropertyService.getProperty("server.name");
157
            String port = PropertyService.getProperty("server.httpPort");
158
            String context = PropertyService.getProperty("application.context");
159
            metacatUrl = "http://" + server + ":" + port + "/" + context + "/d1";
160
            logMetacat.debug("Initializing CrudService with url " + metacatUrl);
161
        }
162
        catch(Exception e)
163
        {
164
            logMetacat.error("Could not find servlet url in CrudService: " + e.getMessage());
165
            e.printStackTrace();
166
            throw new RuntimeException("Error getting servlet url in CrudService: " + e.getMessage());
167
        }
168
        
169
        params = new Hashtable<String, String[]>();
170
        handler = new MetacatHandler(new Timer());
171
    }
172
    
173
    /**
174
     * return the context url CrudService is using.
175
     */
176
    public String getContextUrl()
177
    {
178
        return metacatUrl;
179
    }
180
    
181
    /**
182
     * Set the context url that this service uses.  It is normally not necessary
183
     * to call this method unless you are trying to connect to a server other
184
     * than the one in which this service is installed.  Otherwise, this value is
185
     * taken from the metacat.properties file (server.name, server.port, application.context).
186
     */
187
    public void setContextUrl(String url)
188
    {
189
        metacatUrl = url;
190
    }
191
    
192
    /**
193
     * set the params for this service from an HttpServletRequest param list
194
     */
195
    public void setParamsFromRequest(HttpServletRequest request)
196
    {
197
        @SuppressWarnings("unchecked")
198
        Enumeration<String> paramlist = request.getParameterNames();
199
        while (paramlist.hasMoreElements()) {
200
            String name = (String) paramlist.nextElement();
201
            String[] value = (String[])request.getParameterValues(name);
202
            params.put(name, value);
203
        }
204
    }
205
    
206
    /**
207
     * Authenticate against metacat and get a token.
208
     * @param username
209
     * @param password
210
     * @return
211
     * @throws ServiceFailure
212
     */
213
    public AuthToken authenticate(String username, String password)
214
      throws ServiceFailure
215
    {
216
        /* TODO:
217
         * This method is not in the original D1 crud spec.  It is highly
218
         * metacat centric.  Higher level decisions need to be made on authentication
219
         * interfaces for D1 nodes.
220
         */
221
        try
222
        {
223
            MetacatRestClient restClient = new MetacatRestClient(getContextUrl());   
224
            String response = restClient.login(username, password);
225
            String sessionid = restClient.getSessionId();
226
            SessionService sessionService = SessionService.getInstance();
227
            sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
228
            AuthToken token = new AuthToken(sessionid);
229
            EventLog.getInstance().log(metacatUrl,
230
                    username, null, "authenticate");
231
            logCrud.info("authenticate");
232
            return token;
233
        }
234
        catch(Exception e)
235
        {
236
            throw new ServiceFailure("1620", "Error authenticating with metacat: " + e.getMessage());
237
        }
238
    }
239
    
240
    /**
241
     * set the parameter values needed for this request
242
     */
243
    public void setParameter(String name, String[] value)
244
    {
245
        params.put(name, value);
246
    }
247
    
248
    /**
249
     * Generate SystemMetadata for any object in the object store that does
250
     * not already have it.  SystemMetadata documents themselves, are, of course,
251
     * exempt.  This is a utility method for migration of existing object 
252
     * stores to DataONE where SystemMetadata is required for all objects.  See 
253
     * https://trac.dataone.org/ticket/591
254
     * 
255
     * @param token an authtoken with appropriate permissions to read all 
256
     * documents in the object store.  To work correctly, this should probably
257
     * be an adminstrative credential.
258
     * @throws SQLException 
259
     * @throws AccessionNumberException 
260
     * @throws NoSuchAlgorithmException 
261
     * @throws InvalidRequest 
262
     * @throws NotImplemented 
263
     * @throws NotFound 
264
     * @throws NotAuthorized 
265
     * @throws InvalidToken 
266
     * @throws PropertyNotFoundException 
267
     * @throws McdbDocNotFoundException 
268
     * @throws ServiceFailure 
269
     */
270
    public void generateMissingSystemMetadata(AuthToken token) 
271
    throws ServiceFailure, McdbDocNotFoundException, PropertyNotFoundException, InvalidToken, NotAuthorized, 
272
    NotFound, NotImplemented, InvalidRequest, NoSuchAlgorithmException, AccessionNumberException, SQLException 
273
    {
274
        IdentifierManager im = IdentifierManager.getInstance();
275
        //get the list of ids with no SM
276
        List<String> idList = im.getLocalIdsWithNoSystemMetadata();
277
        for (String localId : idList) { 
278
            //for each id, add a system metadata doc
279
            generateMissingSystemMetadata(token, localId);
280
        }
281
        logCrud.info("generateMissingSystemMetadata(token)");
282
    }
283
    
284
    /**
285
     * Generate SystemMetadata for a particular object with identifier localId.
286
     * This is a utility method for migration of existing objects 
287
     * to DataONE where SystemMetadata is required for all objects.
288
     * 
289
     * @param token an authtoken with appropriate permissions to read all 
290
     *        documents in the object store.  To work correctly, this should
291
     *        be an adminstrative credential.
292
     * @param localId the identifier of the object to be processed
293
     * @throws ServiceFailure 
294
     * @throws SQLException 
295
     * @throws AccessionNumberException 
296
     * @throws NoSuchAlgorithmException 
297
     * @throws InvalidRequest 
298
     * @throws NotImplemented 
299
     * @throws NotFound 
300
     * @throws NotAuthorized 
301
     * @throws InvalidToken 
302
     * @throws PropertyNotFoundException 
303
     * @throws McdbDocNotFoundException 
304
     */
305
    public void generateMissingSystemMetadata(AuthToken token, String localId) 
306
    throws ServiceFailure, McdbDocNotFoundException, PropertyNotFoundException, InvalidToken, NotAuthorized,
307
    NotFound, NotImplemented, InvalidRequest, NoSuchAlgorithmException, AccessionNumberException, SQLException 
308
    {
309
    	logCrud.debug("CrudService.generateMissingSystemMetadata() called.");
310
        logCrud.debug("Creating SystemMetadata for localId " + localId);
311
        SystemMetadata sm = null;
312

    
313
        //generate required system metadata fields from the document
314
        try {
315
        	sm = createSystemMetadata(localId, token);
316
        } catch (IOException e1) {
317
        	e1.printStackTrace();
318
        	ServiceFailure sf = new ServiceFailure("00","IOException in generateMissingSystemMetadata: " +
319
        			e1.getMessage());
320
        	sf.setStackTrace(e1.getStackTrace());
321
        	throw sf;
322
        }
323
        
324
        //insert the systemmetadata object
325
        SessionData sessionData = getSessionData(token);
326
        String smlocalid = insertSystemMetadata(sm, sessionData);
327
        logCrud.debug("setting access on SM doc with localid " + smlocalid);
328
        try {
329
        	handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid, "public", "4", "allow", "allowFirst");
330
        } catch (Exception e) {
331
        	logCrud.debug("Unspecified exception thrown by MetacatHandler.setAccess(): " + e.getMessage());
332
        	logMetacat.error("Could not generate missing systemMetadata: " + e.getMessage());
333
        	logMetacat.error(e.getStackTrace());
334
        	ServiceFailure sf = new ServiceFailure("0","Unspecified exception thrown by MetacatHandler.setAccess(): " + e.getMessage());
335
        	sf.setStackTrace(e.getStackTrace());
336
        	throw sf;
337
        }
338

    
339
        String username = "public";
340
        if (sessionData != null) {
341
        	username = sessionData.getUserName();
342
        }
343
        EventLog.getInstance().log(metacatUrl, username, localId, "generateMissingSystemMetadata");
344

    
345
//        catch (Exception e) { // TODO: Please don't catch Exception -- it masks bad things
346
//            e.printStackTrace();
347
//            logCrud.debug("Exception generating missing system metadata: " + e.getMessage());
348
//            logMetacat.error("Could not generate missing system metadata: " + e.getMessage());
349
//        }
350
        logCrud.info("generateMissingSystemMetadata(token, localId)");
351
    }
352
    
353
    /**
354
     * create an object via the crud interface
355
     */
356
    public Identifier create(AuthToken token, Identifier guid, 
357
            InputStream object, SystemMetadata sysmeta) throws InvalidToken, 
358
            ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
359
            InsufficientResources, InvalidSystemMetadata, NotImplemented {
360
        logMetacat.debug("Starting CrudService.create()...");
361
        
362
        // authenticate & get user info
363
        SessionData sessionData = getSessionData(token);
364
        String username = "public";
365
        String[] groups = null;
366
        if(sessionData != null)
367
        {
368
            username = sessionData.getUserName();
369
            groups = sessionData.getGroupNames();
370
        }
371
        String localId = null;
372

    
373
        if (username == null || username.equals("public"))
374
        {
375
            //TODO: many of the thrown exceptions do not use the correct error codes
376
            //check these against the docs and correct them
377
            throw new NotAuthorized("1100", "User " + username + " is not authorized to create content." +
378
                    "  If you are not logged in, please do so and retry the request.");
379
        }
380
        
381
        // verify that guid == SystemMetadata.getIdentifier()
382
        logMetacat.debug("Comparing guid|sysmeta_guid: " + guid.getValue() + "|" + sysmeta.getIdentifier().getValue());
383
        if (!guid.getValue().equals(sysmeta.getIdentifier().getValue())) {
384
            throw new InvalidSystemMetadata("1180", 
385
                "GUID in method call (" + guid.getValue() + ") does not match GUID in system metadata (" +
386
                sysmeta.getIdentifier().getValue() + ").");
387
        }
388

    
389
        logMetacat.debug("Checking if identifier exists...");
390
        // Check that the identifier does not already exist
391
        IdentifierManager im = IdentifierManager.getInstance();
392
        if (im.identifierExists(guid.getValue())) {
393
            throw new IdentifierNotUnique("1120", 
394
                "GUID is already in use by an existing object.");
395
        }
396

    
397
        // Check if we are handling metadata or data
398
        boolean isScienceMetadata = isScienceMetadata(sysmeta);
399
        
400
        if (isScienceMetadata) {
401
            // CASE METADATA:
402
            try {
403
                //logCrud.debug("CrudService: inserting document with guid " + guid.getValue());
404
                this.insertDocument(object, guid, sessionData);
405
                localId = im.getLocalId(guid.getValue());
406
            } catch (IOException e) {
407
                String msg = "Could not create string from XML stream: " +
408
                    " " + e.getMessage();
409
                logMetacat.debug(msg);
410
                throw new ServiceFailure("1190", msg);
411
            } catch(Exception e) {
412
                String msg = "Unexpected error in CrudService.create: " + e.getMessage();
413
                logMetacat.debug(msg);
414
                throw new ServiceFailure("1190", msg);
415
            }
416
            
417

    
418
        } else {
419
            // DEFAULT CASE: DATA (needs to be checked and completed)
420
            localId = insertDataObject(object, guid, sessionData);
421
            
422
        }
423

    
424
        // For Metadata and Data, insert the system metadata into the object store too
425
        String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
426
        //get the document info.  add any access params for the sysmeta too
427
        //logCrud.debug("looking for access records to add for system " +
428
        //    "metadata who's parent doc's  local id is " + localId);
429
        try
430
        {
431
            Hashtable<String, Object> h = im.getDocumentInfo(localId.substring(0, localId.lastIndexOf(".")));
432
            Vector v = (Vector)h.get("access");
433
            for(int i=0; i<v.size(); i++)
434
            {
435
                @SuppressWarnings("unchecked")
436
                Hashtable<String, String> ah = (Hashtable<String, String>)v.elementAt(i);
437
                String principal = (String)ah.get("principal_name");
438
                String permission = (String)ah.get("permission");
439
                String permissionType = (String)ah.get("permission_type");
440
                String permissionOrder = (String)ah.get("permission_order");
441
                int perm = new Integer(permission).intValue();
442
                //logCrud.debug("found access record for principal " + principal);
443
                //logCrud.debug("permission: " + perm + " perm_type: " + permissionType + 
444
                //    " perm_order: " + permissionOrder);
445
                this.setAccess(token, guid, principal, perm, permissionType, permissionOrder, true);
446
            }
447
        }
448
        catch(Exception e)
449
        {
450
            logMetacat.error("Error setting permissions on System Metadata object " + 
451
                    " with id " + sysMetaLocalId + ": " + e.getMessage());
452
            //TODO: decide if this error should cancel the entire create or
453
            //if it should continue with just a logged error.
454
        }
455
        
456
        
457
        logMetacat.debug("Returning from CrudService.create()");
458
        EventLog.getInstance().log(metacatUrl,
459
                username, localId, "create");
460
        logCrud.info("create D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
461
                ":D1SYSMETADATA:"+ sysMetaLocalId + ":");
462
        return guid;
463
    }
464
    
465
    /**
466
     * update an existing object with a new object.  Change the system metadata
467
     * to reflect the changes and update it as well.
468
     */
469
    public Identifier update(AuthToken token, Identifier guid, 
470
            InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
471
            throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
472
            UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
473
            NotImplemented {
474
    	try
475
    	{
476
    		SessionData sessionData = getSessionData(token);
477
            
478
            //find the old systemmetadata (sm.old) document id (the one linked to obsoletedGuid)
479
            SystemMetadata sm = getSystemMetadata(token, obsoletedGuid);
480
            //change sm.old's obsoletedBy field 
481
            List<Identifier> l = sm.getObsoletedByList();
482
            l.add(guid);
483
            sm.setObsoletedByList(l);
484
            //update sm.old
485
            updateSystemMetadata(sm, sessionData);
486
            
487
            //change the obsoletes field of the new systemMetadata (sm.new) to point to the id of the old one
488
            sysmeta.addObsolete(obsoletedGuid);
489
            //insert sm.new
490
            String sysMetaLocalId = insertSystemMetadata(sysmeta, sessionData);
491
            String localId;
492
            
493
            boolean isScienceMetadata = isScienceMetadata(sysmeta);
494
            if(isScienceMetadata)
495
            {
496
                //update the doc
497
                localId = updateDocument(object, obsoletedGuid, guid, sessionData, false);
498
            }
499
            else
500
            {
501
                //update a data file, not xml
502
                localId = insertDataObject(object, guid, sessionData);
503
            }
504
            
505
            IdentifierManager im = IdentifierManager.getInstance();
506
            String username = "public";
507
            if(sessionData != null)
508
            {
509
                username = sessionData.getUserName();
510
            }
511
            EventLog.getInstance().log(metacatUrl,
512
                    username, im.getLocalId(guid.getValue()), "update");
513
            logCrud.info("update D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
514
                    ":D1SYSMETADATA:"+ sysMetaLocalId + ":");
515
            return guid;
516
        }
517

    
518
    	catch(IOException e) {
519
            throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
520
        }
521
    	catch( McdbDocNotFoundException e) {
522
    		throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
523
    	}
524
    	catch( InvalidRequest e) {
525
    		throw new ServiceFailure("1310", "Error updating document in CrudService: " + e.getMessage());
526
    	}
527
    }
528
    
529
    /**
530
     * set access permissions on both the science metadata and system metadata
531
     */
532
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
533
            String permissionType, String permissionOrder)
534
      throws ServiceFailure
535
    {
536
        setAccess(token, id, principal, permission, permissionType, permissionOrder, true);
537
    }
538
    
539
    /**
540
     * set access control on the doc
541
     * @param token
542
     * @param id
543
     * @param principal
544
     * @param permission
545
     */
546
    public void setAccess(AuthToken token, Identifier id, String principal, int permission,
547
      String permissionType, String permissionOrder, boolean setSystemMetadata)
548
      throws ServiceFailure
549
    {
550
        String perm = "";
551
        if(permission >= 4)
552
        {
553
            perm = "read";
554
        }
555
        if(permission >= 6)
556
        {
557
            perm = "write";
558
        }
559
        //logCrud.debug("perm in setAccess: " + perm);
560
        //logCrud.debug("permission in setAccess: " + permission);
561
        setAccess(token, id, principal, perm, permissionType, permissionOrder,
562
                setSystemMetadata);
563
       
564
    }
565
    
566
    /**
567
     * set the permission on the document
568
     * @param token
569
     * @param principal
570
     * @param permission
571
     * @param permissionType
572
     * @param permissionOrder
573
     * @return
574
     */
575
    public void setAccess(AuthToken token, Identifier id, String principal, String permission,
576
            String permissionType, String permissionOrder, boolean setSystemMetadata)
577
      throws ServiceFailure
578
    {
579
        /* TODO:
580
         * This is also not part of the D1 Crud spec.  This method is needed for
581
         * systems such as metacat where access to objects is controlled by
582
         * and ACL.  Higher level decisions need to be made about how this
583
         * should work within D1.
584
         */
585
        try
586
        {
587
            final SessionData sessionData = getSessionData(token);
588
            if(sessionData == null)
589
            {
590
                throw new ServiceFailure("1000", "User must be logged in to set access.");
591
            }
592
            IdentifierManager im = IdentifierManager.getInstance();
593
            String docid = im.getLocalId(id.getValue());
594
        
595
            String permNum = "0";
596
            if(permission.equals("read"))
597
            {
598
                permNum = "4";
599
            }
600
            else if(permission.equals("write"))
601
            {
602
                permNum = "6";
603
            }
604
            logCrud.debug("user " + sessionData.getUserName() + 
605
                    " is setting access level " + permNum + " for permission " + 
606
                    permissionType + " on doc with localid " + docid);
607
            handler.setAccess(metacatUrl, sessionData.getUserName(), docid, 
608
                    principal, permNum, permissionType, permissionOrder);
609
            if(setSystemMetadata)
610
            {
611
                //set the same perms on the system metadata doc
612
                String smlocalid = im.getSystemMetadataLocalId(id.getValue());
613
                logCrud.debug("setting access on SM doc with localid " + smlocalid);
614
                //cs.setAccess(token, smid, principal, permission, permissionType, permissionOrder);
615
                handler.setAccess(metacatUrl, sessionData.getUserName(), smlocalid,
616
                        principal, permNum, permissionType, permissionOrder);
617
            }
618
            String username = "public";
619
            if(sessionData != null)
620
            {
621
                username = sessionData.getUserName();
622
            }
623
            EventLog.getInstance().log(metacatUrl,
624
                    username, im.getLocalId(id.getValue()), "setAccess");
625
            logCrud.info("setAccess");
626
        }
627
        catch(Exception e)
628
        {
629
            e.printStackTrace();
630
            throw new ServiceFailure("1000", "Could not set access on the document with id " + id.getValue());
631
        }
632
    }
633
    
634
    /**
635
     *  Retrieve the list of objects present on the MN that match the calling 
636
     *  parameters. This method is required to support the process of Member 
637
     *  Node synchronization. At a minimum, this method should be able to 
638
     *  return a list of objects that match:
639
     *  startTime <= SystemMetadata.dateSysMetadataModified
640
     *  but is expected to also support date range (by also specifying endTime), 
641
     *  and should also support slicing of the matching set of records by 
642
     *  indicating the starting index of the response (where 0 is the index 
643
     *  of the first item) and the count of elements to be returned.
644
     *  
645
     *  If startTime or endTime is null, the query is not restricted by that parameter.
646
     *  
647
     * @see http://mule1.dataone.org/ArchitectureDocs/mn_api_replication.html#MN_replication.listObjects
648
     * @param token
649
     * @param startTime
650
     * @param endTime
651
     * @param objectFormat
652
     * @param replicaStatus
653
     * @param start
654
     * @param count
655
     * @return ObjectList
656
     * @throws NotAuthorized
657
     * @throws InvalidRequest
658
     * @throws NotImplemented
659
     * @throws ServiceFailure
660
     * @throws InvalidToken
661
     */
662
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
663
        ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
664
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
665
    {
666
      //ObjectList ol = new ObjectList();
667
      //final SessionData sessionData = getSessionData(token);
668
      //int totalAfterQuery = 0;
669
      
670
      
671
      return IdentifierManager.getInstance().querySystemMetadata(startTime, endTime,
672
              objectFormat, replicaStatus, start, count);
673
      
674
      
675
      /////////////////////////////////////////////////////////////////////////
676
      ///////////////// OLD CODE //////////////////////////////////////////////
677
      /////////////////////////////////////////////////////////////////////////
678
      
679
//      try
680
//      {
681
//          if (PropertyService.getProperty("database.queryCacheOn").equals("true"))
682
//          {
683
//              //System.out.println("the string stored into cache is "+ resultsetBuffer.toString());
684
//              DBQuery.clearQueryResultCache();
685
//          }
686
//      }
687
//      catch (PropertyNotFoundException e1)
688
//      {
689
//          //just don't do anything
690
//      }
691
//      
692
//      try
693
//      {
694
//          //TODO: Milliseconds need to be added to the dateFormat
695
//          System.out.println("=========== Listing Objects =============");
696
//          System.out.println("Current server time is: " + new Date());
697
//          if(startTime != null)
698
//          {
699
//              System.out.println("query start time is " + startTime);
700
//          }
701
//          if(endTime != null)
702
//          {
703
//              System.out.println("query end time is " + endTime);
704
//          }
705
//          params.clear();
706
//          params.put("qformat", new String[] {PropertyService.getProperty("crudService.listObjects.QFormat")});
707
//          params.put("action", new String[] {"squery"});
708
//          params.put("query", new String[] {createListObjectsPathQueryDocument()});
709
//          
710
//          /*System.out.println("query is: metacatUrl: " + metacatUrl + " user: " + sessionData.getUserName() +
711
//                  " sessionid: " + sessionData.getId() + " params: ");
712
//          String url = metacatUrl + "/metacat?action=query&sessionid=" + sessionData.getId();
713
//          Enumeration keys = params.keys();
714
//          while(keys.hasMoreElements())
715
//          {
716
//              String key = (String)keys.nextElement();
717
//              String[] parr = params.get(key);
718
//              for(int i=0; i<parr.length; i++)
719
//              {
720
//                  System.out.println("param " + key + ": " + parr[i]);
721
//                  url += "&" + key + "=" + parr[i] ;
722
//              }
723
//          }
724
//          System.out.println("query url: " + url);
725
//          */
726
//          String username = "public";
727
//          String[] groups = null;
728
//          String sessionid = "";
729
//          if(sessionData != null)
730
//          {
731
//              username = sessionData.getUserName();
732
//              groups = sessionData.getGroupNames();
733
//              sessionid = sessionData.getId();
734
//          }
735
//          
736
//          MetacatResultSet rs = handler.query(metacatUrl, params, username, 
737
//                  groups, sessionid);
738
//          List docs = rs.getDocuments();
739
//          
740
//          System.out.println("query returned " + docs.size() + " documents.");
741
//          Vector<Document> docCopy = new Vector<Document>();
742
//          
743
//          //preparse the list to remove any that don't match the query params
744
//          /* TODO: this type of query/subquery processing is probably not scalable
745
//           * to larger object stores.  This code should be revisited.  The metacat
746
//           * query handler should probably be altered to handle the type of query 
747
//           * done here.
748
//           */ 
749
//          for(int i=0; i<docs.size(); i++)
750
//          {
751
//              Document d = (Document)docs.get(i);
752
//              
753
//              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
754
//              
755
//              if(returnedObjectFormat != null && 
756
//                 objectFormat != null && 
757
//                 !objectFormat.toString().trim().equals(returnedObjectFormat.toString().trim()))
758
//              { //make sure the objectFormat is the one specified
759
//                  continue;
760
//              }
761
//              
762
//              String dateSMM = d.getField("dateSysMetadataModified");
763
//              if((startTime != null || endTime != null) && dateSMM == null)
764
//              {  //if startTime or endTime are not null, we need a date to compare to
765
//                  continue;
766
//              }
767
//              
768
//              //date parse
769
//              Date dateSysMetadataModified = null;
770
//              if(dateSMM != null)
771
//              {
772
//
773
//                  /*                  
774
//                  if(dateSMM.indexOf(".") != -1)
775
//                  {  //strip the milliseconds
776
//                      //TODO: don't do this. we need milliseconds now.
777
//                      //TODO: explore ISO 8601 to figure out milliseconds
778
//                      dateSMM = dateSMM.substring(0, dateSMM.indexOf(".")) + 'Z';
779
//                  }
780
//                  */
781
//                  //System.out.println("dateSMM: " + dateSMM);
782
//                  //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-0"));
783
//                  try
784
//                  {   //the format we want
785
//                      dateSysMetadataModified = dateFormat.parse(dateSMM);
786
//                  }
787
//                  catch(java.text.ParseException pe)
788
//                  {   //try another legacy format
789
//                      try
790
//                      {
791
//                          DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.S'Z'");
792
//                          dateFormat2.setTimeZone(TimeZone.getTimeZone("GMT-0"));
793
//                          dateSysMetadataModified = dateFormat2.parse(dateSMM);
794
//                      }
795
//                      catch(java.text.ParseException pe2)
796
//                      {
797
//                          //try another legacy format
798
//                          DateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
799
//                          dateFormat3.setTimeZone(TimeZone.getTimeZone("GMT-0"));
800
//                          dateSysMetadataModified = dateFormat3.parse(dateSMM);
801
//                      }
802
//                      
803
//                  }                  
804
//              }
805
//              
806
//              /*System.out.println("====================================");
807
//              System.out.println("doc number " + i);
808
//              System.out.println("docid: " + d.docid);
809
//              System.out.println("guid: " + d.getField("identifier").trim());
810
//              System.out.println("dateSMM: " + dateSMM);
811
//              System.out.println("dateSysMetadataModified: " + dateSysMetadataModified);
812
//              System.out.println("startTime: " + startTime);
813
//              System.out.println("endtime: " + endTime);*/
814
//              
815
//              int startDateComparison = 0;
816
//              int endDateComparison = 0;
817
//              if(startTime != null)
818
//              {
819
//                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
820
//                  zTime.setTime(startTime);
821
//                  startTime = zTime.getTime();
822
//                  
823
//                  if(dateSysMetadataModified == null)
824
//                  {
825
//                      startDateComparison = -1;
826
//                  }
827
//                  else
828
//                  {
829
//                      startDateComparison = dateSysMetadataModified.compareTo(startTime);
830
//                  }
831
//                  //System.out.println("startDateCom: " + startDateComparison);
832
//              }
833
//              else
834
//              {
835
//                  startDateComparison = 1;
836
//              }
837
//              
838
//              if(endTime != null)
839
//              {
840
//                  Calendar zTime = Calendar.getInstance(TimeZone.getTimeZone("GMT-0"));
841
//                  zTime.setTime(endTime);
842
//                  endTime = zTime.getTime();
843
//                  
844
//                  if(dateSysMetadataModified == null)
845
//                  {
846
//                      endDateComparison = 1;
847
//                  }
848
//                  else
849
//                  {
850
//                      endDateComparison = dateSysMetadataModified.compareTo(endTime);
851
//                  }
852
//                  //System.out.println("endDateCom: " + endDateComparison);
853
//              }
854
//              else
855
//              {
856
//                  endDateComparison = -1;
857
//              }
858
//              
859
//              
860
//              if(startDateComparison < 0 || endDateComparison > 0)
861
//              { 
862
//                  continue;                  
863
//              }
864
//              
865
//              docCopy.add((Document)docs.get(i));
866
//          } //end pre-parse
867
//          
868
//          docs = docCopy;
869
//          totalAfterQuery = docs.size();
870
//          //System.out.println("total after subquery: " + totalAfterQuery);
871
//          
872
//          //make sure we don't run over the end
873
//          int end = start + count;
874
//          if(end > docs.size())
875
//          {
876
//              end = docs.size();
877
//          }
878
//          
879
//          for(int i=start; i<end; i++)
880
//          {
881
//              //get the document from the result
882
//              Document d = (Document)docs.get(i);
883
//              //System.out.println("processing doc " + d.docid);
884
//              
885
//              String dateSMM = d.getField("dateSysMetadataModified");
886
//              //System.out.println("dateSMM: " + dateSMM);
887
//              //System.out.println("parsed date: " + parseDate(dateSMM));
888
//              Date dateSysMetadataModified = null;
889
//              if(dateSMM != null)
890
//              {
891
//                  try
892
//                  {
893
//                      dateSysMetadataModified = parseDate(dateSMM);
894
//                  }
895
//                  catch(Exception e)
896
//                  { //if we fail to parse the date, just ignore the value
897
//                      dateSysMetadataModified = null;
898
//                  }
899
//              }
900
//              ObjectFormat returnedObjectFormat = ObjectFormat.convert(d.getField("objectFormat"));
901
//                
902
//              
903
//              ObjectInfo info = new ObjectInfo();
904
//              //add the fields to the info object
905
//              Checksum cs = new Checksum();
906
//              cs.setValue(d.getField("checksum"));
907
//              String csalg = d.getField("algorithm");
908
//              if(csalg == null)
909
//              {
910
//                  csalg = "MD5";
911
//              }
912
//              ChecksumAlgorithm ca = ChecksumAlgorithm.convert(csalg);
913
//              cs.setAlgorithm(ca);
914
//              info.setChecksum(cs);
915
//              info.setDateSysMetadataModified(dateSysMetadataModified);
916
//              Identifier id = new Identifier();
917
//              id.setValue(d.getField("identifier").trim());
918
//              info.setIdentifier(id);
919
//              info.setObjectFormat(returnedObjectFormat);
920
//              String size = d.getField("size");
921
//              if(size != null)
922
//              {
923
//                  info.setSize(new Long(size.trim()).longValue());
924
//              }
925
//              //add the ObjectInfo to the ObjectList
926
//              //logCrud.info("objectFormat: " + info.getObjectFormat().toString());
927
//              //logCrud.info("id: " + info.getIdentifier().getValue());
928
//              
929
//              if(info.getIdentifier().getValue() != null)
930
//              { //id can be null from tests.  should not happen in production.
931
//                  if((info.getObjectFormat() != null && !info.getObjectFormat().toString().trim().equals("")))
932
//                  { //objectFormat needs to not be null and not be an empty string
933
//                    ol.addObjectInfo(info);
934
//                  }
935
//                  else
936
//                  {
937
//                      logCrud.info("Not adding object with null objectFormat" + info.getIdentifier().getValue().toString());
938
//                  }
939
//              }
940
//             
941
//          }
942
//      }
943
//      catch(Exception e)
944
//      {
945
//          e.printStackTrace();
946
//          logCrud.error("Error creating ObjectList: " + e.getMessage() + " cause: " + e.getCause());
947
//          throw new ServiceFailure("1580", "Error retrieving ObjectList: " + e.getMessage());
948
//      }
949
//      String username = "public";
950
//      if(sessionData != null)
951
//      {
952
//          username = sessionData.getUserName();
953
//      }
954
//      EventLog.getInstance().log(metacatUrl,
955
//              username, null, "read");
956
//      logCrud.info("listObjects");
957
//      if(totalAfterQuery < count)
958
//      {
959
//          count = totalAfterQuery;
960
//      }
961
//      ol.setCount(count);
962
//      ol.setStart(start);
963
//      ol.setTotal(totalAfterQuery);
964
//      return ol;
965
    }
966
    
967
    /**
968
     * Call listObjects with the default values for replicaStatus (true), start (0),
969
     * and count (1000).
970
     * @param token
971
     * @param startTime
972
     * @param endTime
973
     * @param objectFormat
974
     * @return
975
     * @throws NotAuthorized
976
     * @throws InvalidRequest
977
     * @throws NotImplemented
978
     * @throws ServiceFailure
979
     * @throws InvalidToken
980
     */
981
    public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
982
        ObjectFormat objectFormat)
983
      throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
984
    {
985
       return listObjects(token, startTime, endTime, objectFormat, true, 0, 1000);
986
    }
987

    
988
    /**
989
     * Delete a document. 
990
     */
991
    public Identifier delete(AuthToken token, Identifier guid)
992
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
993
            NotImplemented, InvalidRequest {
994
        logCrud.info("delete");
995
        
996
        if(token == null || token.getToken().equals("publid"))
997
        {
998
            throw new NotAuthorized("1320", "You must be logged in to delete records.");
999
        }
1000
        
1001
        if(guid == null || guid.getValue().trim().equals(""))
1002
        {
1003
            throw new InvalidRequest("1322", "No GUID specified in CrudService.delete()");
1004
        }
1005
        final SessionData sessionData = getSessionData(token);
1006
        IdentifierManager manager = IdentifierManager.getInstance();
1007
        
1008
        String docid;
1009
        try
1010
        {
1011
            docid = manager.getLocalId(guid.getValue());
1012
        }
1013
        catch(McdbDocNotFoundException mnfe)
1014
        {
1015
            throw new InvalidRequest("1322", "GUID " + guid + " not found.");
1016
        }
1017
        
1018
        try
1019
        {
1020
            DocumentImpl.delete(docid, sessionData.getUserName(), sessionData.getGroupNames(), null);
1021
        }
1022
        catch(SQLException e)
1023
        {
1024
            throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
1025
        }
1026
        catch(McdbDocNotFoundException e)
1027
        {
1028
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
1029
        }
1030
        catch(InsufficientKarmaException e)
1031
        {
1032
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
1033
        }
1034
        catch(Exception e)
1035
        {
1036
          throw new ServiceFailure("1350", "Could not delete document: " + e.getMessage());
1037
        }
1038
        return guid;
1039
    }
1040

    
1041
    /**
1042
     * describe a document.  
1043
     */
1044
    public DescribeResponse describe(AuthToken token, Identifier guid)
1045
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1046
            NotImplemented, InvalidRequest {
1047
        logCrud.info("describe");
1048
        
1049
        if(token == null)
1050
        {
1051
            throw new InvalidToken("1370", "Authentication token is null");
1052
        }
1053
        
1054
        if(guid == null || guid.getValue().trim().equals(""))
1055
        {
1056
            throw new InvalidRequest("1362", "Guid is null.  A valid guid is required.");
1057
        }
1058
        
1059
        SystemMetadata sm = getSystemMetadata(token, guid);
1060
        DescribeResponse dr = new DescribeResponse(sm.getObjectFormat(), 
1061
                sm.getSize(), sm.getDateSysMetadataModified(), sm.getChecksum());
1062
        return dr;
1063
    }
1064
    
1065
    /**
1066
     * get a document with a specified guid.
1067
     */
1068
    public InputStream get(AuthToken token, Identifier guid)
1069
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1070
            NotImplemented {
1071
        
1072
        // Retrieve the session information from the AuthToken
1073
        // If the session is expired, then the user is 'public'
1074
        if(token == null)
1075
        {
1076
            token = new AuthToken("Public");
1077
        }
1078
        final SessionData sessionData = getSessionData(token);
1079
        
1080
        // Look up the localId for this global identifier
1081
        IdentifierManager im = IdentifierManager.getInstance();
1082
        
1083
        try 
1084
        {
1085
            final String localId = im.getLocalId(guid.getValue());
1086
            InputStream objectStream;
1087
            try 
1088
            {
1089
                String username = "public";
1090
                String[] groups = new String[0];
1091
                if(sessionData != null)
1092
                {
1093
                    username = sessionData.getUserName();
1094
                    groups = sessionData.getGroupNames();
1095
                }
1096
                
1097
                objectStream = readFromMetacat(localId, username, groups);
1098
                
1099
            } catch (PropertyNotFoundException e) {
1100
                e.printStackTrace();
1101
                throw new ServiceFailure("1030", "Error getting property from metacat: " + e.getMessage());
1102
            } catch (ClassNotFoundException e) {
1103
                e.printStackTrace();
1104
                throw new ServiceFailure("1030", "Class not found error when reading from metacat: " + e.getMessage());
1105
            } catch (IOException e) {
1106
                e.printStackTrace();
1107
                throw new ServiceFailure("1030", "IOException while reading from metacat: " + e.getMessage());
1108
            } catch (SQLException e) {
1109
                e.printStackTrace();
1110
                throw new ServiceFailure("1030", "SQLException while reading from metacat: " + e.getMessage());
1111
            } catch (McdbException e) {
1112
                e.printStackTrace();
1113
                throw new ServiceFailure("1030", "Metacat DB exception while reading from metacat: " + e.getMessage());
1114
            } catch (ParseLSIDException e) {
1115
                e.printStackTrace();
1116
                throw new NotFound("1020", "LSID parsing exception while reading from metacat: " + e.getMessage());
1117
            } catch (InsufficientKarmaException e) {
1118
                e.printStackTrace();
1119
                throw new NotAuthorized("1000", "User not authorized for get(): " + e.getMessage());
1120
            }
1121
        
1122
        
1123
            String username = "public";
1124
            if(sessionData != null)
1125
            {
1126
                username = sessionData.getUserName();
1127
            }
1128
            
1129
            EventLog.getInstance().log(metacatUrl,
1130
                    username, im.getLocalId(guid.getValue()), "read");
1131
            logCrud.info("get D1GUID:" + guid.getValue() + ":D1SCIMETADATA:" + localId + 
1132
                    ":");
1133
            
1134
            return objectStream;
1135
        } 
1136
        catch (McdbDocNotFoundException e) 
1137
        {
1138
            throw new NotFound("1020", e.getMessage());
1139
        } 
1140
    }
1141

    
1142
    /**
1143
     * get the checksum for a document.  defaults to MD5.
1144
     */
1145
    public Checksum getChecksum(AuthToken token, Identifier guid)
1146
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1147
            InvalidRequest, NotImplemented 
1148
    {
1149
        logCrud.info("getChecksum");
1150
        return getChecksum(token, guid, "MD5");
1151
    }
1152

    
1153
    /**
1154
     * get the checksum for a document with the given algorithm
1155
     */
1156
    public Checksum getChecksum(AuthToken token, Identifier guid, 
1157
            String checksumAlgorithm) throws InvalidToken, ServiceFailure, 
1158
            NotAuthorized, NotFound, InvalidRequest, NotImplemented 
1159
    {
1160
        logCrud.info("getChecksum");
1161
        SystemMetadata sm = getSystemMetadata(token, guid);
1162
        Checksum cs = sm.getChecksum();
1163
        if(cs.getAlgorithm().toString().equals(checksumAlgorithm))
1164
        {
1165
            return cs;
1166
        }
1167
        else
1168
        {
1169
            if(checksumAlgorithm == null)
1170
            {
1171
                checksumAlgorithm = "MD5";
1172
            }
1173
            InputStream docStream = get(token, guid);
1174
            String checksum;
1175
            try
1176
            {
1177
                checksum = checksum(docStream, checksumAlgorithm);
1178
            }
1179
            catch(Exception e)
1180
            {
1181
                throw new ServiceFailure("1410", "Error getting checksum: " + e.getMessage());
1182
            }
1183
            Checksum c = new Checksum();
1184
            c.setAlgorithm(ChecksumAlgorithm.convert(checksumAlgorithm));
1185
            c.setValue(checksum);
1186
            return c;
1187
        }
1188
    }
1189

    
1190
    /**
1191
     * get log records.  
1192
     */
1193
    public Log getLogRecords(AuthToken token, Date fromDate, Date toDate, Event event)
1194
            throws InvalidToken, ServiceFailure, NotAuthorized, InvalidRequest, 
1195
            NotImplemented 
1196
    {
1197
        /*System.out.println("=================== Getting log records ===================");
1198
        System.out.println("Current server time is: " + new Date());
1199
        if(fromDate != null)
1200
        {
1201
          System.out.println("query start time is " + fromDate);
1202
        }
1203
        if(toDate != null)
1204
        {
1205
          System.out.println("query end time is " + toDate);
1206
        }*/
1207
        Log log = new Log();
1208
        Vector<LogEntry> logs = new Vector<LogEntry>();
1209
        IdentifierManager im = IdentifierManager.getInstance();
1210
        EventLog el = EventLog.getInstance();
1211
        if(fromDate == null)
1212
        {
1213
            //System.out.println("setting fromdate from null");
1214
            fromDate = new Date(1);
1215
        }
1216
        if(toDate == null)
1217
        {
1218
            //System.out.println("setting todate from null");
1219
            toDate = new Date();
1220
        }
1221
        
1222
        //System.out.println("fromDate: " + fromDate);
1223
        //System.out.println("toDate: " + toDate);
1224
        
1225
        String report = el.getReport(null, null, null, null, 
1226
                new java.sql.Timestamp(fromDate.getTime()), 
1227
                new java.sql.Timestamp(toDate.getTime()), false);
1228
        
1229
        //System.out.println("report: " + report);
1230
        
1231
        String logEntry = "<logEntry>";
1232
        String endLogEntry = "</logEntry>";
1233
        int startIndex = 0;
1234
        int foundIndex = report.indexOf(logEntry, startIndex);
1235
        while(foundIndex != -1)
1236
        {
1237
            //parse out each entry
1238
            int endEntryIndex = report.indexOf(endLogEntry, foundIndex);
1239
            String entry = report.substring(foundIndex, endEntryIndex);
1240
            //System.out.println("entry: " + entry);
1241
            startIndex = endEntryIndex + endLogEntry.length();
1242
            foundIndex = report.indexOf(logEntry, startIndex);
1243
            
1244
            String entryId = getLogEntryField("entryid", entry);
1245
            String ipAddress = getLogEntryField("ipAddress", entry);
1246
            String principal = getLogEntryField("principal", entry);
1247
            String docid = getLogEntryField("docid", entry);
1248
            String eventS = getLogEntryField("event", entry);
1249
            String dateLogged = getLogEntryField("dateLogged", entry);
1250
            
1251
            LogEntry le = new LogEntry();
1252
            
1253
            Event e = Event.convert(eventS);
1254
            if(e == null)
1255
            { //skip any events that are not Dataone Crud events
1256
                continue;
1257
            }
1258
            le.setEvent(e);
1259
            Identifier entryid = new Identifier();
1260
            entryid.setValue(entryId);
1261
            le.setEntryId(entryid);
1262
            Identifier identifier = new Identifier();
1263
            try
1264
            {
1265
                //System.out.println("converting docid '" + docid + "' to a guid.");
1266
                if(docid == null || docid.trim().equals("") || docid.trim().equals("null"))
1267
                {
1268
                    continue;
1269
                }
1270
                docid = docid.substring(0, docid.lastIndexOf("."));
1271
                identifier.setValue(im.getGUID(docid, im.getLatestRevForLocalId(docid)));
1272
            }
1273
            catch(Exception ex)
1274
            { //try to get the guid, if that doesn't work, just use the local id
1275
                //throw new ServiceFailure("1030", "Error getting guid for localId " + 
1276
                //        docid + ": " + ex.getMessage());\
1277
                
1278
                //skip it if the guid can't be found
1279
                continue;
1280
            }
1281
            
1282
            le.setIdentifier(identifier);
1283
            le.setIpAddress(ipAddress);
1284
            Calendar c = Calendar.getInstance();
1285
            String year = dateLogged.substring(0, 4);
1286
            String month = dateLogged.substring(5, 7);
1287
            String date = dateLogged.substring(8, 10);
1288
            //System.out.println("year: " + year + " month: " + month + " day: " + date);
1289
            c.set(new Integer(year).intValue(), new Integer(month).intValue(), new Integer(date).intValue());
1290
            Date logDate = c.getTime();
1291
            le.setDateLogged(logDate);
1292
            NodeReference memberNode = new NodeReference();
1293
            memberNode.setValue(ipAddress);
1294
            le.setMemberNode(memberNode);
1295
            Subject princ = new Subject();
1296
            princ.setValue(principal);
1297
            le.setSubject(princ);
1298
            le.setUserAgent("metacat/RESTService");
1299
            
1300
            if(event == null)
1301
            {
1302
                logs.add(le);
1303
            }
1304
            
1305
            if(event != null &&
1306
               e.toString().toLowerCase().trim().equals(event.toString().toLowerCase().trim()))
1307
            {
1308
              logs.add(le);
1309
            }
1310
        }
1311
        
1312
        log.setLogEntryList(logs);
1313
        logCrud.info("getLogRecords");
1314
        return log;
1315
    }
1316
    
1317
    /**
1318
     * parse a logEntry and get the relavent field from it
1319
     * @param fieldname
1320
     * @param entry
1321
     * @return
1322
     */
1323
    private String getLogEntryField(String fieldname, String entry)
1324
    {
1325
        String begin = "<" + fieldname + ">";
1326
        String end = "</" + fieldname + ">";
1327
        //System.out.println("looking for " + begin + " and " + end + " in entry " + entry);
1328
        String s = entry.substring(entry.indexOf(begin) + begin.length(), entry.indexOf(end));
1329
        //System.out.println("entry " + fieldname + " : " + s);
1330
        return s;
1331
    }
1332

    
1333
    /**
1334
     * get the system metadata for a document with a specified guid.
1335
     */
1336
public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
1337
            throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
1338
            InvalidRequest, NotImplemented {
1339
        
1340
        logMetacat.debug("CrudService.getSystemMetadata - for guid: " + guid.getValue());
1341
        
1342
        // Retrieve the session information from the AuthToken
1343
        // If the session is expired, then the user is 'public'
1344
        final SessionData sessionData = getSessionData(token);
1345
                
1346
        try {
1347
            IdentifierManager im = IdentifierManager.getInstance();
1348
            final String localId = im.getSystemMetadataLocalId(guid.getValue());
1349
            InputStream objectStream;
1350
            
1351
            try {
1352
                String username = "public";
1353
                String[] groupnames = null;
1354
                if(sessionData != null)
1355
                {
1356
                    username = sessionData.getUserName();
1357
                    groupnames = sessionData.getGroupNames();
1358
                }
1359
                
1360
                objectStream = readFromMetacat(localId, username, groupnames);
1361
                
1362
            } catch (PropertyNotFoundException e) {
1363
                e.printStackTrace();
1364
                throw new ServiceFailure("1090", "Property not found while reading system metadata from metacat: " + e.getMessage());
1365
            } catch (ClassNotFoundException e) {
1366
                e.printStackTrace();
1367
                throw new ServiceFailure("1090", "Class not found while reading system metadata from metacat: " + e.getMessage());
1368
            } catch (IOException e) {
1369
                e.printStackTrace();
1370
                throw new ServiceFailure("1090", "IOException while reading system metadata from metacat: " + e.getMessage());
1371
            } catch (SQLException e) {
1372
                e.printStackTrace();
1373
                throw new ServiceFailure("1090", "SQLException while reading system metadata from metacat: " + e.getMessage());
1374
            } catch (McdbException e) {
1375
                e.printStackTrace();
1376
                throw new ServiceFailure("1090", "Metacat DB Exception while reading system metadata from metacat: " + e.getMessage());
1377
            } catch (ParseLSIDException e) {
1378
                e.printStackTrace();
1379
                throw new NotFound("1060", "Error parsing LSID while reading system metadata from metacat: " + e.getMessage());
1380
            } catch (InsufficientKarmaException e) {
1381
                e.printStackTrace();
1382
                throw new NotAuthorized("1040", "User not authorized for get() on system metadata: " + e.getMessage());
1383
            }
1384
                        
1385
            // Deserialize the xml to create a SystemMetadata object
1386
            SystemMetadata sysmeta = deserializeSystemMetadata(objectStream);
1387
            String username = "public";
1388
            if(sessionData != null)
1389
            {
1390
                username = sessionData.getUserName();
1391
            }
1392
            EventLog.getInstance().log(metacatUrl,
1393
                    username, im.getLocalId(guid.getValue()), "read");
1394
            logCrud.info("getsystemmetadata D1GUID:" + guid.getValue()  + 
1395
                    ":D1SYSMETADATA:"+ localId + ":");
1396
            return sysmeta;
1397
            
1398
        } catch (McdbDocNotFoundException e) {
1399
            //e.printStackTrace();
1400
            throw new NotFound("1040", e.getMessage());
1401
        }                
1402
    }
1403
    
1404
    /**
1405
     * parse the date in the systemMetadata
1406
     * @param s
1407
     * @return
1408
     * @throws Exception
1409
     */
1410
    public Date parseDate(String s)
1411
      throws Exception
1412
    {
1413
        /* TODO:
1414
         * This method should be replaced by a DateFormatter
1415
         */
1416
        Date d = null;
1417
        int tIndex = s.indexOf("T");
1418
        int zIndex = s.indexOf("Z");
1419
        if(tIndex != -1 && zIndex != -1)
1420
        { //parse a date that looks like 2010-05-18T21:12:54.362Z
1421
            //System.out.println("original date: " + s);
1422
            
1423
            String date = s.substring(0, tIndex);
1424
            String year = date.substring(0, date.indexOf("-"));
1425
            String month = date.substring(date.indexOf("-") + 1, date.lastIndexOf("-"));
1426
            String day = date.substring(date.lastIndexOf("-") + 1, date.length());
1427
            /*System.out.println("date: " + "year: " + new Integer(year).intValue() + 
1428
                    " month: " + new Integer(month).intValue() + " day: " + 
1429
                    new Integer(day).intValue());
1430
            */
1431
            String time = s.substring(tIndex + 1, zIndex);
1432
            String hour = time.substring(0, time.indexOf(":"));
1433
            String minute = time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"));
1434
            String seconds = "00";
1435
            String milliseconds = "00";
1436
            if(time.indexOf(".") != -1)
1437
            {
1438
                seconds = time.substring(time.lastIndexOf(":") + 1, time.indexOf("."));
1439
                milliseconds = time.substring(time.indexOf(".") + 1, time.length());
1440
            }
1441
            else
1442
            {
1443
                seconds = time.substring(time.lastIndexOf(":") + 1, time.length());
1444
            }
1445
            /*System.out.println("time: " + "hour: " + new Integer(hour).intValue() + 
1446
                    " minute: " + new Integer(minute).intValue() + " seconds: " + 
1447
                    new Integer(seconds).intValue() + " milli: " + 
1448
                    new Integer(milliseconds).intValue());*/
1449
            
1450
            //d = DateFormat.getDateTimeInstance().parse(date + " " + time);
1451
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-0")/*TimeZone.getDefault()*/);
1452
            c.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, 
1453
                  new Integer(day).intValue(), new Integer(hour).intValue(), 
1454
                  new Integer(minute).intValue(), new Integer(seconds).intValue());
1455
            c.set(Calendar.MILLISECOND, new Integer(milliseconds).intValue());
1456
            d = new Date(c.getTimeInMillis());
1457
            //System.out.println("d: " + d);
1458
            return d;
1459
        }
1460
        else
1461
        {  //if it's not in the expected format, try the formatter
1462
            return DateFormat.getDateTimeInstance().parse(s);
1463
        }
1464
    }
1465

    
1466
    /*
1467
     * Look up the information on the session using the token provided in
1468
     * the AuthToken.  The Session should have all relevant user information.
1469
     * If the session has expired or is invalid, the 'public' session will
1470
     * be returned, giving the user anonymous access.
1471
     */
1472
    public static SessionData getSessionData(AuthToken token) {
1473
        SessionData sessionData = null;
1474
        String sessionId = "PUBLIC";
1475
        if (token != null) {
1476
            sessionId = token.getToken();
1477
        }
1478
        
1479
        // if the session id is registered in SessionService, get the
1480
        // SessionData for it. Otherwise, use the public session.
1481
        //System.out.println("sessionid: " + sessionId);
1482
        if (sessionId != null &&
1483
            !sessionId.toLowerCase().equals("public") &&
1484
            SessionService.getInstance().isSessionRegistered(sessionId)) 
1485
        {
1486
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
1487
        } else {
1488
            sessionData = SessionService.getInstance().getPublicSession();
1489
        }
1490
        
1491
        return sessionData;
1492
    }
1493

    
1494
    /** 
1495
     * Determine if a given object should be treated as an XML science metadata
1496
     * object. 
1497
     * 
1498
     * TODO: This test should be externalized in a configuration dictionary rather than being hardcoded.
1499
     * 
1500
     * @param sysmeta the SystemMetadata describig the object
1501
     * @return true if the object should be treated as science metadata
1502
     */
1503
    private boolean isScienceMetadata(SystemMetadata sysmeta) {
1504
        /*boolean scimeta = false;
1505
        //TODO: this should be read from a .properties file instead of being hard coded
1506
        switch (sysmeta.getObjectFormat()) {
1507
            case EML_2_1_0: scimeta = true; break;
1508
            case EML_2_0_1: scimeta = true; break;
1509
            case EML_2_0_0: scimeta = true; break;
1510
            case FGDC_STD_001_1_1999: scimeta = true; break;
1511
            case FGDC_STD_001_1998: scimeta = true; break;
1512
            case NCML_2_2: scimeta = true; break;
1513
            case DSPACE_METS_SIP_1_0: scimeta = true; break;
1514
        }
1515
        
1516
        return scimeta;*/
1517
        
1518
        return MetadataTypeRegister.isMetadataType(sysmeta.getObjectFormat());
1519
    }
1520

    
1521
    /**
1522
     * insert a data doc
1523
     * @param object
1524
     * @param guid
1525
     * @param sessionData
1526
     * @throws ServiceFailure
1527
     * @returns localId of the data object inserted
1528
     */
1529
    private String insertDataObject(InputStream object, Identifier guid, 
1530
            SessionData sessionData) throws ServiceFailure {
1531
        
1532
        String username = "public";
1533
        String[] groups = null;
1534
        if(sessionData != null)
1535
        {
1536
          username = sessionData.getUserName();
1537
          groups = sessionData.getGroupNames();
1538
        }
1539

    
1540
        // generate guid/localId pair for object
1541
        logMetacat.debug("Generating a guid/localId mapping");
1542
        IdentifierManager im = IdentifierManager.getInstance();
1543
        String localId = im.generateLocalId(guid.getValue(), 1);
1544

    
1545
        try {
1546
            logMetacat.debug("Case DATA: starting to write to disk.");
1547
            if (DocumentImpl.getDataFileLockGrant(localId)) {
1548
    
1549
                // Save the data file to disk using "localId" as the name
1550
                try {
1551
                    String datafilepath = PropertyService.getProperty("application.datafilepath");
1552
    
1553
                    File dataDirectory = new File(datafilepath);
1554
                    dataDirectory.mkdirs();
1555
    
1556
                    File newFile = writeStreamToFile(dataDirectory, localId, object);
1557
    
1558
                    // TODO: Check that the file size matches SystemMetadata
1559
                    //                        long size = newFile.length();
1560
                    //                        if (size == 0) {
1561
                    //                            throw new IOException("Uploaded file is 0 bytes!");
1562
                    //                        }
1563
    
1564
                    // Register the file in the database (which generates an exception
1565
                    // if the localId is not acceptable or other untoward things happen
1566
                    try {
1567
                        logMetacat.debug("Registering document...");
1568
                        DocumentImpl.registerDocument(localId, "BIN", localId,
1569
                                username, groups);
1570
                        logMetacat.debug("Registration step completed.");
1571
                    } catch (SQLException e) {
1572
                        //newFile.delete();
1573
                        logMetacat.debug("SQLE: " + e.getMessage());
1574
                        e.printStackTrace(System.out);
1575
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1576
                    } catch (AccessionNumberException e) {
1577
                        //newFile.delete();
1578
                        logMetacat.debug("ANE: " + e.getMessage());
1579
                        e.printStackTrace(System.out);
1580
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1581
                    } catch (Exception e) {
1582
                        //newFile.delete();
1583
                        logMetacat.debug("Exception: " + e.getMessage());
1584
                        e.printStackTrace(System.out);
1585
                        throw new ServiceFailure("1190", "Registration failed: " + e.getMessage());
1586
                    }
1587
    
1588
                    logMetacat.debug("Logging the creation event.");
1589
                    EventLog.getInstance().log(metacatUrl,
1590
                            username, localId, "create");
1591
    
1592
                    // Schedule replication for this data file
1593
                    logMetacat.debug("Scheduling replication.");
1594
                    ForceReplicationHandler frh = new ForceReplicationHandler(
1595
                            localId, "create", false, null);
1596
    
1597
                } catch (PropertyNotFoundException e) {
1598
                    throw new ServiceFailure("1190", "Could not lock file for writing:" + e.getMessage());
1599
                }
1600
            }
1601
            return localId;
1602
        } catch (Exception e) {
1603
            // Could not get a lock on the document, so we can not update the file now
1604
            throw new ServiceFailure("1190", "Failed to lock file: " + e.getMessage());
1605
        }
1606
    }
1607

    
1608
    /**
1609
     * write a file to a stream
1610
     * @param dir
1611
     * @param fileName
1612
     * @param data
1613
     * @return
1614
     * @throws ServiceFailure
1615
     */
1616
    private File writeStreamToFile(File dir, String fileName, InputStream data) 
1617
        throws ServiceFailure {
1618
        
1619
        File newFile = new File(dir, fileName);
1620
        logMetacat.debug("Filename for write is: " + newFile.getAbsolutePath());
1621

    
1622
        try {
1623
            if (newFile.createNewFile()) {
1624
                // write data stream to desired file
1625
                OutputStream os = new FileOutputStream(newFile);
1626
                long length = IOUtils.copyLarge(data, os);
1627
                os.flush();
1628
                os.close();
1629
            } else {
1630
                logMetacat.debug("File creation failed, or file already exists.");
1631
                throw new ServiceFailure("1190", "File already exists: " + fileName);
1632
            }
1633
        } catch (FileNotFoundException e) {
1634
            logMetacat.debug("FNF: " + e.getMessage());
1635
            throw new ServiceFailure("1190", "File not found: " + fileName + " " 
1636
                    + e.getMessage());
1637
        } catch (IOException e) {
1638
            logMetacat.debug("IOE: " + e.getMessage());
1639
            throw new ServiceFailure("1190", "File was not written: " + fileName 
1640
                    + " " + e.getMessage());
1641
        }
1642

    
1643
        return newFile;
1644
    }
1645

    
1646
    /**
1647
     * insert a systemMetadata doc, return the localId of the sysmeta
1648
     */
1649
    private String insertSystemMetadata(SystemMetadata sysmeta, SessionData sessionData) 
1650
        throws ServiceFailure 
1651
    {
1652
        logMetacat.debug("Starting to insert SystemMetadata...");
1653
    
1654
        // generate guid/localId pair for sysmeta
1655
        Identifier sysMetaGuid = new Identifier();
1656
        sysMetaGuid.setValue(DocumentUtil.generateDocumentId(1));
1657
        sysmeta.setDateSysMetadataModified(new Date());
1658
        logCrud.debug("****inserting new system metadata with modified date " + 
1659
                sysmeta.getDateSysMetadataModified());
1660

    
1661
        String xml = new String(serializeSystemMetadata(sysmeta).toByteArray());
1662
        logCrud.debug("sysmeta: " + xml);
1663
        String localId = insertDocument(xml, sysMetaGuid, sessionData, true);
1664
        logCrud.debug("sysmeta inserted with localId " + localId);
1665
        //insert the system metadata doc id into the systemmetadata table to 
1666
        //link it to the data or metadata document
1667
        IdentifierManager.getInstance().createSystemMetadataMapping(
1668
                sysmeta, sysMetaGuid.getValue());
1669
        return localId;
1670
    }
1671
    
1672
    /**
1673
     * update a systemMetadata doc
1674
     */
1675
    private void updateSystemMetadata(SystemMetadata sm, SessionData sessionData)
1676
      throws ServiceFailure
1677
    {
1678
        
1679
        logCrud.debug("CrudService.updateSystemMetadata() called.");
1680
        try
1681
        {
1682
            String smId = IdentifierManager.getInstance().getSystemMetadataLocalId(sm.getIdentifier().getValue());
1683
            logCrud.debug("Setting date modified to " + new Date());
1684
            sm.setDateSysMetadataModified(new Date());
1685
            String xml = new String(serializeSystemMetadata(sm).toByteArray());
1686
            String localId = updateDocument(xml, sm.getIdentifier(), null, sessionData, true);
1687
            IdentifierManager.getInstance().updateSystemMetadataMapping(sm.getIdentifier().getValue(), localId);
1688
            IdentifierManager.getInstance().insertAdditionalSystemMetadataFields(
1689
              sm.getDateUploaded().getTime(), 
1690
              sm.getRightsHolder().getValue(),
1691
              sm.getChecksum().getValue(), 
1692
              /*sm.getChecksum().getAlgorithm().toString()*/sm.getChecksum().getAlgorithm().name(), 
1693
              sm.getOriginMemberNode().getValue(), 
1694
              sm.getAuthoritativeMemberNode().getValue(), 
1695
              sm.getDateSysMetadataModified().getTime(), 
1696
              sm.getSubmitter().getValue(), 
1697
              sm.getIdentifier().getValue(), 
1698
              sm.getObjectFormat().toString(), 
1699
              sm.getSize());
1700
                        
1701
        }
1702
        catch(Exception e)
1703
        {
1704
            throw new ServiceFailure("1030", "Error updating system metadata: " + e.getClass() + ": " + e.getMessage());
1705
        }
1706
    }
1707
    
1708
    private String insertDocument(String xml, Identifier guid, SessionData sessionData)
1709
        throws ServiceFailure
1710
    {
1711
        return insertDocument(xml, guid, sessionData, false);
1712
    }
1713
    
1714
    /**
1715
     * insert a document
1716
     * NOTE: this method shouldn't be used from the update or create() methods.  
1717
     * we shouldn't be putting the science metadata or data objects into memory.
1718
     */
1719
    private String insertDocument(String xml, Identifier guid, SessionData sessionData,
1720
            boolean isSystemMetadata)
1721
        throws ServiceFailure
1722
    {
1723
        return insertOrUpdateDocument(xml, guid, sessionData, "insert", isSystemMetadata);
1724
    }
1725
    
1726
    /**
1727
     * insert a document from a stream
1728
     */
1729
    private String insertDocument(InputStream is, Identifier guid, SessionData sessionData)
1730
      throws IOException, ServiceFailure
1731
    {
1732
        //HACK: change this eventually.  we should not be converting the stream to a string
1733
        String xml = IOUtils.toString(is);
1734
        return insertDocument(xml, guid, sessionData);
1735
    }
1736
    
1737
    /**
1738
     * update a document
1739
     * NOTE: this method shouldn't be used from the update or create() methods.  
1740
     * we shouldn't be putting the science metadata or data objects into memory.
1741
     */
1742
    private String updateDocument(String xml, Identifier obsoleteGuid, 
1743
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1744
        throws ServiceFailure
1745
    {
1746
        return insertOrUpdateDocument(xml, obsoleteGuid, sessionData, "update", isSystemMetadata);
1747
    }
1748
    
1749
    /**
1750
     * update a document from a stream
1751
     */
1752
    private String updateDocument(InputStream is, Identifier obsoleteGuid, 
1753
            Identifier guid, SessionData sessionData, boolean isSystemMetadata)
1754
      throws IOException, ServiceFailure
1755
    {
1756
        //HACK: change this eventually.  we should not be converting the stream to a string
1757
        String xml = IOUtils.toString(is);
1758
        String localId = updateDocument(xml, obsoleteGuid, guid, sessionData, isSystemMetadata);
1759
        IdentifierManager im = IdentifierManager.getInstance();
1760
        if(guid != null)
1761
        {
1762
          im.createMapping(guid.getValue(), localId);
1763
        }
1764
        return localId;
1765
    }
1766
    
1767
    /**
1768
     * insert a document, return the id of the document that was inserted
1769
     */
1770
    protected String insertOrUpdateDocument(String xml, Identifier guid, 
1771
            SessionData sessionData, String insertOrUpdate, boolean isSystemMetadata) 
1772
        throws ServiceFailure {
1773
        logMetacat.debug("Starting to insert xml document...");
1774
        IdentifierManager im = IdentifierManager.getInstance();
1775

    
1776
        // generate guid/localId pair for sysmeta
1777
        String localId = null;
1778
        if(insertOrUpdate.equals("insert"))
1779
        {
1780
            localId = im.generateLocalId(guid.getValue(), 1, isSystemMetadata);
1781
        }
1782
        else
1783
        {
1784
            //localid should already exist in the identifier table, so just find it
1785
            try
1786
            {
1787
                logCrud.debug("updating guid " + guid.getValue());
1788
                if(!isSystemMetadata)
1789
                {
1790
                    logCrud.debug("looking in identifier table for guid " + guid.getValue());
1791
                    localId = im.getLocalId(guid.getValue());
1792
                }
1793
                else
1794
                {
1795
                    logCrud.debug("looking in systemmetadata table for guid " + guid.getValue());
1796
                    localId = im.getSystemMetadataLocalId(guid.getValue());
1797
                }
1798
                logCrud.debug("localId: " + localId);
1799
                //increment the revision
1800
                String docid = localId.substring(0, localId.lastIndexOf("."));
1801
                String revS = localId.substring(localId.lastIndexOf(".") + 1, localId.length());
1802
                int rev = new Integer(revS).intValue();
1803
                rev++;
1804
                docid = docid + "." + rev;
1805
                localId = docid;
1806
                logCrud.debug("incremented localId: " + localId);
1807
            }
1808
            catch(McdbDocNotFoundException e)
1809
            {
1810
                throw new ServiceFailure("1030", "CrudService.insertOrUpdateDocument(): " +
1811
                    "guid " + guid.getValue() + " should have been in the identifier table, but it wasn't: " + e.getMessage());
1812
            }
1813
        }
1814
        logMetacat.debug("Metadata guid|localId: " + guid.getValue() + "|" +
1815
                localId);
1816

    
1817
        String[] action = new String[1];
1818
        action[0] = insertOrUpdate;
1819
        params.put("action", action);
1820
        String[] docid = new String[1];
1821
        docid[0] = localId;
1822
        params.put("docid", docid);
1823
        String[] doctext = new String[1];
1824
        doctext[0] = xml;
1825
        logMetacat.debug(doctext[0]);
1826
        params.put("doctext", doctext);
1827
        
1828
        // TODO: refactor handleInsertOrUpdateAction() to not output XML directly
1829
        // onto output stream, or alternatively, capture that and parse it to 
1830
        // generate the right exceptions
1831
        //ByteArrayOutputStream output = new ByteArrayOutputStream();
1832
        //PrintWriter pw = new PrintWriter(output);
1833
        String username = "public";
1834
        String[] groupnames = null;
1835
        if(sessionData != null)
1836
        {
1837
            username = sessionData.getUserName();
1838
            groupnames = sessionData.getGroupNames();
1839
        }
1840
        String result = handler.handleInsertOrUpdateAction(metacatUrl, null, 
1841
                            null, params, username, groupnames);
1842
        if(result.indexOf("<error>") != -1)
1843
        {
1844
            throw new ServiceFailure("1000", "Error inserting or updating document: " + result);
1845
        }
1846
        //String outputS = new String(output.toByteArray());
1847
        logMetacat.debug("CrudService.insertDocument - Metacat returned: " + result);
1848
        logMetacat.debug("Finsished inserting xml document with id " + localId);
1849
        return localId;
1850
    }
1851
    
1852
    /**
1853
     * serialize a dataone type
1854
     */
1855
//    private void serializeServiceType(Class type, Object object, OutputStream out)
1856
//        throws JiBXException
1857
//    {
1858
//        IBindingFactory bfact = BindingDirectory.getFactory(type);
1859
//        IMarshallingContext mctx = bfact.createMarshallingContext();
1860
//        mctx.marshalDocument(object, "UTF-8", null, out);
1861
//    }
1862
    
1863
    /**
1864
     * serialize a system metadata doc
1865
     * @param sysmeta
1866
     * @return
1867
     * @throws ServiceFailure
1868
     */
1869
    public static ByteArrayOutputStream serializeSystemMetadata(SystemMetadata sysmeta) 
1870
        throws ServiceFailure {
1871
        IBindingFactory bfact;
1872
        ByteArrayOutputStream sysmetaOut = null;
1873
        try {
1874
            bfact = BindingDirectory.getFactory(SystemMetadata.class);
1875
            IMarshallingContext mctx = bfact.createMarshallingContext();
1876
            sysmetaOut = new ByteArrayOutputStream();
1877
            mctx.marshalDocument(sysmeta, "UTF-8", null, sysmetaOut);
1878
        } catch (JiBXException e) {
1879
            e.printStackTrace();
1880
            throw new ServiceFailure("1190", "Failed to serialize and insert SystemMetadata: " + e.getMessage());
1881
        }
1882
        
1883
        return sysmetaOut;
1884
    }
1885
    
1886
    /**
1887
     * deserialize a system metadata doc
1888
     * @param xml
1889
     * @return
1890
     * @throws ServiceFailure
1891
     */
1892
    public static SystemMetadata deserializeSystemMetadata(InputStream xml) 
1893
        throws ServiceFailure {
1894
        try {
1895
            IBindingFactory bfact = BindingDirectory.getFactory(SystemMetadata.class);
1896
            IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
1897
            SystemMetadata sysmeta = (SystemMetadata) uctx.unmarshalDocument(xml, null);
1898
            return sysmeta;
1899
        } catch (JiBXException e) {
1900
            e.printStackTrace();
1901
            throw new ServiceFailure("1190", "Failed to deserialize and insert SystemMetadata: " + e.getMessage());
1902
        }    
1903
    }
1904
    
1905
    /**
1906
     * read a document from metacat and return the InputStream
1907
     * 
1908
     * @param localId
1909
     * @param username
1910
     * @param groups
1911
     * @return
1912
     * @throws InsufficientKarmaException
1913
     * @throws ParseLSIDException
1914
     * @throws PropertyNotFoundException
1915
     * @throws McdbException
1916
     * @throws SQLException
1917
     * @throws ClassNotFoundException
1918
     * @throws IOException
1919
     */
1920
    private InputStream readFromMetacat(String localId, String username, String[] groups)
1921
        throws InsufficientKarmaException, ParseLSIDException,
1922
        PropertyNotFoundException, McdbException, SQLException, 
1923
        ClassNotFoundException, IOException
1924
    {
1925
        File tmpDir;
1926
        try
1927
        {
1928
            tmpDir = new File(PropertyService.getProperty("application.tempDir"));
1929
        }
1930
        catch(PropertyNotFoundException pnfe)
1931
        {
1932
            logMetacat.error("ResourceHandler.writeMMPPartstoFiles: " +
1933
                    "application.tmpDir not found.  Using /tmp instead.");
1934
            tmpDir = new File("/tmp");
1935
        }
1936
        Date d = new Date();
1937
        final File outputFile = new File(tmpDir, "metacat.output." + d.getTime());
1938
        FileOutputStream dataSink = new FileOutputStream(outputFile);
1939
        
1940
        handler.readFromMetacat(metacatUrl, null, 
1941
                dataSink, localId, "xml",
1942
                username, 
1943
                groups, true, params);
1944
        
1945
        //set a timer to clean up the temp files
1946
        Timer t = new Timer();
1947
        TimerTask tt = new TimerTask() {
1948
            @Override
1949
            public void run()
1950
            {
1951
                outputFile.delete();
1952
            }
1953
        };
1954
        t.schedule(tt, 20000); //schedule after 20 secs
1955
        
1956
        InputStream objectStream = new FileInputStream(outputFile);
1957
        return objectStream;
1958
    }
1959
    
1960
    /**
1961
     * return an MD5 checksum for the stream
1962
     * @param is
1963
     * @return
1964
     * @throws IOException 
1965
     * @throws NoSuchAlgorithmException 
1966
     */
1967
    public static String checksum(InputStream is) throws NoSuchAlgorithmException, IOException
1968
    {
1969
        return checksum(is, "MD5");
1970
    }
1971
    
1972
    /**
1973
     * produce a checksum for item using the given algorithm
1974
     * @throws IOException 
1975
     * @throws NoSuchAlgorithmException 
1976
     */
1977
    public static String checksum(InputStream is, String algorithm) throws NoSuchAlgorithmException, IOException
1978
    {        
1979
        return ServiceTypeUtil.checksum(is, ChecksumAlgorithm.convert(algorithm)).getValue();
1980
    }
1981
    
1982
    /**
1983
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
1984
     * a proper date object
1985
     * @param date
1986
     * @return
1987
     */
1988
    private Date parseMetacatDate(String date)
1989
    {
1990
        String year = date.substring(0, 4);
1991
        String month = date.substring(5, 7);
1992
        String day = date.substring(8, 10);
1993
        Calendar c = Calendar.getInstance(TimeZone.getDefault());
1994
        c.set(new Integer(year).intValue(), 
1995
              new Integer(month).intValue(), 
1996
              new Integer(day).intValue());
1997
        logCrud.debug("time in parseMetacatDate: " + c.getTime());
1998
        return c.getTime();
1999
    }
2000
    
2001
    /**
2002
     * find the size (in bytes) of a stream
2003
     * @param is
2004
     * @return
2005
     * @throws IOException
2006
     */
2007
    private long sizeOfStream(InputStream is)
2008
        throws IOException
2009
    {
2010
        long size = 0;
2011
        byte[] b = new byte[1024];
2012
        int numread = is.read(b, 0, 1024);
2013
        while(numread != -1)
2014
        {
2015
            size += numread;
2016
            numread = is.read(b, 0, 1024);
2017
        }
2018
        return size;
2019
    }
2020
    
2021
    /**
2022
     * create system metadata with a specified id, doc and format
2023
     * @throws McdbDocNotFoundException 
2024
     * @throws SQLException
2025
     * @throws AccessionNumberException 
2026
     * @throws NumberFormatException 
2027
     * @throws IOException 
2028
     * @throws NoSuchAlgorithmException 
2029
     * @throws PropertyNotFoundException 
2030
     * @throws NotImplemented 
2031
     * @throws NotFound 
2032
     * @throws NotAuthorized 
2033
     * @throws InvalidToken 
2034
     * @throws InvalidRequest 
2035
     * @throws NoSuchAlgorithmException 
2036
     */
2037
    private SystemMetadata createSystemMetadata(String localId, AuthToken token) 
2038
    throws McdbDocNotFoundException, PropertyNotFoundException, AccessionNumberException, SQLException,
2039
    ServiceFailure, InvalidToken, NotAuthorized, NotFound, NotImplemented, InvalidRequest,
2040
    IOException, NoSuchAlgorithmException
2041
    {     
2042
    	logCrud.debug("CrudService.createSystemMetadata() called.");
2043

    
2044
    	IdentifierManager im = IdentifierManager.getInstance();
2045
    	Hashtable<String, Object> docInfo = im.getDocumentInfo(localId);
2046

    
2047
    	//get the document text
2048
    	int rev = im.getLatestRevForLocalId(localId);
2049
    	Identifier identifier = new Identifier();
2050
    	try {
2051
    		identifier.setValue(im.getGUID(localId, rev));
2052

    
2053
    	} catch (McdbDocNotFoundException mcdbe) { 
2054
    		//we're creating a new SM doc for a doc that is not in the identifier table                                       
2055
    		//so we need to add it to
2056
    		logCrud.debug("No guid in the identifier table.  adding it for " + localId);
2057
    		im.createMapping(localId, localId);
2058
    		logCrud.debug("Mapping created for " + localId);
2059
    		AccessionNumber accNum = new AccessionNumber(localId, "NONE");
2060
    		identifier.setValue(im.getGUID(accNum.getDocid(), rev));
2061
    	}
2062

    
2063
    	logCrud.debug("Creating system metadata for guid " + identifier.getValue());
2064
    	InputStream is = this.get(token, identifier);
2065
    	SystemMetadata sm = new SystemMetadata();
2066

    
2067
    	//set the id
2068
    	sm.setIdentifier(identifier);
2069

    
2070
    	//set the default object format
2071
    	String doctype = (String) docInfo.get("doctype");
2072
    	ObjectFormat format = ObjectFormat.convert(doctype);
2073
    	if (format == null) {
2074
    		if (doctype.trim().equals("BIN")) {
2075
    			format = ObjectFormat.OCTET_STREAM;
2076
    		} else {
2077
    			format = ObjectFormat.convert("text/plain");
2078
    		}
2079
    	}
2080
    	sm.setObjectFormat(format);
2081
    	logCrud.debug("The ObjectFormat for " + localId + " is " + format.toString());
2082

    
2083
    	// further parse EML documents to get data object format,
2084
    	// describes and describedBy information
2085
    	if ( format == ObjectFormat.EML_2_0_0 ||
2086
    			format == ObjectFormat.EML_2_0_1 ||
2087
    			format == ObjectFormat.EML_2_1_0 ) {
2088

    
2089
    		try {
2090
    			DataoneEMLParser emlParser = DataoneEMLParser.getInstance();
2091
    			EMLDocument emlDocument = emlParser.parseDocument(is);
2092

    
2093
    			// iterate through the data objects in the EML doc and add sysmeta
2094
    			logCrud.debug("The number of data entities is: " +
2095
    					emlDocument.distributionMetadata.size());
2096

    
2097
    			for( int j = 0; j < emlDocument.distributionMetadata.size(); j++ ) {
2098

    
2099
    				DistributionMetadata distMetadata = 
2100
    					emlDocument.distributionMetadata.elementAt(j);
2101
    				String dataDocUrl = distMetadata.url;
2102
    				String dataDocMimeType = distMetadata.mimeType;
2103
    				String dataDocLocalId = "";
2104
    				logCrud.debug("\tData local ID: " + dataDocLocalId);
2105
    				logCrud.debug("\tData URL: " + dataDocUrl);
2106
    				logCrud.debug("\tData mime: " + dataDocMimeType);
2107

    
2108
    				//we only handle ecogrid urls right now
2109
    				if ( dataDocUrl.trim().startsWith("ecogrid://knb/") ) {
2110
    					dataDocLocalId = 
2111
    						dataDocUrl.substring(dataDocUrl.indexOf("ecogrid://knb/") + 
2112
    								"ecogrid://knb/".length(), dataDocUrl.length());
2113

    
2114
    					//set the id
2115
    					Identifier dataDocId = new Identifier();
2116
    					dataDocId.setValue(dataDocLocalId);
2117

    
2118
    					// add describes into EML system metadata
2119
    					sm.addDescribe(dataDocId);
2120

    
2121
    					SystemMetadata dataSysMeta = new SystemMetadata();
2122
    					// check if data system metadata exists
2123
    					try {
2124
    						logCrud.debug("Checking for existing system metadata for " + dataDocId.getValue());
2125
    						dataSysMeta = this.getSystemMetadata(token, dataDocId);
2126
    						// add describedBy sysmeta
2127
    						logCrud.debug("Setting describedBy for " + dataDocId.getValue() +
2128
    								" to " + identifier.getValue());
2129
    						dataSysMeta.addDescribedBy(identifier);
2130
    						dataSysMeta.setObjectFormat(ObjectFormat.convert(dataDocMimeType));
2131
    						this.updateSystemMetadata(dataSysMeta, getSessionData(token));
2132

    
2133
    					} catch ( NotFound nf ) {
2134
    						// System metadata for data doesn't exist
2135
    						logCrud.debug("There was not an existing system metadata " + "document for " + dataDocId.getValue());
2136
    						logCrud.debug("Creating a system metadata " + "document for " + dataDocId.getValue());
2137
    						dataSysMeta = this.createSystemMetadata(dataDocLocalId, token);
2138

    
2139
    						logCrud.debug("Setting describedBy for " + dataDocId.getValue() + " to " + identifier.getValue());
2140
    						dataSysMeta.addDescribedBy(identifier);
2141

    
2142
    						logCrud.debug("Setting mimeType for " + dataDocId.getValue() + " to " + dataDocMimeType);
2143
    						dataSysMeta.setObjectFormat(ObjectFormat.convert(dataDocMimeType));
2144

    
2145
    						logCrud.debug("Updating system metadata for " + dataDocId.getValue() + " to " + dataDocMimeType);
2146
    						this.updateSystemMetadata(dataSysMeta, getSessionData(token));
2147
    					}
2148
    				} // end if()
2149
    			} // end for()
2150

    
2151
    		} catch ( ParserConfigurationException pce ) {
2152
    			logCrud.debug("There was a problem parsing the EML document. " +
2153
    					"The error message was: " + pce.getMessage());
2154

    
2155
    		} catch ( SAXException saxe ) {
2156
    			logCrud.debug("There was a problem traversing the EML document. " +
2157
    					"The error message was: " + saxe.getMessage());
2158

    
2159
    		} catch ( XPathExpressionException xpee ) {
2160
    			logCrud.debug("There was a problem searching the EML document. " +
2161
    					"The error message was: " + xpee.getMessage());
2162
    		} // end try
2163

    
2164
    	} // end if()
2165

    
2166
    	//create the checksum
2167
    	is = this.get(token, identifier);
2168
    	String checksumS = checksum(is);
2169
    	ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
2170
    	Checksum checksum = new Checksum();
2171
    	checksum.setValue(checksumS);
2172
    	checksum.setAlgorithm(ca);
2173
    	sm.setChecksum(checksum);
2174

    
2175
    	//set the size
2176
    	is = this.get(token, identifier);
2177
    	sm.setSize(sizeOfStream(is));
2178

    
2179
    	//submitter
2180
    	Subject p = new Subject();
2181
    	p.setValue((String) docInfo.get("user_owner"));
2182
    	sm.setSubmitter(p);
2183
    	sm.setRightsHolder(p);
2184
    	try {
2185
    		Date dateCreated = parseMetacatDate((String) docInfo.get("date_created"));
2186
    		sm.setDateUploaded(dateCreated);
2187
    		Date dateUpdated = parseMetacatDate((String) docInfo.get("date_updated"));
2188
    		sm.setDateSysMetadataModified(dateUpdated);
2189
    	} catch (Exception e) {
2190
    		logCrud.debug("POSSIBLE ERROR: couldn't parse a date: " + e.getMessage());
2191
    		Date dateCreated = new Date();
2192
    		sm.setDateUploaded(dateCreated);
2193
    		Date dateUpdated = new Date();
2194
    		sm.setDateSysMetadataModified(dateUpdated);
2195
    	}
2196
    	NodeReference nr = new NodeReference();
2197
    	nr.setValue(PropertyService.getProperty("dataone.memberNodeId"));
2198
    	sm.setOriginMemberNode(nr);
2199
    	sm.setAuthoritativeMemberNode(nr);
2200

    
2201
    	// TODO: Need to set describes/describedBy
2202

    
2203
    	return sm;
2204
    }
2205
    
2206
    /**
2207
     * create the listObjects pathQuery document
2208
     */
2209
//    private String createListObjectsPathQueryDocument()
2210
//        throws PropertyNotFoundException
2211
//    {
2212
//        String s = "<pathquery>";
2213
//        s += "<returndoctype>" + PropertyService.getProperty("crudService.listObjects.ReturnDoctype") + "</returndoctype>";
2214
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.1") + "</returnfield>";
2215
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.2") + "</returnfield>";
2216
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</returnfield>";
2217
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.4") + "</returnfield>";
2218
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.5") + "</returnfield>";
2219
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.6") + "</returnfield>";
2220
//        s += "<returnfield>" + PropertyService.getProperty("crudService.listObjects.ReturnField.7") + "</returnfield>";
2221
//        s += "<querygroup operator=\"UNION\"><queryterm casesensitive=\"false\" searchmode=\"contains\">";
2222
//        s += "<value>%</value>"; 
2223
//        s += "<pathexpr>" + PropertyService.getProperty("crudService.listObjects.ReturnField.3") + "</pathexpr>";
2224
//        s += "</queryterm></querygroup></pathquery>";
2225
//  
2226
//        return s;
2227
//    }
2228
}
2229

    
(1-1/4)