org.apache.jena.datatypes.xsd.XSDDatatype Java Examples

The following examples show how to use org.apache.jena.datatypes.xsd.XSDDatatype. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RdfStreamWriterTest.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private Dataset getDataset(String prefix) {
    Dataset dataset = createDataset(prefix);
    dataset.addIdentifier(new Identifier(createValue(prefix, "identifier")));
    dataset.addLanguage(new Language("en"));
    dataset.addKeyword(createKeyword(DATASET));
    dataset.setAccrualPeriodicity(createAccrualPeriodicity());
    dataset.addTheme(createTheme());
    dataset.setPublisher(createPubisher(DATASET));
    dataset.setModified(new Modified(XSDDatatype.XSDdateTime, "2019-04-17T00:00:00Z"));
    dataset.setIssued(new Issued(XSDDatatype.XSDdateTime, "2019-04-17T00:00:00Z"));
    dataset.addContactPoint(createContactPoint(DATASET));
    dataset.setAccessRights(createAccessRights());
    dataset.addLandingPage(createLandingPage(DATASET));
    dataset.addDistribution(createDistribution(DATASET));
    dataset.addSpatial(createSpatial());
    return dataset;
}
 
Example #2
Source File: SDADatasetAccessor.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Model makeSampleModel() {
	String BASE = "http://example/";
	
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefix("", BASE);
	Resource r1 = model.createResource(BASE + "r1");
	Resource r2 = model.createResource(BASE + "r2");
	Property p1 = model.createProperty(BASE + "p");
	Property p2 = model.createProperty(BASE + "p2");
	RDFNode v1 = model.createTypedLiteral("1", XSDDatatype.XSDinteger);
	RDFNode v2 = model.createTypedLiteral("2", XSDDatatype.XSDinteger);

	r1.addProperty(p1, v1).addProperty(p1, v2);
	r1.addProperty(p2, v1).addProperty(p2, v2);
	r2.addProperty(p1, v1).addProperty(p1, v2);

	return model;
}
 
Example #3
Source File: SDADatasetAccessor.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Model makeSampleModel() {
	String BASE = "http://example/";
	
	Model model = ModelFactory.createDefaultModel();
	model.setNsPrefix("", BASE);
	Resource r1 = model.createResource(BASE + "r1");
	Resource r2 = model.createResource(BASE + "r2");
	Property p1 = model.createProperty(BASE + "p");
	Property p2 = model.createProperty(BASE + "p2");
	RDFNode v1 = model.createTypedLiteral("1", XSDDatatype.XSDinteger);
	RDFNode v2 = model.createTypedLiteral("2", XSDDatatype.XSDinteger);

	r1.addProperty(p1, v1).addProperty(p1, v2);
	r1.addProperty(p2, v1).addProperty(p2, v2);
	r2.addProperty(p1, v1).addProperty(p1, v2);

	return model;
}
 
Example #4
Source File: ComponentParameterWriter.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource = ElementWriter.copyElementResourceInModel(componentParameter, model);

    // rdf:type sh:ComponentParameter
    resource.addProperty(RDF.type, SHACL.ParameterCls);

    // sh:path sh:argX
    resource.addProperty(SHACL.path, componentParameter.getPredicate()) ;

    //Optional
    if (componentParameter.isOptional()) {
        resource.addProperty(SHACL.optional, ResourceFactory.createTypedLiteral("true", XSDDatatype.XSDboolean)) ;
    }
    return resource;
}
 
Example #5
Source File: AlgebraExec.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private static Model makeModel()
{
    String BASE = "http://example/" ;
    Model model = ModelFactory.createDefaultModel() ;
    model.setNsPrefix("", BASE) ;
    Resource r1 = model.createResource(BASE+"r1") ;
    Resource r2 = model.createResource(BASE+"r2") ;
    Property p1 = model.createProperty(BASE+"p") ;
    Property p2 = model.createProperty(BASE+"p2") ;
    RDFNode v1 = model.createTypedLiteral("1", XSDDatatype.XSDinteger) ;
    RDFNode v2 = model.createTypedLiteral("2", XSDDatatype.XSDinteger) ;
    
    r1.addProperty(p1, v1).addProperty(p1, v2) ;
    r1.addProperty(p2, v1).addProperty(p2, v2) ;
    r2.addProperty(p1, v1).addProperty(p1, v2) ;
    
    return model  ;
}
 
Example #6
Source File: JSFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
public static Node getNodeFlex(Object obj) {
	Node fromTerm = getNode(obj);
	if(fromTerm != null) {
		return fromTerm;
	}
	else if(obj instanceof Integer) {
		return JenaDatatypes.createInteger((Integer)obj).asNode();
	}
	else if(obj instanceof Number) {
		return NodeFactory.createLiteral(obj.toString(), XSDDatatype.XSDdecimal);
	}
	else if(obj instanceof Boolean) {
		return ((Boolean)obj) ? JenaDatatypes.TRUE.asNode() : JenaDatatypes.FALSE.asNode();
	}
	else if(obj != null) {
		return NodeFactory.createLiteral(obj.toString());
	}
	else {
		return null;
	}
}
 
Example #7
Source File: TriplePatternFragmentBase.java    From Server.Java with MIT License 6 votes vote down vote up
@Override
public void addMetadata( final Model model )
{
    super.addMetadata( model );

    final Resource fragmentId = model.createResource( fragmentURL );

    final Literal totalTyped = model.createTypedLiteral( totalSize,
                                                  XSDDatatype.XSDinteger );
    final Literal limitTyped = model.createTypedLiteral( getMaxPageSize(),
                                                  XSDDatatype.XSDinteger );

    fragmentId.addLiteral( CommonResources.VOID_TRIPLES, totalTyped );
    fragmentId.addLiteral( CommonResources.HYDRA_TOTALITEMS, totalTyped );
    fragmentId.addLiteral( CommonResources.HYDRA_ITEMSPERPAGE, limitTyped );
}
 
Example #8
Source File: GroupConcatExpression.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	StringBuffer sb = new StringBuffer();
	ExtendedIterator<RDFNode> it = evalInput(focusNode, context);
	while(it.hasNext()) {
		RDFNode node = it.next();
		if(node.isLiteral() && XSDDatatype.XSDstring.getURI().equals(node.asNode().getLiteralDatatypeURI())) {
			sb.append(node.asNode().getLiteralLexicalForm());
		}
		else {
			String label = RDFLabels.get().getNodeLabel(node);
			if(label != null) {
				sb.append(label);
			}
		}
		if(separator != null && it.hasNext()) {
			sb.append(separator);
		}
	}
	List<RDFNode> results = Collections.singletonList(ResourceFactory.createTypedLiteral(sb.toString()));
	return WrappedIterator.create(results.iterator());
}
 
Example #9
Source File: TemplateImpl.java    From Processor with Apache License 2.0 6 votes vote down vote up
@Override
public UriTemplate getMatch()
{
    Statement path = getProperty(LDT.match);
    if (path != null)
    {
        if (!path.getObject().isLiteral() ||
                path.getObject().asLiteral().getDatatype() == null ||
                !path.getObject().asLiteral().getDatatype().equals(XSDDatatype.XSDstring))
        {
            if (log.isErrorEnabled()) log.error("Class {} property {} is not an xsd:string literal", getURI(), LDT.match);
            throw new OntologyException("Class '" + getURI() + "' property '" + LDT.match + "' is not an xsd:string literal");
        }
        
        return new UriTemplate(path.getString());
    }
    
    return null;
}
 
Example #10
Source File: RDFNodeFactory.java    From Processor with Apache License 2.0 6 votes vote down vote up
public static final RDFNode createTyped(String value, Resource valueType)
   {
if (value == null) throw new IllegalArgumentException("Param value cannot be null");

       // without value type, return default xsd:string value
       if (valueType == null) return ResourceFactory.createTypedLiteral(value, XSDDatatype.XSDstring);

       // if value type is from XSD namespace, value is treated as typed literal with XSD datatype
       if (valueType.getNameSpace().equals(XSD.getURI()))
       {
           RDFDatatype dataType = NodeFactory.getType(valueType.getURI());
           return ResourceFactory.createTypedLiteral(value, dataType);
       }
       // otherwise, value is treated as URI resource
       else
           return ResourceFactory.createResource(value);
   }
 
Example #11
Source File: Skolemizer.java    From Processor with Apache License 2.0 6 votes vote down vote up
protected String getStringValue(OntClass ontClass, Property property)
{
    if (ontClass == null) throw new IllegalArgumentException("OntClass cannot be null");
    if (property == null) throw new IllegalArgumentException("Property cannot be null");

    if (ontClass.hasProperty(property))
    {
        if (!ontClass.getPropertyValue(property).isLiteral() ||
                ontClass.getPropertyValue(property).asLiteral().getDatatype() == null ||
                !ontClass.getPropertyValue(property).asLiteral().getDatatype().equals(XSDDatatype.XSDstring))
        {
            if (log.isErrorEnabled()) log.error("Class {} property {} is not an xsd:string literal", ontClass, property);
            throw new OntologyException("Class '" + ontClass + "' property '" + property + "' is not an xsd:string literal");
        }
        
        return ontClass.getPropertyValue(property).asLiteral().getString();
    }
    
    return null;
}
 
Example #12
Source File: CSVParser.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Binding toBinding(String[] row) {
	BindingHashMap result = new BindingHashMap();
	for (int i = 0; i < row.length; i++) {
		if (isUnboundValue(row[i]))
			continue;
		result.add(getVar(i), NodeFactory.createLiteral(sanitizeString(row[i])));
	}
	// Add current row number as ?ROWNUM
	result.add(TarqlQuery.ROWNUM, NodeFactory.createLiteral(
			Integer.toString(rownum), XSDDatatype.XSDinteger));
	return result;
}
 
Example #13
Source File: AbstractDatatype.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Deprecated
private static RDFDatatype getDataType(DataType dataType) {
    switch (dataType) {
        case Date:
            return XSDDatatype.XSDdate;
        case DateTime:
            return XSDDatatype.XSDdateTime;
        case GEO_JSON:
            return RDFDataTypes.GEO_JSON;
        case WKT_LITERAL:
            return RDFDataTypes.WKT_LITERAL;
        default:
            return new BaseDatatype(dataType.getType());
    }
}
 
Example #14
Source File: PrefixUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Resource addNamespace(Resource ontology, String prefix, String namespace) {
	Resource declaration = ontology.getModel().createResource(namespace + SH.PrefixDeclaration.getLocalName(), SH.PrefixDeclaration);
	ontology.addProperty(SH.declare, declaration);
	declaration.addProperty(SH.prefix, prefix);
	declaration.addProperty(SH.namespace, ResourceFactory.createTypedLiteral(namespace, XSDDatatype.XSDanyURI));
	return declaration;
}
 
Example #15
Source File: RdfStreamWriterTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void testModelCreation() throws XMLStreamException, IOException {
    RDF rdf = new RDF();
    Dataset dataset = getDataset(CATALOG);
    Catalog catalog = createCatalog(CATALOG, dataset);
    catalog.addLanguage(new Language("en"));
    catalog.setHomepage(new Homepage(createValue(CATALOG, "homepage")));
    catalog.setModified(new Modified(XSDDatatype.XSDdateTime, "2019-04-17T00:00:00Z"));
    catalog.setIssued(new Issued(XSDDatatype.XSDdateTime, "2019-04-17T00:00:00Z"));
    catalog.addLanguage(new Language("en"));
    catalog.addThemeTaxonomy(new ThemeTaxonomy("http://publications.europa.eu/resource/authority/data-theme"));
    rdf.addElements(catalog);

    Distribution distribution = new Distribution(new AccessURL("http://accessurl.test.org"));
    distribution.addTitle(createTitle(DISTRIBUTION));
    distribution.addDownloadURL(new DownloadURL("http://downloadurl.test.org"));
    distribution.setFormat(new Format(createValue(DISTRIBUTION, "format")));
    distribution.setLicense(new License(createValue(DISTRIBUTION, "license")));
    rdf.addElements(distribution);

    Organization organization = new Organization();
    organization.setName(new Name("name"));
    organization.setmBox(new MBox("[email protected]"));
    rdf.addElements(organization);

    Model model = ModelFactory.createDefaultModel();
    rdf.addToModel(model);

    RDFWriter w = model.getWriter("RDF/XML-ABBREV");
    w.setProperty("showXMLDeclaration", "true");
    w.setProperty("tab", "4");
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        new RdfStreamWriter(EncodingContext.of(EncoderFlags.ENCODER_REPOSITORY, new EncoderRepository()), out,
                rdf);
    }

}
 
Example #16
Source File: OpenAnnotationRDFWriter.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Adds a single {@link GeneAnnotation} to a model
 *
 * @param ann
 */
public void add(GeneAnnotation ann) {
	if (ann == null) {
		return;
	}
	final Bioentity bioentity = ann.getBioentityObject();
	// TODO - why are we trimming here?
	final String isoForm = StringUtils.trimToNull(ann.getGeneProductForm());

	// TODO: don't use blank nodes
	Resource rAnn = model.createResource();
	Resource rBioentity = createResourceFromId(bioentity.getId());
	Resource rDescriptor = createResourceFromId(ann.getCls());

	model.add(rAnn, RDF.type, getAnnotationType());
	model.add(rAnn, getAnnotationToBioentityProperty(), rBioentity);
	model.add(rAnn, getAnnotationToDescriptorProperty(), rDescriptor);

	// TODO
	if (isoForm != null) {
		//Resource x = createResourceFromId(isoForm);
		//model.add(rAnn, getAnnotationToIsoformProperty(), x);

	}

	if (ann.getEcoEvidenceCls() != null) {
		Resource rEvidenceType = createResourceFromId(ann.getEcoEvidenceCls());
		model.add(rAnn, getAnnotationToEvidenceProperty(), rEvidenceType);
	}

	for (String refId : ann.getReferenceIds()) {
		//model.add(rAnn, getAnnotationToReferencesProperty(), rDescriptor);
	}

	/// TODO
	if (ann.isNegated()) {
	}


	for (List<ExtensionExpression> xl : ann.getExtensionExpressions()) {
		for (ExtensionExpression x : xl) {
			if (false) {
				// TODO - relations ontology needs loaded for mapping
				Resource xn = model.createResource(); // TODO - alternative to blank nodes?
				model.add(xn, 
						createPropertyFromId(x.getRelation()), 
						createResourceFromId(x.getCls()));
				model.add(rAnn, getAnnotationToExtensionProperty(), xn);
			}
		}
	}

	Pair<String, String> actsOnTaxon = ann.getActsOnTaxonId();
	if (actsOnTaxon != null) {
		// TODO
	}

	String date = ann.getLastUpdateDate();
	if (date != null) {
		// TODO - convert to xsd:date if use oa
		String isoDate = 
				date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
		Literal xsdDate = ResourceFactory.createTypedLiteral (isoDate, XSDDatatype.XSDdate);
		model.add(rAnn, getAnnotationDateProperty(), xsdDate);
	}

	if (ann.getAssignedBy() != null) {
		// TODO - use ORCID?
		model.add(rAnn, getAssignedByProperty(), ann.getAssignedBy());
	}

	for (String w : ann.getWithInfos()) {
		model.add(rAnn, getAnnotationToWithProperty(), createResourceFromId(w));

	}

}
 
Example #17
Source File: DataIDGenerator.java    From gerbil with GNU Affero General Public License v3.0 4 votes vote down vote up
public void createExperimentTask(Model model, ExperimentTaskStatus result, Resource superExpTask,
        List<Resource> experimentTasks) {
    // create Resource
    Resource experimentTask = model.createResource(generateExperimentTaskUri(result.idInDb));
    experimentTasks.add(experimentTask);
    if (model.containsResource(experimentTask)) {
        return;
    }
    experimentTask.addProperty(RDF.type, CUBE.Observation);

    // add annotator and dataset
    experimentTask.addProperty(GERBIL.annotator,
            gerbilURL + ANNOTATOR_DATAID + DataIDUtils.treatsNames(result.dataset) + DATAID_EXTENSION);
    experimentTask.addProperty(GERBIL.dataset,
            gerbilURL + DATASET_DATAID + DataIDUtils.treatsNames(result.annotator) + DATAID_EXTENSION);

    // set the status of this task
    model.add(experimentTask, GERBIL.statusCode, model.createTypedLiteral(result.state));

    if (superExpTask != null) {
        model.add(experimentTask, GERBIL.subExperimentOf, superExpTask);
    }

    // If this task has been finished
    if (ExperimentTaskStateHelper.taskFinished(result)) {
        // creating and setting literals for the current experiment
        Map<String, TaskResult> resMap = result.getResultsMap();
        String propertyUri;
        for(String resName: resMap.keySet()) {
        	 propertyUri = GERBIL.getURI() + resName.replace(" ", "_");
        	 model.add(experimentTask, model.createProperty(propertyUri), model.createTypedLiteral(
                     String.valueOf(resMap.get(resName).getResValue()), XSDDatatype.XSDdecimal));
        }
        if (result.hasSubTasks()) {
            for (ExperimentTaskStatus subResult : result.getSubTasks()) {
                createExperimentTask(model, subResult, experimentTask, experimentTasks);
            }
        }
    }

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(result.timestamp);
    model.add(experimentTask, GERBIL.timestamp, model.createTypedLiteral(cal));
}
 
Example #18
Source File: PredicateMappingsDataSet.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
protected Node intToNode(int val) {
	return NodeFactory.createLiteral(Long.toString(val), "", XSDDatatype.XSDinteger) ;
}
 
Example #19
Source File: JenaDatatypes.java    From shacl with Apache License 2.0 4 votes vote down vote up
public static Literal createInteger(int value) {
	return ResourceFactory.createTypedLiteral("" + value, XSDDatatype.XSDinteger);
}
 
Example #20
Source File: JenaDatatypes.java    From shacl with Apache License 2.0 4 votes vote down vote up
public static Literal createDecimal(int value) {
	return ResourceFactory.createTypedLiteral("" + value, XSDDatatype.XSDdecimal);
}
 
Example #21
Source File: TestCaseResultWriter.java    From RDFUnit with Apache License 2.0 4 votes vote down vote up
@Override
public Resource write(Model model) {
    Resource resource;
    if (testCaseResult.getElement().isAnon()) {
        resource = model.createResource(JenaUtils.getUniqueIri(executionUri + "/"));
    } else {
        resource = ElementWriter.copyElementResourceInModel(testCaseResult, model);
    }

    // general properties
    resource
            .addProperty(RDF.type, RDFUNITv.TestCaseResult)
            .addProperty(PROV.wasGeneratedBy, model.createResource(executionUri))
            .addProperty(RDFUNITv.testCase, model.createResource(testCaseResult.getTestCaseUri()))
            .addProperty(DCTerms.date, model.createTypedLiteral(testCaseResult.getTimestamp(), XSDDatatype.XSDdateTime));

    if (testCaseResult instanceof StatusTestCaseResult) {
        resource
                .addProperty(RDF.type, RDFUNITv.StatusTestCaseResult)
                .addProperty(RDFUNITv.resultStatus, model.createResource(((StatusTestCaseResult) testCaseResult).getStatus().getUri()))
                .addProperty(DCTerms.description, testCaseResult.getMessage())
                .addProperty(RDFUNITv.testCaseLogLevel, model.createResource(testCaseResult.getSeverity().getUri()))
                ;
    }

    if (testCaseResult instanceof AggregatedTestCaseResult) {
        resource
                .addProperty(RDF.type, RDFUNITv.AggregatedTestResult)
                .addProperty(RDFUNITv.resultCount,
                        ResourceFactory.createTypedLiteral(Long.toString(((AggregatedTestCaseResult) testCaseResult).getErrorCount()), XSDDatatype.XSDinteger))
                .addProperty(RDFUNITv.resultPrevalence,
                        ResourceFactory.createTypedLiteral(Long.toString(((AggregatedTestCaseResult) testCaseResult).getPrevalenceCount().orElse(-1L)), XSDDatatype.XSDinteger));
    }

    if (testCaseResult instanceof ShaclLiteTestCaseResult) {
        resource.addProperty(RDF.type, SHACL.ValidationResult)
        ;
    }

    if (testCaseResult instanceof ShaclTestCaseResult) {

        Collection<PropertyValuePair> annotations = ((ShaclTestCaseResult) testCaseResult).getResultAnnotations();
        for (PropertyValuePair annotation : annotations) {
            for (RDFNode rdfNode : annotation.getValues()) {


                if (rdfNode.isAnon() && annotation.getProperty().equals(SHACL.resultPath)) {
                    resource.getModel().add(reanonimisePathBlankNodes(resource, rdfNode));
                } else {
                    resource.addProperty(annotation.getProperty(), rdfNode);
                }

            }
        }
        boolean containsMessage = annotations.stream().anyMatch(an -> an.getProperty().equals(SHACL.message));
        if (!containsMessage) {
            resource.addProperty(SHACL.message, testCaseResult.getMessage());
        }
        boolean containsFocusNode = annotations.stream().anyMatch(an -> an.getProperty().equals(SHACL.focusNode));
        if (!containsFocusNode) {
            resource.addProperty(SHACL.focusNode, ((ShaclTestCaseResult) testCaseResult).getFailingNode());
        }
        boolean containsSeverity = annotations.stream().anyMatch(an -> an.getProperty().equals(SHACL.severity));
        if (!containsSeverity) {
            resource.addProperty(SHACL.severity, ResourceFactory.createResource(testCaseResult.getSeverity().getUri()));
        }
    }


    return resource;
}