Project

General

Profile

1
package edu.ucsb.nceas.metacat.annotation;
2

    
3
import java.io.InputStream;
4
import java.io.StringWriter;
5
import java.sql.PreparedStatement;
6
import java.sql.SQLException;
7
import java.util.ArrayList;
8
import java.util.Arrays;
9
import java.util.HashMap;
10
import java.util.Iterator;
11
import java.util.List;
12
import java.util.Map;
13
import java.util.Vector;
14

    
15
import org.apache.commons.io.IOUtils;
16
import org.apache.log4j.Logger;
17
import org.apache.wicket.protocol.http.mock.MockHttpServletRequest;
18
import org.dataone.service.types.v1.Identifier;
19
import org.dataone.service.types.v1.Session;
20
import org.dataone.service.types.v1.Subject;
21
import org.ecoinformatics.datamanager.parser.Attribute;
22
import org.ecoinformatics.datamanager.parser.DataPackage;
23
import org.ecoinformatics.datamanager.parser.Entity;
24
import org.ecoinformatics.datamanager.parser.Party;
25
import org.ecoinformatics.datamanager.parser.generic.DataPackageParserInterface;
26
import org.ecoinformatics.datamanager.parser.generic.Eml200DataPackageParser;
27

    
28
import com.hp.hpl.jena.ontology.AllValuesFromRestriction;
29
import com.hp.hpl.jena.ontology.Individual;
30
import com.hp.hpl.jena.ontology.ObjectProperty;
31
import com.hp.hpl.jena.ontology.OntClass;
32
import com.hp.hpl.jena.ontology.OntDocumentManager;
33
import com.hp.hpl.jena.ontology.OntModel;
34
import com.hp.hpl.jena.ontology.Ontology;
35
import com.hp.hpl.jena.query.Dataset;
36
import com.hp.hpl.jena.query.Query;
37
import com.hp.hpl.jena.query.QueryExecution;
38
import com.hp.hpl.jena.query.QueryExecutionFactory;
39
import com.hp.hpl.jena.query.QueryFactory;
40
import com.hp.hpl.jena.query.QuerySolution;
41
import com.hp.hpl.jena.query.ResultSet;
42
import com.hp.hpl.jena.rdf.model.ModelFactory;
43
import com.hp.hpl.jena.rdf.model.Property;
44
import com.hp.hpl.jena.rdf.model.Resource;
45
import com.hp.hpl.jena.tdb.TDBFactory;
46

    
47
import edu.ucsb.nceas.metacat.DBUtil;
48
import edu.ucsb.nceas.metacat.DocumentImpl;
49
import edu.ucsb.nceas.metacat.IdentifierManager;
50
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
51
import edu.ucsb.nceas.metacat.database.DBConnection;
52
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
53
import edu.ucsb.nceas.metacat.dataone.MNodeService;
54
import edu.ucsb.nceas.metacat.index.MetacatSolrIndex;
55
import edu.ucsb.nceas.metacat.properties.PropertyService;
56
import edu.ucsb.nceas.metacat.replication.ReplicationService;
57
import edu.ucsb.nceas.metacat.util.DocumentUtil;
58
import edu.ucsb.nceas.utilities.SortedProperties;
59

    
60
public class DatapackageSummarizer {
61

    
62
	private static Logger logMetacat = Logger.getLogger(DatapackageSummarizer.class);
63
	
64
	public static String rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
65
	public static String rdfs = "http://www.w3.org/2000/01/rdf-schema#";
66
	public static String owl = "http://www.w3.org/2002/07/owl#";
67
	public static String oboe = "http://ecoinformatics.org/oboe/oboe.1.0/oboe.owl#";
68
	public static String oboe_core = "http://ecoinformatics.org/oboe/oboe.1.0/oboe-core.owl#";
69
	public static String oboe_characteristics = "http://ecoinformatics.org/oboe/oboe.1.0/oboe-characteristics.owl#";
70
	public static String oboe_sbc = "http://ecoinformatics.org/oboe-ext/sbclter.1.0/oboe-sbclter.owl#";
71
	public static String oa = "http://www.w3.org/ns/oa#";
72
	public static String oa_source = "http://www.w3.org/ns/oa.rdf";
73
	public static String dcterms = "http://purl.org/dc/terms/";
74
	public static String dcterms_source = "http://dublincore.org/2012/06/14/dcterms.rdf";
75
	public static String foaf = "http://xmlns.com/foaf/0.1/";
76
	public static String foaf_source = "http://xmlns.com/foaf/spec/index.rdf";
77
    public static String prov = "http://www.w3.org/ns/prov#";
78
    public static String prov_source = "http://www.w3.org/ns/prov.owl";
79
    public static String cito =  "http://purl.org/spar/cito/";
80
    
81
	public static String OBOE_SBC = "OBOE-SBC";
82
	
83
	private static boolean cacheInitialized;
84
	
85
	private static void initializeCache() {
86
		if (!cacheInitialized) {
87
			// cache the ontologies we use
88
			OntDocumentManager.getInstance().addModel(oboe, ModelFactory.createOntologyModel().read(oboe));
89
			OntDocumentManager.getInstance().addModel(oboe_sbc, ModelFactory.createOntologyModel().read(oboe_sbc));
90
			OntDocumentManager.getInstance().addModel(oa, ModelFactory.createOntologyModel().read(oa_source));
91
			OntDocumentManager.getInstance().addModel(dcterms, ModelFactory.createOntologyModel().read(dcterms_source));
92
			OntDocumentManager.getInstance().addModel(foaf, ModelFactory.createOntologyModel().read(foaf_source));
93
			OntDocumentManager.getInstance().addModel(prov, ModelFactory.createOntologyModel().read(prov));
94
			OntDocumentManager.getInstance().addModel(cito, ModelFactory.createOntologyModel().read(cito));
95
			cacheInitialized = true;
96
		}
97
	}
98
    
99
    public void indexEphemeralAnnotation(Identifier metadataPid) throws Exception {
100

    
101
    	// generate an annotation for the metadata given
102
		String rdfContent = this.generateAnnotation(metadataPid);
103
		
104
		// load to triple store
105
		//Dataset dataset = TDBFactory.createDataset("./tbd");
106
		Dataset dataset = TDBFactory.createDataset();
107
		//Dataset dataset = DatasetFactory.createMem();
108
		
109
    	// read the annotation into the triplestore
110
		InputStream source = IOUtils.toInputStream(rdfContent, "UTF-8");
111
    	String name = "http://annotation/" + metadataPid.getValue();
112
    	boolean loaded = dataset.containsNamedModel(name);
113
    	if (loaded) {
114
    		dataset.removeNamedModel(name);
115
    		loaded = false;
116
    	}
117
		OntModel ontModel = null;
118
		if (!loaded) {
119
			ontModel = ModelFactory.createOntologyModel();
120
			ontModel.read(source, name);
121
			dataset.addNamedModel(name, ontModel);
122
		}
123
		
124
		// query for fields to add to index
125
        Map<String, List<Object>> fields = new HashMap<String, List<Object>>();
126
		
127
        // TODO: look up the query to use (support multiple like in the indexing project)
128
        List<String> queries = new ArrayList<String>();        
129
        queries.add("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
130
        	+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
131
        	+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> " 
132
			+ "PREFIX oboe-core: <http://ecoinformatics.org/oboe/oboe.1.0/oboe-core.owl#> "
133
			+ "PREFIX oa: <http://www.w3.org/ns/oa#> "
134
			+ "PREFIX dcterms: <http://purl.org/dc/terms/> "
135
			+ "SELECT ?standard_sm ?pid "
136
			+ "FROM <$GRAPH_NAME> "
137
			+ "WHERE { "
138
			+ "		?measurement rdf:type oboe-core:Measurement . "
139
			+ "		?measurement rdf:type ?restriction . "
140
			+ "		?restriction owl:onProperty oboe-core:usesStandard . "
141
			+ "		?restriction owl:allValuesFrom ?standard . "
142
			+ "		?standard rdfs:subClassOf+ ?standard_sm . "
143
			+ "		?standard_sm rdfs:subClassOf oboe-core:Standard . "				
144
			+ "		?annotation oa:hasBody ?measurement . "												
145
			+ "		?annotation oa:hasTarget ?target . "
146
			+ "		?target oa:hasSource ?metadata . "
147
			+ "		?metadata dcterms:identifier ?pid . " 
148
			+ "}");
149
        
150
        queries.add("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
151
    		+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
152
    		+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
153
    		+ "PREFIX oboe-core: <http://ecoinformatics.org/oboe/oboe.1.0/oboe-core.owl#> "
154
    		+ "PREFIX oa: <http://www.w3.org/ns/oa#> "
155
    		+ "PREFIX dcterms: <http://purl.org/dc/terms/> "
156
    		+ "SELECT ?characteristic_sm ?pid "
157
    		+ "FROM <$GRAPH_NAME>"
158
    		+ "WHERE { "
159
    		+ "		?measurement rdf:type oboe-core:Measurement . "
160
    		+ "		?measurement rdf:type ?restriction . "
161
			+ "		?restriction owl:onProperty oboe-core:ofCharacteristic . "
162
			+ "		?restriction owl:allValuesFrom ?characteristic . "
163
			+ "		?characteristic rdfs:subClassOf+ ?characteristic_sm . "
164
			+ "		?characteristic_sm rdfs:subClassOf oboe-core:Characteristic . "
165
			+ "		?annotation oa:hasBody ?measurement .	"											
166
			+ "		?annotation oa:hasTarget ?target . "
167
			+ "		?target oa:hasSource ?metadata . "
168
			+ "		?metadata dcterms:identifier ?pid . " 
169
			+ "}");
170
        
171
        for (String q: queries) {
172
	        q = q.replaceAll("\\$GRAPH_NAME", name);
173
			Query query = QueryFactory.create(q);
174
			QueryExecution qexec = QueryExecutionFactory.create(query, dataset);
175
			ResultSet results = qexec.execSelect();
176
			
177
			while (results.hasNext()) {
178
				QuerySolution solution = results.next();
179
				System.out.println(solution.toString());
180
				
181
				// find the index document we are trying to augment with the annotation
182
				if (solution.contains("pid")) {
183
					String id = solution.getLiteral("pid").getString();
184
					if (!id.equals(metadataPid.getValue())) {
185
						// skip any solution that does not annotate the given pid
186
						continue;
187
					}
188
					
189
				}
190
				// loop through the solution variables, add an index value for each
191
				Iterator<String> varNameIter = solution.varNames();
192
				while (varNameIter.hasNext()) {
193
					String key = varNameIter.next();
194
					if (key.equals("pid")) {
195
						// don't include the id
196
						continue;
197
					}
198
					String value = solution.get(key).toString();
199
					List<Object> values = fields.get(key);
200
					if (values  == null) {
201
						values = new ArrayList<Object>();
202
					}
203
					values.add(value);
204
					fields.put(key, values);
205
				}
206
			}
207
        }
208

    
209
        // remove the graph to save storage
210
//        ontModel.removeAll();
211
//        ontModel.commit();
212
//        ontModel.close();
213
		dataset.removeNamedModel(name);
214
        
215
		// clean up the triple store
216
		TDBFactory.release(dataset);
217
        
218
		// add to index
219
		MetacatSolrIndex.getInstance().submit(metadataPid, null, fields, true);
220
		
221
		
222
	}
223

    
224
    /**
225
     * Generate annotation for given metadata identifier
226
     * @param metadataPid
227
     */
228
    public String generateAnnotation(Identifier metadataPid) throws Exception {
229
    	
230
    	DataPackage dataPackage = this.getDataPackage(metadataPid);
231
    	
232
		OntModel m = ModelFactory.createOntologyModel();
233
		Ontology ont = m.createOntology("http://annotation/" + metadataPid.getValue());
234
		
235
		// TODO: import the ontologies we use
236
		initializeCache();
237
		
238
		ont.addImport(m.createResource(oboe));
239
		m.addSubModel(OntDocumentManager.getInstance().getModel(oboe));
240
		
241
		ont.addImport(m.createResource(oboe_sbc));
242
		m.addSubModel(OntDocumentManager.getInstance().getModel(oboe_sbc));
243
		
244
		ont.addImport(m.createResource(oa));
245
		m.addSubModel(OntDocumentManager.getInstance().getModel(oa));
246

    
247
		ont.addImport(m.createResource(dcterms));
248
		m.addSubModel(OntDocumentManager.getInstance().getModel(dcterms));
249

    
250
		ont.addImport(m.createResource(foaf));
251
		m.addSubModel(OntDocumentManager.getInstance().getModel(foaf));
252
		
253
		ont.addImport(m.createResource(prov));
254
		//m.addSubModel(ModelFactory.createOntologyModel().read(prov_source));
255

    
256
		ont.addImport(m.createResource(cito));
257
		
258
		// properties
259
		ObjectProperty hasBodyProperty = m.getObjectProperty(oa + "hasBody");
260
		ObjectProperty hasTargetProperty = m.getObjectProperty(oa + "hasTarget");
261
		ObjectProperty hasSourceProperty = m.getObjectProperty(oa + "hasSource");
262
		ObjectProperty hasSelectorProperty = m.getObjectProperty(oa + "hasSelector");
263
		ObjectProperty annotatedByProperty = m.getObjectProperty(oa + "annotatedBy");
264
		Property identifierProperty = m.getProperty(dcterms + "identifier");
265
		Property conformsToProperty = m.getProperty(dcterms + "conformsTo");
266
		Property wasAttributedTo = m.getProperty(prov + "wasAttributedTo");
267
		Property nameProperty = m.getProperty(foaf + "name");
268
		Property rdfValue = m.getProperty(rdf + "value");
269
		
270
		ObjectProperty ofCharacteristic = m.getObjectProperty(oboe_core + "ofCharacteristic");
271
		ObjectProperty usesStandard = m.getObjectProperty(oboe_core + "usesStandard");
272
		ObjectProperty ofEntity = m.getObjectProperty(oboe_core + "ofEntity");
273
		ObjectProperty hasMeasurement = m.getObjectProperty(oboe_core + "hasMeasurement");
274

    
275
		// classes
276
		OntClass entityClass =  m.getOntClass(oboe_core + "Entity");
277
		OntClass observationClass =  m.getOntClass(oboe_core + "Observation");
278
		OntClass measurementClass =  m.getOntClass(oboe_core + "Measurement");
279
		OntClass characteristicClass = m.getOntClass(oboe_core + "Characteristic");
280
		OntClass standardClass =  m.getOntClass(oboe_core + "Standard");
281
		
282
		Resource annotationClass =  m.getOntClass(oa + "Annotation");
283
		Resource specificResourceClass =  m.getOntClass(oa + "SpecificResource");
284
		Resource fragmentSelectorClass =  m.getOntClass(oa + "FragmentSelector");
285
		Resource provEntityClass =  m.getResource(prov + "Entity");
286
		Resource personClass =  m.getResource(prov + "Person");
287
				
288
		// these apply to every attribute annotation
289
		Individual meta1 = m.createIndividual(ont.getURI() + "#meta", provEntityClass);
290
		meta1.addProperty(identifierProperty, metadataPid.getValue());
291

    
292
		// decide who should be credited with the package
293
		Individual p1 = null;
294
		
295
		// look up creators from the EML metadata
296
		List<Party> creators = dataPackage.getCreators();
297
		//creators = Arrays.asList("Matthew Jones");
298
		if (creators != null && creators.size() > 0) {	
299
			// use an orcid if we can find one from their system
300
			String orcidUri = OrcidService.lookupOrcid(creators.get(0).getOrganization(), creators.get(0).getSurName(), creators.get(0).getGivenNames(), null);
301
			if (orcidUri != null) {
302
				p1 = m.createIndividual(orcidUri, personClass);
303
				p1.addProperty(identifierProperty, orcidUri);
304
			} else {
305
				p1 = m.createIndividual(ont.getURI() + "#person", personClass);
306
			}
307
			// include the name we have in the metadata
308
			if (creators.get(0).getSurName() != null) {
309
				p1.addProperty(nameProperty, creators.get(0).getSurName());
310
			} else if (creators.get(0).getOrganization() != null) {
311
				p1.addProperty(nameProperty, creators.get(0).getOrganization());
312
			}
313
		}
314
		
315
		// attribute the package to this creator if we have one
316
		if (p1 != null) {
317
			meta1.addProperty(wasAttributedTo, p1);
318
		}
319
		
320
		// loop through the tables and attributes
321
		int entityCount = 1;
322
		Entity[] entities = dataPackage.getEntityList();
323
		if (entities != null) {
324
			for (Entity entity: entities) {
325
				String entityName = entity.getName();
326
				
327
				Individual o1 = m.createIndividual(ont.getURI() + "#observation" + entityCount, observationClass);
328
				Resource entityConcept = lookupEntity(entityClass, entity);
329
				if (entityConcept != null) {
330
					AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, ofEntity, entityConcept);
331
					o1.addOntClass(avfr);
332
				}
333
				
334
				logMetacat.debug("Entity name: " + entityName);
335
				Attribute[] attributes = entity.getAttributeList().getAttributes();
336
				int attributeCount = 1;
337
				if (attributes != null) {
338
					for (Attribute attribute: attributes) {
339
						
340
						// for naming the individuals uniquely
341
						String cnt = entityCount + "_" + attributeCount;
342
						
343
						String attributeName = attribute.getName();
344
						String attributeLabel = attribute.getLabel();
345
						String attributeDefinition = attribute.getDefinition();
346
						String attributeType = attribute.getAttributeType();
347
						String attributeScale = attribute.getMeasurementScale();
348
						String attributeUnitType = attribute.getUnitType();
349
						String attributeUnit = attribute.getUnit();
350
						String attributeDomain = attribute.getDomain().getClass().getSimpleName();
351
		
352
						logMetacat.debug("Attribute name: " + attributeName);
353
						logMetacat.debug("Attribute label: " + attributeLabel);
354
						logMetacat.debug("Attribute definition: " + attributeDefinition);
355
						logMetacat.debug("Attribute type: " + attributeType);
356
						logMetacat.debug("Attribute scale: " + attributeScale);
357
						logMetacat.debug("Attribute unit type: " + attributeUnitType);
358
						logMetacat.debug("Attribute unit: " + attributeUnit);
359
						logMetacat.debug("Attribute domain: " + attributeDomain);
360
					
361
						// look up the characteristic or standard subclasses
362
						Resource standard = this.lookupStandard(standardClass, attribute);
363
						Resource characteristic = this.lookupCharacteristic(characteristicClass, attribute);
364
						
365
						if (standard != null || characteristic != null) {
366
							
367
							// instances
368
							Individual m1 = m.createIndividual(ont.getURI() + "#measurement" + cnt, measurementClass);
369
							Individual a1 = m.createIndividual(ont.getURI() + "#annotation" + cnt, annotationClass);
370
							Individual t1 = m.createIndividual(ont.getURI() + "#target" + cnt, specificResourceClass);
371
							String xpointer = "xpointer(/eml/dataSet/" + entityCount + "/attributeList/" + attributeCount + ")";
372
							Individual s1 = m.createIndividual(ont.getURI() + "#" + xpointer, fragmentSelectorClass);
373
							s1.addLiteral(rdfValue, xpointer);
374
							s1.addProperty(conformsToProperty, "http://www.w3.org/TR/xptr/");
375
							
376
							// statements about the annotation
377
							a1.addProperty(hasBodyProperty, m1);
378
							a1.addProperty(hasTargetProperty, t1);
379
							t1.addProperty(hasSourceProperty, meta1);
380
							t1.addProperty(hasSelectorProperty, s1);
381
							//a1.addProperty(annotatedByProperty, p1);
382
							
383
							// describe the measurement in terms of restrictions
384
							if (standard != null) {
385
								AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, usesStandard, standard);
386
								m1.addOntClass(avfr);
387
							}
388
							if (characteristic != null) {
389
								AllValuesFromRestriction avfr = m.createAllValuesFromRestriction(null, ofCharacteristic, characteristic);
390
								m1.addOntClass(avfr);
391
							}
392
							
393
							// attach to the observation
394
							// TODO: evaluate whether the measurement can apply to the given observed entity
395
							o1.addProperty(hasMeasurement, m1);
396
						}
397
						attributeCount++;
398
						
399
					}
400
				}
401
				entityCount++;
402
			}
403
		}
404
		
405
		StringWriter sw = new StringWriter();
406
		// only write the base model
407
		//m.write(sw, "RDF/XML-ABBREV");
408
		m.write(sw, null);
409

    
410
		return sw.toString();
411
		
412
	}
413
	
414
	private Resource lookupStandard(OntClass standardClass, Attribute attribute) {
415
		// what's our unit?
416
		String unit = attribute.getUnit().toLowerCase();
417
		
418
		/*
419
		boolean found = false;
420
		List<String> tokens = Arrays.asList(unit.split(" "));
421
		ExtendedIterator iter = standardClass.listSubClasses(false);
422
		while (iter.hasNext()) {
423
			OntClass subclass = (OntClass) iter.next();
424
			String subclassName = subclass.getLocalName().toLowerCase();
425
			logMetacat.debug("subclass: " + subclassName);
426
			if (tokens.contains(subclassName)) {
427
				found = true;
428
			}
429
			if (subclass.hasLabel(unit, null)) {
430
				found = true;
431
			}
432
			if (found) {
433
				return subclass;
434
			}
435
		}
436
		*/
437
		
438
		// try to look it up if we got this far
439
		return BioPortalService.lookupAnnotationClass(standardClass, unit, OBOE_SBC);
440
	}
441
	
442
	private Resource lookupCharacteristic(OntClass characteristicClass, Attribute attribute) {
443
		// what are we looking for?
444
		String label = attribute.getLabel().toLowerCase();
445
		String definition = attribute.getDefinition();
446
		String text = label + " " + definition;
447
		
448
		/*
449
		// find something that matches		
450
		boolean found = false;
451
		List<String> tokens = Arrays.asList(label.split(" "));
452
		ExtendedIterator iter = characteristicClass.listSubClasses();
453
		while (iter.hasNext()) {
454
			OntClass subclass = (OntClass) iter.next();
455
			String subclassName = subclass.getLocalName().toLowerCase();
456
			logMetacat.debug("subclass: " + subclassName);
457
			if (tokens.contains(subclassName)) {
458
				found = true;
459
			}
460
			if (subclass.hasLabel(label, null)) {
461
				found = true;
462
			}
463
			if (found) {
464
				return subclass;
465
			}
466
		}
467
		*/
468
		
469
		// try to look it up from the service
470
		return BioPortalService.lookupAnnotationClass(characteristicClass, text, OBOE_SBC);
471
		
472
	}
473
	
474
	private Resource lookupEntity(OntClass entityClass, Entity entity) {
475
		// what's our description like?
476
		String name = entity.getName();
477
		String definition = entity.getDefinition();
478
		
479
		// try to look it up if we got this far
480
		return BioPortalService.lookupAnnotationClass(entityClass, definition, OBOE_SBC);
481
		
482
	}
483
	
484
	private DataPackage getDataPackage(Identifier pid) throws Exception {
485
		// for using the MN API as the MN itself
486
		MockHttpServletRequest request = new MockHttpServletRequest(null, null, null);
487
		Session session = new Session();
488
        Subject subject = MNodeService.getInstance(request).getCapabilities().getSubject(0);
489
        session.setSubject(subject);
490
		InputStream emlStream = MNodeService.getInstance(request).get(session, pid);
491

    
492
		// parse the metadata
493
		DataPackageParserInterface parser = new Eml200DataPackageParser();
494
		parser.parse(emlStream);
495
		DataPackage dataPackage = parser.getDataPackage();
496
		return dataPackage;
497
	}
498

    
499
	private void summarize(List<Identifier> identifiers) throws SQLException {
500
		
501
		DBConnection dbconn = null;
502

    
503
		try {
504
			dbconn = DBConnectionPool.getDBConnection("DatapackageSummarizer.summarize");
505
			
506
			PreparedStatement dropStatement = dbconn.prepareStatement("DROP TABLE IF EXISTS entity_summary");
507
			dropStatement.execute();
508
	
509
			PreparedStatement createStatement = dbconn.prepareStatement(
510
					"CREATE TABLE entity_summary (" +
511
					"guid text, " +
512
					"title text, " +
513
					"entity text," +
514
					"attributeName text," +
515
					"attributeLabel text," +
516
					"attributeDefinition text," +
517
					"attributeType text," +
518
					"attributeScale text," +
519
					"attributeUnitType text," +
520
					"attributeUnit text," +
521
					"attributeDomain text" +
522
					")");
523
			createStatement.execute();
524
			
525
			PreparedStatement insertStatement = dbconn.prepareStatement(
526
					"INSERT INTO entity_summary " +
527
					"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
528
			
529
			for (Identifier pid: identifiers) {
530
			
531
				logMetacat.debug("Parsing pid: " + pid.getValue());
532
				
533
				try {
534
					
535
					// get the package
536
					DataPackage dataPackage = this.getDataPackage(pid);
537
					String title = dataPackage.getTitle();
538
					logMetacat.debug("Title: " + title);
539
					
540
					Entity[] entities = dataPackage.getEntityList();
541
					if (entities != null) {
542
						for (Entity entity: entities) {
543
							String entityName = entity.getName();
544
							logMetacat.debug("Entity name: " + entityName);
545
							Attribute[] attributes = entity.getAttributeList().getAttributes();
546
							for (Attribute attribute: attributes) {
547
								String attributeName = attribute.getName();
548
								String attributeLabel = attribute.getLabel();
549
								String attributeDefinition = attribute.getDefinition();
550
								String attributeType = attribute.getAttributeType();
551
								String attributeScale = attribute.getMeasurementScale();
552
								String attributeUnitType = attribute.getUnitType();
553
								String attributeUnit = attribute.getUnit();
554
								String attributeDomain = attribute.getDomain().getClass().getSimpleName();
555
	
556
								logMetacat.debug("Attribute name: " + attributeName);
557
								logMetacat.debug("Attribute label: " + attributeLabel);
558
								logMetacat.debug("Attribute definition: " + attributeDefinition);
559
								logMetacat.debug("Attribute type: " + attributeType);
560
								logMetacat.debug("Attribute scale: " + attributeScale);
561
								logMetacat.debug("Attribute unit type: " + attributeUnitType);
562
								logMetacat.debug("Attribute unit: " + attributeUnit);
563
								logMetacat.debug("Attribute domain: " + attributeDomain);
564
								
565
								// set the values for this attribute
566
								insertStatement.setString(1, pid.getValue());
567
								insertStatement.setString(2, title);
568
								insertStatement.setString(3, entityName);
569
								insertStatement.setString(4, attributeName);
570
								insertStatement.setString(5, attributeLabel);
571
								insertStatement.setString(6, attributeDefinition);
572
								insertStatement.setString(7, attributeType);
573
								insertStatement.setString(8, attributeScale);
574
								insertStatement.setString(9, attributeUnitType);
575
								insertStatement.setString(10, attributeUnit);
576
								insertStatement.setString(11, attributeDomain);
577
								insertStatement.execute();
578
								
579
							}		
580
						}
581
					}
582
					
583
				} catch (Exception e) {
584
					logMetacat.warn("error parsing metadata for: " + pid.getValue(), e);
585
				}
586
			}
587
		} catch (SQLException sqle) {
588
			// just throw it
589
			throw sqle;
590
		} finally {
591
			if (dbconn != null) {
592
				DBConnectionPool.returnDBConnection(dbconn, 0);
593
				dbconn.close();
594
			}
595
		}
596
	}
597
	
598
	public static void main(String[] args) throws Exception {
599
		// set up the properties based on the test/deployed configuration of the workspace
600
			SortedProperties testProperties = new SortedProperties("test/test.properties");
601
			testProperties.load();
602
			String metacatContextDir = testProperties.getProperty("metacat.contextDir");
603
			PropertyService.getInstance(metacatContextDir + "/WEB-INF");
604
			
605
			testGenerate();
606
//			testSummary();
607
			System.exit(0);
608
	}
609
	
610
	public static void testGenerate() throws Exception {
611
		Identifier metadataPid = new Identifier();
612
		metadataPid.setValue("tao.1.4");
613
		DatapackageSummarizer ds = new DatapackageSummarizer();
614
		String rdfString = ds.generateAnnotation(metadataPid);
615
		logMetacat.info("RDF annotation: \n" + rdfString);
616
		
617
	}
618
	
619
	public static void testSummary() throws Exception {
620
		
621
		// summarize the packages
622
		DatapackageSummarizer ds = new DatapackageSummarizer();
623
		List<Identifier> identifiers = new ArrayList<Identifier>();
624
		Map<Integer, String> serverCodes = ReplicationService.getServerCodes();
625

    
626
		// select the metadata ids we want to summarize
627
		boolean includeReplicas = true;
628
		Iterator<Integer> codeIter = Arrays.asList(new Integer[] {1}).iterator();
629
		if (includeReplicas ) {
630
			codeIter = serverCodes.keySet().iterator();
631
		}
632
		
633
		Vector<String> idList = new Vector<String>();
634
		while (codeIter.hasNext()) {
635
			int serverLocation = codeIter.next();
636
			Vector<String> idList0 = DBUtil.getAllDocidsByType(DocumentImpl.EML2_0_0NAMESPACE, false, serverLocation);
637
			Vector<String> idList1 = DBUtil.getAllDocidsByType(DocumentImpl.EML2_0_1NAMESPACE, false, serverLocation);
638
			Vector<String> idList2 = DBUtil.getAllDocidsByType(DocumentImpl.EML2_1_0NAMESPACE, false, serverLocation);
639
			Vector<String> idList3 = DBUtil.getAllDocidsByType(DocumentImpl.EML2_1_1NAMESPACE, false, serverLocation);
640
			
641
			idList.addAll(idList0);
642
			idList.addAll(idList1);
643
			idList.addAll(idList2);
644
			idList.addAll(idList3);
645
		
646
		}
647
		
648
		// go through all the identifiers now
649
		for (String localId : idList) {
650
			try {
651
				String guid = IdentifierManager.getInstance().getGUID(
652
						DocumentUtil.getDocIdFromAccessionNumber(localId), 
653
						DocumentUtil.getRevisionFromAccessionNumber(localId));
654
				Identifier pid = new Identifier();
655
				pid.setValue(guid);
656
				identifiers.add(pid);
657
			} catch (McdbDocNotFoundException nfe) {
658
				// just skip it
659
				continue;
660
			}
661
		}
662
		ds.summarize(identifiers);
663
		System.exit(0);
664
	}
665
	
666
}
(2-2/3)