Skip to content

Commit

Permalink
[New] Add function add-days
Browse files Browse the repository at this point in the history
  • Loading branch information
blcham committed Oct 22, 2021
1 parent 264cfdf commit 5fe4e52
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cz.cvut.spipes.function.time;

import cz.cvut.spipes.function.ValueFunction;
import org.apache.jena.datatypes.RDFDatatype;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.datatypes.xsd.impl.XSDDateType;
import org.apache.jena.graph.Node;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.function.FunctionEnv;
import org.topbraid.spin.arq.AbstractFunction2;

import java.time.LocalDate;
import java.util.Optional;

/**
* Extend specified `date` by number of `days`. Return typed literal with same datatype.
* Currently, supports only xsd:date datatype.
*/
public class AddDays extends AbstractFunction2 implements ValueFunction {


private static final String TYPE_IRI = "http://onto.fel.cvut.cz/ontologies/lib/function/time/add-days";

@Override
public String getTypeURI() {
return TYPE_IRI;
}

@Override
protected NodeValue exec(Node date, Node days, FunctionEnv env) {

Long daysToAdd = getDays(days);

if (getDatatype(date).equals(XSDDatatype.XSDdate) && daysToAdd != null) {

String newDate = LocalDate.parse(date.getLiteral().getValue().toString()).plusDays(daysToAdd).toString();

return NodeValue.makeNode(newDate, XSDDatatype.XSDdate);
}

return null;
}

private Long getDays(Node days) {
return Optional.of(days)
.filter(Node::isLiteral)
.filter(n -> n.getLiteralValue() instanceof Integer)
.map(n -> ((Integer) n.getLiteralValue()).longValue())
.orElse(null);
}

RDFDatatype getDatatype(Node date) {

return Optional.of(date)
.filter(Node::isLiteral)
.filter(n -> n.getLiteralDatatype() instanceof XSDDateType)
.map(Node::getLiteralDatatype)
.orElse(null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cz.cvut.spipes.function.time;

import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.graph.Node;
import org.apache.jena.sparql.expr.NodeValue;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class AddDaysTest {

@Test
public void execReturnsTimeFromPast() {

AddDays addDays = new AddDays();
Node date = getDateNode("2022-01-01").asNode();
Node days = NodeValue.makeNodeDecimal("-1").asNode();

NodeValue returnedDate = addDays.exec(date, days, null);

NodeValue expectedDate = getDateNode("2021-12-31");
assertEquals(expectedDate, returnedDate);
}


private NodeValue getDateNode(String date) {
return NodeValue.makeNode(
date,
null,
XSDDatatype.XSDdate.getURI()
);
}
}

0 comments on commit 5fe4e52

Please sign in to comment.