Project

General

Profile

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

    
28
import java.io.ByteArrayInputStream;
29
import java.io.InputStream;
30
import java.io.OutputStream;
31
import java.net.HttpURLConnection;
32
import java.net.URL;
33
import java.security.MessageDigest;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.Vector;
37

    
38
import javax.activation.DataHandler;
39
import javax.activation.DataSource;
40
import javax.mail.internet.MimeBodyPart;
41
import javax.mail.internet.MimeMultipart;
42

    
43
import org.apache.commons.io.IOUtils;
44
import org.dataone.client.D1Client;
45
import org.dataone.client.MNode;
46
import org.dataone.client.ObjectFormatCache;
47
import org.dataone.client.auth.CertificateManager;
48
import org.dataone.service.exceptions.NotFound;
49
import org.dataone.service.types.AccessPolicy;
50
import org.dataone.service.types.AccessRule;
51
import org.dataone.service.types.Checksum;
52
import org.dataone.service.types.ChecksumAlgorithm;
53
import org.dataone.service.types.Identifier;
54
import org.dataone.service.types.NodeReference;
55
import org.dataone.service.types.ObjectFormat;
56
import org.dataone.service.types.Permission;
57
import org.dataone.service.types.Session;
58
import org.dataone.service.types.Subject;
59
import org.dataone.service.types.SystemMetadata;
60
import org.ecoinformatics.datamanager.DataManager;
61
import org.ecoinformatics.datamanager.database.DatabaseConnectionPoolInterface;
62
import org.ecoinformatics.datamanager.parser.DataPackage;
63

    
64
import edu.ucsb.nceas.metacat.MetaCatServlet;
65
import edu.ucsb.nceas.metacat.dataquery.MetacatDatabaseConnectionPoolFactory;
66
import edu.ucsb.nceas.metacat.properties.PropertyService;
67
import edu.ucsb.nceas.metacat.restservice.InputStreamDataSource;
68

    
69
/**
70
 * @author berkley
71
 * A class to populate a metacat instance based on documents returned from a query
72
 */
73
public class MetacatPopulator
74
{
75
    private String sourceUrl = null;
76
    private String destinationUrl = null;
77
    private String query = null;
78
    private String username = null;
79
    private String password = null;
80
    private Session session = null;
81
    
82
    /**
83
     * create a new MetacatPopulator with given source and destination urls.  
84
     * These should be
85
     * of the form "http://<url>/<metacat_instance>"
86
     * If username and/or password is null, the query will be run as public
87
     * @param sourceUrl
88
     * @param destUrl
89
     * @param query
90
     * @param username
91
     * @param password
92
     */
93
    public MetacatPopulator(String sourceUrl, String destUrl, String query, String username, String password)
94
    {
95
        this.sourceUrl = sourceUrl;
96
        this.query = query;
97
        this.username = username;
98
        this.password = password;
99
        this.destinationUrl = destUrl;
100
        // TODO: set up certificate for D1 interaction
101
        CertificateManager.getInstance();
102
        this.session = new Session();
103
        Subject subject = new Subject();
104
        subject.setValue(username);
105
    }
106
    
107
    /**
108
     * populate from the source
109
     */
110
    public void populate()
111
      throws Exception
112
    {
113
        printHeader("Source login");
114
        String sourceSessionid = loginSource();
115
        
116
        //do a query
117
        String params = "returndoctype=eml://ecoinformatics.org/eml-2.1.0&" +
118
                        "returndoctype=eml://ecoinformatics.org/eml-2.0.1&" +
119
                        "returndoctype=eml://ecoinformatics.org/eml-2.0.0&";
120
        params += "action=query&";
121
        params += "qformat=xml&";
122
        params += "anyfield=" + query;
123
        
124
        printHeader("Searching source");
125
        System.out.println("searching '" + sourceUrl + "' for '" + query + "' with sessionid '" + sourceSessionid + "'");
126
        InputStream is = getResponse(sourceUrl, "/metacat",
127
                params, "POST");
128
        String response = streamToString(is);
129
        //System.out.println("response: " + response);
130
        Vector<Document> docs = parseResponse(response);
131
        
132
        
133
        printHeader("Parsing source results");
134
        System.out.println("creating MN with url: " + destinationUrl + "/");
135
        MNode mn = D1Client.getMN(destinationUrl + "/");
136
        
137
        printHeader("Processing " + docs.size() + " results.");
138
        printHeader("logging in to the destination " + destinationUrl);
139
        
140
        System.out.println("session: " + session.getSubject());
141
        for(int i=0; i<docs.size(); i++)
142
        {
143
            //for each document in the query
144
            Document doc = docs.get(i);
145
            String docid = doc.docid;
146
            //get the doc from source
147
            printHeader("Getting document " + doc.docid + " from source " + sourceUrl);
148
            params = "action=read&qformat=xml&docid=" + docid;
149
            is = getResponse(sourceUrl, "/metacat", params, "POST");
150
            String doctext = streamToString(is);
151
            System.out.println("doctext: " + doctext);
152
            is = stringToStream(doctext);
153
            //parse the document
154
            DatabaseConnectionPoolInterface connectionPool = MetacatDatabaseConnectionPoolFactory.getDatabaseConnectionPoolInterface();
155
        	DataManager dataManager = DataManager.getInstance(connectionPool, connectionPool.getDBAdapterName());
156
        	DataPackage dataPackage = dataManager.parseMetadata(is);
157
        	
158
            if(dataPackage == null)
159
            {
160
                continue;
161
            }
162
            //go through the DistributionMetadata and download any described data
163
            
164
            is = stringToStream(doctext);
165
            doc.doctext = doctext;
166

    
167
            printHeader("creating document on destination " + destinationUrl);            
168
            SystemMetadata sysmeta = generateSystemMetadata(doc);
169
            if (dataPackage.getEntityList() != null) {
170
	            for(int j=0; j < dataPackage.getEntityList().length; j++)
171
	            {
172
	                String dataDocUrl = dataPackage.getEntityList()[j].getURL();
173
	                String dataDocMimeType = 
174
	                	dataPackage.getEntityList()[j].getDataFormat();
175
	                if (dataDocMimeType == null) {
176
		                dataDocMimeType = 
177
		                	ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFmtid().getValue();
178
	                }
179
	                String dataDocLocalId = "";
180
	                if(dataDocUrl.trim().startsWith("ecogrid://knb/"))
181
	                { //we only handle ecogrid urls right now
182
	                    dataDocLocalId = dataDocUrl.substring(dataDocUrl.indexOf("ecogrid://knb/") + 
183
	                            "ecogrid://knb/".length(), dataDocUrl.length());
184
	                    //get the file
185
	                    params = "action=read&qformat=xml&docid=" + dataDocLocalId;
186
	                    InputStream dataDocIs = getResponse(sourceUrl, "/metacat", params, "POST");
187
	                    String dataDocText = streamToString(dataDocIs);
188
	                    
189
	                    //set the id
190
	                    Identifier did = new Identifier();
191
	                    did.setValue(dataDocLocalId);
192
	                    
193
	                    //add the desribeby to the eml's sysmeta
194
	                    System.out.println("adding describe for doc " + 
195
	                            sysmeta.getIdentifier().getValue() + " :" + did.getValue());
196
	                    sysmeta.addDescribe(did);
197
	                    
198
	                    //create sysmeta for the data doc                    
199
	                    SystemMetadata dataDocSysMeta = generateSystemMetadata(doc);
200
	                    //overwrite the bogus values from the last call 
201
	                    dataDocSysMeta.setIdentifier(did);
202
	                    ObjectFormat format = null;
203
	                    try {
204
	                    	format = ObjectFormatCache.getInstance().getFormat(dataDocMimeType);
205
	                    } catch (NotFound e) {
206
							System.out.println(e.getMessage());
207
						}
208
						dataDocSysMeta.setObjectFormat(format);
209
	                    Checksum checksum = new Checksum();
210
	                    dataDocIs = stringToStream(dataDocText);
211
	                    ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
212
	                    checksum.setAlgorithm(ca);
213
	                    checksum.setValue(checksum(dataDocIs));
214
	                    dataDocSysMeta.setChecksum(checksum);
215
	                    dataDocSysMeta.setSize(dataDocText.getBytes(MetaCatServlet.DEFAULT_ENCODING).length);
216
	                    dataDocSysMeta.addDescribedBy(sysmeta.getIdentifier());
217
	                    boolean error = false;
218
	                    
219
	                    // create access policy
220
	                    //"public", "read", "allow", "allowFirst"
221
	                    AccessPolicy accessPolicy = new AccessPolicy();
222
	                    AccessRule accessRule = new AccessRule();
223
						accessRule.addPermission(Permission.READ);
224
	                    Subject subject = new Subject();
225
	                    subject.setValue("public");
226
						accessRule.addSubject(subject );
227
						accessPolicy.addAllow(accessRule );
228
	                    //create the data doc on d1
229
	                    try
230
	                    {
231
	                        mn.create(session, dataDocSysMeta.getIdentifier(), IOUtils.toInputStream(dataDocText), dataDocSysMeta);
232
							mn.setAccessPolicy(session, dataDocSysMeta.getIdentifier(), accessPolicy);
233
	                    }
234
	                    catch(Exception e)
235
	                    {
236
	                        error = true;
237
	                        System.out.println("ERROR: Could not create data document with id " + 
238
	                                dataDocSysMeta.getIdentifier().getValue() + " : " + e.getMessage());
239
	                    }
240
	                    finally
241
	                    {
242
	                        if(error)
243
	                        {
244
	                            printHeader("Insertion of document " + dataDocSysMeta.getIdentifier().getValue() + 
245
	                                    "FAILED.");
246
	                        }
247
	                        else
248
	                        {
249
	                            printHeader("Done inserting document " + dataDocSysMeta.getIdentifier().getValue() +
250
	                                " which is described by " + sysmeta.getIdentifier().getValue());
251
	                        }
252
	                    }
253
	                }
254
	                else
255
	                {
256
	                    System.out.println("WARNING: Could not process describes url " +
257
	                            dataDocUrl + " for document " + doc.docid + 
258
	                    ".  Only ecogrid://knb/ urls are currently supported.");
259
	                }
260
	            }
261
            }
262
            
263
            try
264
            {
265
              Identifier id = mn.create(session, sysmeta.getIdentifier(), 
266
                    IOUtils.toInputStream(doc.doctext), sysmeta);
267
              System.out.println("Success inserting document " + id.getValue());
268
              
269
            }
270
            catch(Exception e)
271
            {
272
                e.printStackTrace();
273
                System.out.println("Could not create document with id " + 
274
                        sysmeta.getIdentifier().getValue() + " : " + e.getMessage());
275
                
276
            }
277
            finally
278
            {
279
                printHeader("Done inserting document " + sysmeta.getIdentifier().getValue());
280
            }
281
        }
282
        
283
        logout();
284
    }
285
    
286

    
287
    
288
    /**
289
     * @param doc
290
     * @return
291
     */
292
    private SystemMetadata generateSystemMetadata(Document doc)
293
      throws Exception
294
    {
295
        SystemMetadata sm = new SystemMetadata();
296
        //set the id
297
        Identifier id = new Identifier();
298
        id.setValue(doc.docid.trim());
299
        sm.setIdentifier(id);
300
        
301
        //set the object format
302
        ObjectFormat format = ObjectFormatCache.getInstance().getFormat(doc.doctype);
303
        if(format == null)
304
        {
305
            if(doc.doctype.trim().equals("BIN"))
306
            {
307
                format = ObjectFormatCache.getInstance().getFormat("application/octet-stream");
308
            }
309
            else
310
            {
311
                format = ObjectFormatCache.getInstance().getFormat("text/plain");
312
            }
313
        }
314
        sm.setObjectFormat(format);
315
        
316
        //create the checksum
317
        ByteArrayInputStream bais = new ByteArrayInputStream(doc.doctext.getBytes(MetaCatServlet.DEFAULT_ENCODING));
318
        String checksumS = checksum(bais);
319
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
320
        Checksum checksum = new Checksum();
321
        checksum.setValue(checksumS);
322
        checksum.setAlgorithm(ca);
323
        sm.setChecksum(checksum);
324
        
325
        //set the size
326
        sm.setSize(doc.doctext.getBytes(MetaCatServlet.DEFAULT_ENCODING).length);
327
        
328
        //submitter
329
        Subject p = new Subject();
330
        p.setValue("unknown");
331
        sm.setSubmitter(p);
332
        sm.setRightsHolder(p);
333
        try
334
        {
335
            Date dateCreated = parseMetacatDate(doc.createDate);
336
            sm.setDateUploaded(dateCreated);
337
            Date dateUpdated = parseMetacatDate(doc.updateDate);
338
            sm.setDateSysMetadataModified(dateUpdated);
339
        }
340
        catch(Exception e)
341
        {
342
            System.out.println("couldn't parse a date: " + e.getMessage());
343
            Date dateCreated = new Date();
344
            sm.setDateUploaded(dateCreated);
345
            Date dateUpdated = new Date();
346
            sm.setDateSysMetadataModified(dateUpdated);
347
        }
348
        NodeReference nr = new NodeReference();
349
        nr.setValue(PropertyService.getProperty("dataone.memberNodeId"));
350
        sm.setOriginMemberNode(nr);
351
        sm.setAuthoritativeMemberNode(nr);
352
        
353
        return sm;
354
    }
355
    
356
    private void printHeader(String s)
357
    {
358
        System.out.println("****** " + s + " *******");
359
    }
360
    
361
    /**
362
     * produce an md5 checksum for item
363
     */
364
    private String checksum(InputStream is)
365
      throws Exception
366
    {        
367
        byte[] buffer = new byte[1024];
368
        MessageDigest complete = MessageDigest.getInstance("MD5");
369
        int numRead;
370
        
371
        do 
372
        {
373
          numRead = is.read(buffer);
374
          if (numRead > 0) 
375
          {
376
            complete.update(buffer, 0, numRead);
377
          }
378
        } while (numRead != -1);
379
        
380
        
381
        return getHex(complete.digest());
382
    }
383
    
384
    /**
385
     * convert a byte array to a hex string
386
     */
387
    private static String getHex( byte [] raw ) 
388
    {
389
        final String HEXES = "0123456789ABCDEF";
390
        if ( raw == null ) {
391
          return null;
392
        }
393
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
394
        for ( final byte b : raw ) {
395
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
396
             .append(HEXES.charAt((b & 0x0F)));
397
        }
398
        return hex.toString();
399
    }
400
    
401
    /**
402
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
403
     * a proper date object
404
     * @param date
405
     * @return
406
     */
407
    private Date parseMetacatDate(String date)
408
    {
409
        String year = date.substring(0, 4);
410
        String month = date.substring(5, 7);
411
        String day = date.substring(8, 10);
412
        Calendar c = Calendar.getInstance();
413
        c.set(new Integer(year).intValue(), 
414
              new Integer(month).intValue(), 
415
              new Integer(day).intValue());
416
        return c.getTime();
417
    }
418

    
419
    /**
420
     * send a request to the resource
421
     */
422
    private InputStream sendRequest(String contextRootUrl, String resource, 
423
            String sessionid, String method, String urlParamaters, 
424
            String contentType, InputStream dataStream) 
425
        throws Exception 
426
    {
427
        
428
        HttpURLConnection connection = null ;
429
        String restURL = contextRootUrl + resource;
430

    
431
        if (urlParamaters != null) {
432
            if (restURL.indexOf("?") == -1)             
433
                restURL += "?";
434
            restURL += urlParamaters; 
435
            if(restURL.indexOf(" ") != -1)
436
            {
437
                restURL = restURL.replaceAll("\\s", "%20");
438
            }
439
        }
440
        
441
        if(sessionid != null)
442
        {
443
            if(restURL.indexOf("?") == -1)
444
            {
445
                restURL += "?sessionid=" + sessionid;
446
            }
447
            else
448
            {
449
                restURL += "&sessionid=" + sessionid;
450
            }
451
        }
452

    
453
        URL u = null;
454
        InputStream content = null;
455
        System.out.println("url: " + restURL);
456
        System.out.println("method: " + method);
457
        u = new URL(restURL);
458
        connection = (HttpURLConnection) u.openConnection();
459
        if (contentType!=null) {
460
            connection.setRequestProperty("Content-Type",contentType);
461
        }
462

    
463
        connection.setDoOutput(true);
464
        connection.setDoInput(true);
465
        connection.setRequestMethod(method);
466

    
467
        if (!method.equals("GET")) {
468
            if (dataStream != null) {
469
                OutputStream out = connection.getOutputStream();
470
                IOUtils.copy(dataStream, out);
471
            }
472
        }
473

    
474
        return connection.getInputStream();   
475
    }
476
    
477
    /**
478
     * create a mime multipart message from object and sysmeta
479
     */
480
    private MimeMultipart createMimeMultipart(InputStream object)
481
      throws Exception
482
    {
483
        final MimeMultipart mmp = new MimeMultipart();
484
        MimeBodyPart objectPart = new MimeBodyPart();
485
        objectPart.addHeaderLine("Content-Transfer-Encoding: base64");
486
        objectPart.setFileName("doctext");
487
        DataSource ds = new InputStreamDataSource("doctext", object);
488
        DataHandler dh = new DataHandler(ds);
489
        objectPart.setDataHandler(dh);
490
        mmp.addBodyPart(objectPart);
491
        return mmp;
492
    }
493
    
494
    /**
495
     * parse a metacat query response and return a vector of docids
496
     * @param response
497
     * @return
498
     */
499
    private Vector<Document> parseResponse(String response)
500
    {
501
        Vector<Document> v = new Vector<Document>();
502
        int dstart = response.indexOf("<document>");
503
        int dend = response.indexOf("</document>", dstart);
504
        while(dstart != -1)
505
        {
506
            String doc = response.substring(dstart + "<document>".length(), dend);
507
            //System.out.println("adding " + docid);
508
            Document d = new Document(getFieldFromDoc(doc, "docid"),
509
                    getFieldFromDoc(doc, "doctype"),
510
                    getFieldFromDoc(doc, "createdate"),
511
                    getFieldFromDoc(doc, "updatedate"));
512
            v.add(d);
513
            dstart = response.indexOf("<document>", dend);
514
            dend = response.indexOf("</document>", dstart);
515
        }
516
        
517
        return v;
518
    }
519
    
520
    private String getFieldFromDoc(String doc, String fieldname)
521
    {
522
        String field = "<" + fieldname + ">";
523
        String fieldend = "</" + fieldname + ">";
524
        int start = doc.indexOf(field);
525
        int end = doc.indexOf(fieldend);
526
        String s = doc.substring(start + field.length(), end);
527
        //System.out.println("field: " + fieldname + " : " + s);
528
        return s;
529
    }
530
    
531
    /**
532
     * login the source
533
     * @return
534
     * @throws Exception
535
     */
536
    private String loginSource()
537
      throws Exception
538
    {
539
        return login(sourceUrl);
540
    }
541
    
542
    
543
    /**
544
     * returns a sessionid
545
     * @return
546
     */
547
    private String login(String sourceUrl)
548
      throws Exception
549
    {
550
        InputStream is = getResponse(sourceUrl, "/metacat", 
551
                "action=login&username=" + username + "&password=" + password + "&qformat=xml", "POST");
552
        String response = streamToString(is);
553
        //System.out.println("response: " + response);
554
        if(response.indexOf("sessionId") == -1)
555
        {
556
            throw new Exception("Error logging into " + sourceUrl);
557
        }
558
        
559
        String sessionid = response.substring(
560
                response.indexOf("<sessionId>") + "<sessionId>".length(), 
561
                response.indexOf("</sessionId>"));
562
        System.out.println("sessionid: " + sessionid);
563
        return sessionid;
564
    }
565
    
566
    /**
567
     * logout both the source and destination
568
     * @throws Exception
569
     */
570
    private void logout()
571
        throws Exception
572
    {
573
        getResponse(sourceUrl, "/metacat", "action=logout&username=" + username, "POST");
574
        getResponse(destinationUrl, "/metacat", "action=logout&username=" + username, "POST");
575
    }
576
    
577
    /**
578
     * get an http response
579
     * @param contextRootUrl
580
     * @param resource
581
     * @param urlParameters
582
     * @param method
583
     * @return
584
     * @throws Exception
585
     */
586
    private InputStream getResponse(String contextRootUrl, String resource, 
587
            String urlParameters, String method)
588
      throws Exception
589
    {
590
        HttpURLConnection connection = null ;
591

    
592
        String restURL = contextRootUrl+resource;
593

    
594
        if (urlParameters != null) {
595
            if (restURL.indexOf("?") == -1)             
596
                restURL += "?";
597
            restURL += urlParameters; 
598
            if(restURL.indexOf(" ") != -1)
599
            {
600
                restURL = restURL.replaceAll("\\s", "%20");
601
            }
602
        }
603

    
604
        URL u = null;
605
        InputStream content = null;            
606
        System.out.println("url: " + restURL);
607
        System.out.println("method: " + method);
608
        u = new URL(restURL);
609
        connection = (HttpURLConnection) u.openConnection();
610
        connection.setDoOutput(true);
611
        connection.setDoInput(true);
612
        connection.setRequestMethod(method);
613
        content = connection.getInputStream();
614
        return content;
615
    }
616
    
617
    private String streamToString(InputStream is)
618
        throws Exception
619
    {
620
        byte b[] = new byte[1024];
621
        int numread = is.read(b, 0, 1024);
622
        String response = new String();
623
        while(numread != -1)
624
        {
625
            response += new String(b, 0, numread);
626
            numread = is.read(b, 0, 1024);
627
        }
628
        return response;
629
    }
630
    
631
    private InputStream stringToStream(String s)
632
      throws Exception
633
    {
634
        ByteArrayInputStream bais = new ByteArrayInputStream(s.getBytes(MetaCatServlet.DEFAULT_ENCODING));
635
        return bais;
636
    }
637
    
638
    private class Document
639
    {
640
        public String docid;
641
        public String doctype;
642
        public String createDate;
643
        public String updateDate;
644
        public String doctext;
645
        
646
        public Document(String docid, String doctype, String createDate, String updateDate)
647
        {
648
            this.docid = docid.trim();
649
            this.doctype = doctype.trim();
650
            this.createDate = createDate.trim();
651
            this.updateDate = updateDate.trim();
652
        }
653
    }
654
}
(8-8/16)