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.math.BigInteger;
31
import java.net.HttpURLConnection;
32
import java.net.URL;
33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Date;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Map;
39
import java.util.Vector;
40

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

    
65
import edu.ucsb.nceas.metacat.MetaCatServlet;
66
import edu.ucsb.nceas.metacat.dataquery.MetacatDatabaseConnectionPoolFactory;
67
import edu.ucsb.nceas.metacat.properties.PropertyService;
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
    private String subjectDN = null;
82
    
83
    /**
84
     * create a new MetacatPopulator with given source and destination urls.  
85
     * These should be
86
     * of the form "http://<url>/<metacat_instance>"
87
     * If username and/or password is null, the query will be run as public
88
     * @param sourceUrl
89
     * @param destUrl
90
     * @param query
91
     * @param username
92
     * @param password
93
     */
94
    public MetacatPopulator(String sourceUrl, String destUrl, String query, String username, String password)
95
    {
96
        this.sourceUrl = sourceUrl;
97
        this.query = query;
98
        this.username = username;
99
        this.password = password;
100
        this.destinationUrl = destUrl;
101
        // TODO: use specific certificate?
102
        this.session = null; //new Session();
103
        this.subjectDN = CertificateManager.getInstance().getSubjectDN(CertificateManager.getInstance().loadCertificate());
104
    }
105
    
106
    /**
107
     * populate from the source
108
     */
109
    public void populate()
110
      throws Exception
111
    {
112
        //String sourceSessionid = login();
113
        
114
        //do a query
115
        String params = "returndoctype=eml://ecoinformatics.org/eml-2.1.0&" +
116
                        "returndoctype=eml://ecoinformatics.org/eml-2.0.1&" +
117
                        "returndoctype=eml://ecoinformatics.org/eml-2.0.0&";
118
        params += "action=query&";
119
        params += "qformat=xml&";
120
        params += "anyfield=" + query;
121
        
122
        printHeader("Searching source");
123
        System.out.println("searching '" + sourceUrl + "' for '" + query + "'");
124
        InputStream is = getResponse(sourceUrl, "/metacat", params, "POST");
125
        String response = IOUtils.toString(is, MetaCatServlet.DEFAULT_ENCODING);
126
        //System.out.println("response: " + response);
127
        Vector<Document> docs = parseResponse(response);
128
        
129
        printHeader("Parsing source results");
130
        System.out.println("creating MN with url: " + destinationUrl + "/");
131
        MNode mn = D1Client.getMN(destinationUrl + "/");
132
        
133
        printHeader("Processing " + docs.size() + " results.");
134
        for (int i=0; i<docs.size(); i++) {
135
        	
136
        	// for generating the ORE map
137
            Map<Identifier, List<Identifier>> idMap = new HashMap<Identifier, List<Identifier>>();
138
            List<Identifier> dataIds = new ArrayList<Identifier>();
139
            
140
            //for each document in the query
141
            Document doc = docs.get(i);
142
            String docid = doc.docid;
143
            //get the doc from source
144
            printHeader("Getting document " + doc.docid + " from source " + sourceUrl);
145
            params = "action=read&qformat=xml&docid=" + docid;
146
            is = getResponse(sourceUrl, "/metacat", params, "POST");
147
            String doctext = IOUtils.toString(is, MetaCatServlet.DEFAULT_ENCODING);
148
            System.out.println("doctext: " + doctext);
149
            is = IOUtils.toInputStream(doctext, MetaCatServlet.DEFAULT_ENCODING);
150
            //parse the document
151
            DatabaseConnectionPoolInterface connectionPool = MetacatDatabaseConnectionPoolFactory.getDatabaseConnectionPoolInterface();
152
        	DataManager dataManager = DataManager.getInstance(connectionPool, connectionPool.getDBAdapterName());
153
        	DataPackage dataPackage = dataManager.parseMetadata(is);
154
        	
155
            if (dataPackage == null) {
156
                continue;
157
            }
158
            
159
            //go through the DistributionMetadata and download any described data
160
            is = IOUtils.toInputStream(doctext, MetaCatServlet.DEFAULT_ENCODING);
161
            doc.doctext = doctext;
162

    
163
            printHeader("creating document on destination " + destinationUrl);            
164
            SystemMetadata sysmeta = generateSystemMetadata(doc);
165
            
166
            // iterate through the data objects
167
            if (dataPackage.getEntityList() != null) {
168
	            for (int j=0; j < dataPackage.getEntityList().length; j++) {
169
	                String dataDocUrl = dataPackage.getEntityList()[j].getURL();
170
	                String dataDocMimeType = dataPackage.getEntityList()[j].getDataFormat();
171
	                if (dataDocMimeType == null) {
172
		                dataDocMimeType = 
173
		                	ObjectFormatCache.getInstance().getFormat("application/octet-stream").getFormatId().getValue();
174
	                }
175
	                String dataDocLocalId = "";
176
	                if (dataDocUrl.trim().startsWith("ecogrid://knb/")) { //we only handle ecogrid urls right now
177
	                    dataDocLocalId = dataDocUrl.substring(dataDocUrl.indexOf("ecogrid://knb/") + 
178
	                            "ecogrid://knb/".length(), dataDocUrl.length());
179
	                    //get the file
180
	                    params = "action=read&qformat=xml&docid=" + dataDocLocalId;
181
	                    InputStream dataDocIs = getResponse(sourceUrl, "/metacat", params, "POST");
182
	                    String dataDocText = IOUtils.toString(dataDocIs, MetaCatServlet.DEFAULT_ENCODING);
183
	                    
184
	                    //set the id
185
	                    Identifier did = new Identifier();
186
	                    did.setValue(dataDocLocalId);
187
	                    
188
	                    // add the data identifier for ORE map 
189
	                    dataIds.add(did);
190
	                    
191
	                    //create sysmeta for the data doc                    
192
	                    SystemMetadata dataDocSysMeta = generateSystemMetadata(doc);
193
	                    //overwrite the bogus values from the last call 
194
	                    dataDocSysMeta.setIdentifier(did);
195
	                    ObjectFormat format = null;
196
	                    try {
197
	                    	format = ObjectFormatCache.getInstance().getFormat(dataDocMimeType);
198
							dataDocSysMeta.setFormatId(format.getFormatId());
199
	                    } catch (NotFound e) {
200
							System.out.println(e.getMessage());
201
						}
202
	                    dataDocIs = IOUtils.toInputStream(dataDocText, MetaCatServlet.DEFAULT_ENCODING);
203
	                    Checksum checksum = ChecksumUtil.checksum(dataDocIs, "MD5");
204
	                    dataDocSysMeta.setChecksum(checksum);
205
	                    String sizeStr = 
206
	                    	Long.toString(dataDocText.getBytes(MetaCatServlet.DEFAULT_ENCODING).length);
207
	                    dataDocSysMeta.setSize(new BigInteger(sizeStr));
208

    
209
	                    boolean error = false;
210
	                    
211
	                    //create the data doc on d1
212
	                    try {
213
	                        mn.create(session, dataDocSysMeta.getIdentifier(), IOUtils.toInputStream(dataDocText, MetaCatServlet.DEFAULT_ENCODING), dataDocSysMeta);
214
	                    }
215
	                    catch(Exception e) {
216
	                        error = true;
217
	                        System.out.println("ERROR: Could not create data document with id " + 
218
	                                dataDocSysMeta.getIdentifier().getValue() + " : " + e.getMessage());
219
	                    }
220
	                    finally {
221
	                        if (error) {
222
	                            printHeader("Insertion of document " + dataDocSysMeta.getIdentifier().getValue() + 
223
	                                    "FAILED.");
224
	                        }
225
	                        else {
226
	                            printHeader("Done inserting document " + dataDocSysMeta.getIdentifier().getValue() +
227
	                                " which is described by " + sysmeta.getIdentifier().getValue());
228
	                        }
229
	                    }
230
	                }
231
	                else {
232
	                    System.out.println("WARNING: Could not process describes url " +
233
	                            dataDocUrl + " for document " + doc.docid + 
234
	                    ".  Only ecogrid://knb/ urls are currently supported.");
235
	                }
236
	            }
237
            }
238
            
239
            try {
240
              Identifier id = 
241
            	  mn.create(session, sysmeta.getIdentifier(), IOUtils.toInputStream(doc.doctext, MetaCatServlet.DEFAULT_ENCODING), sysmeta);
242
              System.out.println("Success inserting document " + id.getValue());
243
              
244
              // no need for an ORE map if there's no data
245
              if (!dataIds.isEmpty()) {
246
	              // generate the ORE map for this datapackage
247
	              Identifier resourceMapId = new Identifier();
248
	              resourceMapId.setValue("resourceMap_" + sysmeta.getIdentifier().getValue());
249
	              idMap.put(sysmeta.getIdentifier(), dataIds);
250
	              ResourceMap rm = ResourceMapFactory.getInstance().createResourceMap(resourceMapId, idMap);
251
	              String resourceMapXML = ResourceMapFactory.getInstance().serializeResourceMap(rm);
252
	              Document rmDoc = new Document(resourceMapId.getValue(), "http://www.openarchives.org/ore/terms", "", "");
253
	              rmDoc.doctext = resourceMapXML;
254
	              SystemMetadata resourceMapSysMeta = generateSystemMetadata(rmDoc);
255
	              mn.create(session, resourceMapId, IOUtils.toInputStream(resourceMapXML, MetaCatServlet.DEFAULT_ENCODING), resourceMapSysMeta);
256
	              
257
            }
258
              
259
            }
260
            catch(Exception e) {
261
                e.printStackTrace();
262
                System.out.println("Could not create document with id " + 
263
                        sysmeta.getIdentifier().getValue() + " : " + e.getMessage());
264
            }
265
            finally {
266
                printHeader("Done processing document " + sysmeta.getIdentifier().getValue());
267
            }
268
        }
269
        
270
        //logout();
271
    }
272
    
273

    
274
    
275
    /**
276
     * @param doc
277
     * @return
278
     */
279
    private SystemMetadata generateSystemMetadata(Document doc)
280
      throws Exception {
281
        SystemMetadata sm = new SystemMetadata();
282
        sm.setSerialVersion(BigInteger.valueOf(1));
283
        //set the id
284
        Identifier id = new Identifier();
285
        id.setValue(doc.docid.trim());
286
        sm.setIdentifier(id);
287
        
288
        //set the object format
289
        ObjectFormat format = ObjectFormatCache.getInstance().getFormat(doc.doctype);
290
        if (format == null) {
291
            if (doc.doctype.trim().equals("BIN")) {
292
                format = ObjectFormatCache.getInstance().getFormat("application/octet-stream");
293
            }
294
            else {
295
                format = ObjectFormatCache.getInstance().getFormat("text/plain");
296
            }
297
        }
298
        sm.setFormatId(format.getFormatId());
299
        
300
        //create the checksum
301
        ByteArrayInputStream bais = new ByteArrayInputStream(doc.doctext.getBytes(MetaCatServlet.DEFAULT_ENCODING));
302
        Checksum checksum = ChecksumUtil.checksum(bais, "MD5");
303
        sm.setChecksum(checksum);
304
        
305
        //set the size
306
        String sizeStr = Long.toString(doc.doctext.getBytes(MetaCatServlet.DEFAULT_ENCODING).length);
307
        sm.setSize(new BigInteger(sizeStr));
308
        
309
        //submitter, rights holder
310
        Subject p = new Subject();
311
        p.setValue(subjectDN);
312
        sm.setSubmitter(p);
313
        sm.setRightsHolder(p);
314
        try {
315
            Date dateCreated = parseMetacatDate(doc.createDate);
316
            sm.setDateUploaded(dateCreated);
317
            Date dateUpdated = parseMetacatDate(doc.updateDate);
318
            sm.setDateSysMetadataModified(dateUpdated);
319
        }
320
        catch(Exception e) {
321
            System.out.println("couldn't parse a date: " + e.getMessage());
322
            Date dateCreated = new Date();
323
            sm.setDateUploaded(dateCreated);
324
            Date dateUpdated = new Date();
325
            sm.setDateSysMetadataModified(dateUpdated);
326
        }
327
        NodeReference nr = new NodeReference();
328
        nr.setValue(PropertyService.getProperty("dataone.memberNodeId"));
329
        sm.setOriginMemberNode(nr);
330
        sm.setAuthoritativeMemberNode(nr);
331
        
332
        // create access policy
333
        AccessPolicy accessPolicy = new AccessPolicy();
334
        AccessRule accessRule = new AccessRule();
335
		accessRule.addPermission(Permission.READ);
336
        Subject subject = new Subject();
337
        subject.setValue(Constants.SUBJECT_PUBLIC);
338
		accessRule.addSubject(subject);
339
		accessPolicy.addAllow(accessRule);
340
		
341
		sm.setAccessPolicy(accessPolicy);
342
        
343
        return sm;
344
    }
345
    
346
    private void printHeader(String s) {
347
        System.out.println("****** " + s + " *******");
348
    }
349
    
350
    /**
351
     * parse the metacat date which looks like 2010-06-08 (YYYY-MM-DD) into
352
     * a proper date object
353
     * @param date
354
     * @return
355
     */
356
    private Date parseMetacatDate(String date)
357
    {
358
        String year = date.substring(0, 4);
359
        String month = date.substring(5, 7);
360
        String day = date.substring(8, 10);
361
        Calendar c = Calendar.getInstance();
362
        c.set(new Integer(year).intValue(), 
363
              new Integer(month).intValue(), 
364
              new Integer(day).intValue());
365
        return c.getTime();
366
    }
367
    
368
    /**
369
     * parse a metacat query response and return a vector of docids
370
     * @param response
371
     * @return
372
     */
373
    private Vector<Document> parseResponse(String response)
374
    {
375
        Vector<Document> v = new Vector<Document>();
376
        int dstart = response.indexOf("<document>");
377
        int dend = response.indexOf("</document>", dstart);
378
        while(dstart != -1)
379
        {
380
            String doc = response.substring(dstart + "<document>".length(), dend);
381
            //System.out.println("adding " + docid);
382
            Document d = new Document(getFieldFromDoc(doc, "docid"),
383
                    getFieldFromDoc(doc, "doctype"),
384
                    getFieldFromDoc(doc, "createdate"),
385
                    getFieldFromDoc(doc, "updatedate"));
386
            v.add(d);
387
            dstart = response.indexOf("<document>", dend);
388
            dend = response.indexOf("</document>", dstart);
389
        }
390
        
391
        return v;
392
    }
393
    
394
    private String getFieldFromDoc(String doc, String fieldname)
395
    {
396
        String field = "<" + fieldname + ">";
397
        String fieldend = "</" + fieldname + ">";
398
        int start = doc.indexOf(field);
399
        int end = doc.indexOf(fieldend);
400
        String s = doc.substring(start + field.length(), end);
401
        //System.out.println("field: " + fieldname + " : " + s);
402
        return s;
403
    }
404
    
405
    
406
    /**
407
     * returns a sessionid
408
     * @return
409
     */
410
    private String login()
411
      throws Exception
412
    {
413
        InputStream is = getResponse(sourceUrl, "/metacat", 
414
                "action=login&username=" + username + "&password=" + password + "&qformat=xml", "POST");
415
        String response = IOUtils.toString(is, MetaCatServlet.DEFAULT_ENCODING);
416
        //System.out.println("response: " + response);
417
        if(response.indexOf("sessionId") == -1)
418
        {
419
            throw new Exception("Error logging into " + sourceUrl);
420
        }
421
        
422
        String sessionid = response.substring(
423
                response.indexOf("<sessionId>") + "<sessionId>".length(), 
424
                response.indexOf("</sessionId>"));
425
        System.out.println("sessionid: " + sessionid);
426
        return sessionid;
427
    }
428
    
429
    /**
430
     * logout both the source and destination
431
     * @throws Exception
432
     */
433
    private void logout()
434
        throws Exception
435
    {
436
        getResponse(sourceUrl, "/metacat", "action=logout&username=" + username, "POST");
437
    }
438
    
439
    /**
440
     * get an http response
441
     * @param contextRootUrl
442
     * @param resource
443
     * @param urlParameters
444
     * @param method
445
     * @return
446
     * @throws Exception
447
     */
448
    private InputStream getResponse(String contextRootUrl, String resource, 
449
            String urlParameters, String method)
450
      throws Exception
451
    {
452
        HttpURLConnection connection = null ;
453

    
454
        String restURL = contextRootUrl+resource;
455

    
456
        if (urlParameters != null) {
457
            if (restURL.indexOf("?") == -1)             
458
                restURL += "?";
459
            restURL += urlParameters; 
460
            if(restURL.indexOf(" ") != -1)
461
            {
462
                restURL = restURL.replaceAll("\\s", "%20");
463
            }
464
        }
465

    
466
        URL u = null;
467
        InputStream content = null;            
468
        System.out.println("url: " + restURL);
469
        System.out.println("method: " + method);
470
        u = new URL(restURL);
471
        connection = (HttpURLConnection) u.openConnection();
472
        connection.setDoOutput(true);
473
        connection.setDoInput(true);
474
        connection.setRequestMethod(method);
475
        content = connection.getInputStream();
476
        return content;
477
    }
478
    
479
    private class Document
480
    {
481
        public String docid;
482
        public String doctype;
483
        public String createDate;
484
        public String updateDate;
485
        public String doctext;
486
        
487
        public Document(String docid, String doctype, String createDate, String updateDate)
488
        {
489
            this.docid = docid.trim();
490
            this.doctype = doctype.trim();
491
            this.createDate = createDate.trim();
492
            this.updateDate = updateDate.trim();
493
        }
494
    }
495
}
(8-8/16)