package com.ldodds.sparql; import com.hp.hpl.jena.query.expr.ExprEvalException; import com.hp.hpl.jena.query.expr.NodeValue; import com.hp.hpl.jena.query.function.FunctionBase1; import java.net.*; import java.text.SimpleDateFormat; import java.util.*; public class LastModified extends FunctionBase1 { private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); private Map _cache; public LastModified() { _cache = new HashMap(); } public NodeValue exec(NodeValue nodeValue) { String value = nodeValue.asString(); if (_cache.containsKey(value)) { return (NodeValue)_cache.get(value); } if ( !nodeValue.asNode().isURI() ) throw new ExprEvalException("Attempt to get Last-Modified for a literal"); try { String lastModified = getLastModified( nodeValue.asString() ); NodeValue date = NodeValue.makeDate(lastModified); _cache.put(value, date); return date; } catch (Exception e) { throw new ExprEvalException("Error fetching Last-Modified", e); } } public String getLastModified(String link) throws Exception { URL url = new URL(link); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); long secs = connection.getLastModified(); String xsdDate = dateToXSD(secs); return xsdDate; } public String dateToXSD(long secs) { Date date = new Date(secs); return format.format(date); } }