View Javadoc

1   package uk.ac.cam.spectra;
2   
3   import java.text.ParseException;
4   import java.util.Date;
5   
6   import org.apache.log4j.Logger;
7   
8   import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
9   import com.hp.hpl.jena.rdf.model.Literal;
10  import com.hp.hpl.jena.rdf.model.Model;
11  import com.hp.hpl.jena.rdf.model.RDFNode;
12  import com.hp.hpl.jena.rdf.model.Resource;
13  
14  /**
15   * Metadata property with a Date literal value.
16   * @see uk.ac.cam.spectra.MetadataProperty
17   * @author Jim Downing
18   */
19  public class DateProperty extends LiteralProperty implements MetadataProperty {
20  
21  	/**
22  	 * 
23  	 */
24  	private static final long serialVersionUID = -5300575852132044416L;
25  	private static final Logger LOG = Logger.getLogger(DateProperty.class);
26  
27  	public DateProperty(String ns, String el) {
28  		super(ns, el);
29  	}
30  
31  	@Override
32  	public String getXsiType() {
33  		return Constants.XSI_DATE;
34  	}
35  
36  	@Override
37  	public boolean valid(RDFNode nd, Model m) {
38  		if (super.valid(nd, m)) {
39  			Literal l = (Literal) nd;
40  			if (!l.getDatatypeURI().equals(getXsiType())) {
41  				LOG.debug("Datatypes did not match. Expected: " + getXsiType()
42  						+ ". Got: " + l.getDatatypeURI());
43  				return false;
44  			}
45  		}
46  		return true;
47  	}
48  
49  	public Date decodeDate(Literal l) {
50  		try {
51  			return Constants.SIMPLE_ISO_DATE_FORMAT.parse(l.getLexicalForm());
52  		} catch (ParseException e) {
53  			LOG.warn("Could not parse " + l.getLexicalForm()
54  					+ " as an ISO date");
55  			return null;
56  		}
57  	}
58  
59  	@Override
60  	public void add(Resource resource, Object value) {
61  		if(value == null) {
62  			throw new IllegalArgumentException("value must not be null");
63  		}
64  		if (!(value instanceof Date)) {
65  			throw new IllegalArgumentException(value + " is not a date");
66  		}
67  		Model m = resource.getModel();
68  		Literal l = m.createTypedLiteral(Constants.SIMPLE_ISO_DATE_FORMAT
69  				.format((Date) value), XSDDatatype.XSDdate);
70  		resource.addProperty(asProperty(m), l);
71  	}
72  
73  }