org.apache.jena.rdf.model.ResourceFactory Java Examples
The following examples show how to use
org.apache.jena.rdf.model.ResourceFactory.
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: DqvReportWriter.java From RDFUnit with Apache License 2.0 | 6 votes |
@Override public Resource write(Model model) { Resource te = null; for (QualityMeasure m: measures) { te = model.createResource(m.getTestExecutionUri()); Resource measureResource = model.createResource(JenaUtils.getUniqueIri()) .addProperty(ResourceFactory.createProperty(DQV_NS + "computedOn"), te) .addProperty(ResourceFactory.createProperty(DQV_NS + "hasMetric"), ResourceFactory.createResource(m.getDqvMetricUri())) .addProperty(ResourceFactory.createProperty(DQV_NS + "value"), Double.toString(m.getValue())) ; te.addProperty(ResourceFactory.createProperty(DQV_NS + "dqv:hasQualityMeasure"), measureResource ); } return te; }
Example #2
Source File: TestCaseGroupAnd.java From RDFUnit with Apache License 2.0 | 6 votes |
public TestCaseGroupAnd(@NonNull Set<? extends TargetBasedTestCase> testCases) { assert(! testCases.isEmpty()); target = testCases.iterator().next().getTarget(); assert(testCases.stream().map(TargetBasedTestCase::getTarget).noneMatch(x -> x != target)); this.resource = ResourceFactory.createProperty(JenaUtils.getUniqueIri()); this.testCases = ImmutableSet.copyOf(testCases); List<TestCaseAnnotation> innerAnnotations = testCases.stream().map(GenericTestCase::getTestCaseAnnotation).collect(Collectors.toList()); String description = "A logical AND constraint component containing the following rules:"; if (innerAnnotations.size() == 1) { description = ""; } description += innerAnnotations.stream().map(TestCaseAnnotation::getDescription).collect(Collectors.joining(", ")); this.testCaseAnnotation = new TestCaseAnnotation( this.resource, innerAnnotations.stream().map(TestCaseAnnotation::getGenerated).findFirst().orElse(TestGenerationType.AutoGenerated), null, innerAnnotations.stream().map(TestCaseAnnotation::getAppliesTo).findFirst().orElse(TestAppliesTo.Dataset), innerAnnotations.stream().map(TestCaseAnnotation::getSourceUri).findFirst().orElse(SHACL.namespace), innerAnnotations.stream().flatMap(t -> t.getReferences().stream()).collect(Collectors.toSet()), description, RLOGLevel.ERROR, // TODO probably needs to provided from shape ImmutableSet.of() //TODO do I have to add annotations by default? ); }
Example #3
Source File: TemplateCallTest.java From Processor with Apache License 2.0 | 6 votes |
public void testArg() { String param1Value = "1", param2Value = "with space"; Resource param3Value = ResourceFactory.createResource("http://whateverest/"); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add(PREDICATE1_LOCAL_NAME, param1Value); queryParams.add(PREDICATE2_LOCAL_NAME, param2Value); queryParams.add(UNUSED_PREDICATE_LOCAL_NAME, param3Value); TemplateCall otherCall = TemplateCall.fromResource(resource, template). arg(param1, ResourceFactory.createPlainLiteral(param1Value)). arg(param2, ResourceFactory.createPlainLiteral(param2Value)). arg(param3, param3Value); assertEquals(call.applyArguments(queryParams).build(), otherCall.build()); }
Example #4
Source File: RDFNodeFactory.java From Processor with Apache License 2.0 | 6 votes |
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 #5
Source File: TestDASHTestCases.java From shacl with Apache License 2.0 | 6 votes |
private static void collectTestCases(File folder, List<TestCase> testCases) throws Exception { for(File f : folder.listFiles()) { if(f.isDirectory()) { collectTestCases(f, testCases); } else if(f.isFile() && f.getName().endsWith(".ttl")) { Model testModel = JenaUtil.createDefaultModel(); InputStream is = new FileInputStream(f); testModel.read(is, "urn:dummy", FileUtils.langTurtle); testModel.add(SHACLSystemModel.getSHACLModel()); Resource ontology = testModel.listStatements(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI)).next().getSubject(); for(TestCaseType type : TestCaseTypes.getTypes()) { testCases.addAll(type.getTestCases(testModel, ontology)); } } } }
Example #6
Source File: GroupConcatExpression.java From shacl with Apache License 2.0 | 6 votes |
@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 #7
Source File: SHACLCTestRunner.java From shacl with Apache License 2.0 | 6 votes |
private void runFile(File compactFile) { try { Model compactModel = JenaUtil.createMemoryModel(); compactModel.read(new FileReader(compactFile), "urn:x-base:default", SHACLC.langName); compactModel.removeAll(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI)); File turtleFile = new File(compactFile.getParentFile(), compactFile.getName().replaceAll(".shaclc", ".ttl")); Model turtleModel = JenaUtil.createMemoryModel(); turtleModel.read(new FileReader(turtleFile), "urn:x-base:default", FileUtils.langTurtle); if(compactModel.getGraph().isIsomorphicWith(turtleModel.getGraph())) { System.out.println("Passed test " + compactFile); } else { System.err.println("Failed test " + compactFile); System.err.println("Turtle: " + ModelPrinter.get().print(turtleModel)); System.err.println("Compact: " + ModelPrinter.get().print(compactModel)); } } catch(Exception ex) { System.err.println("Exception during test " + compactFile + ": " + ex); ex.printStackTrace(); } }
Example #8
Source File: ComponentParameterWriter.java From RDFUnit with Apache License 2.0 | 6 votes |
@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 #9
Source File: String2Node.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public String2Node(String type, String value, short datatype) { if(value.equals("NULL")){ node = null; } else if (value.startsWith(Constants.PREFIX_BLANK_NODE)) { AnonId id = new AnonId(value.substring(Constants.PREFIX_BLANK_NODE.length())); node = ModelFactory.createDefaultModel().createResource(id); } else if (type.equals(Constants.NAME_COLUMN_SUBJECT)) { node = ResourceFactory.createResource(value); } else if (type.equals(Constants.NAME_COLUMN_PREDICATE)) { node = ResourceFactory.createProperty(value); } else if (type.equals(Constants.NAME_COLUMN_OBJECT)) { assignLiteral(value, datatype); } }
Example #10
Source File: String2Node.java From quetzal with Eclipse Public License 2.0 | 6 votes |
public String2Node(String type, String value) { if(value.equals("NULL")){ node = null; } else if (value.startsWith(Constants.PREFIX_BLANK_NODE)) { AnonId id = new AnonId(value.substring(Constants.PREFIX_BLANK_NODE.length())); node = ModelFactory.createDefaultModel().createResource(id); } else if (type.equals(Constants.NAME_COLUMN_SUBJECT)) { node = ResourceFactory.createResource(value); } else if (type.equals(Constants.NAME_COLUMN_PREDICATE)) { node = ResourceFactory.createProperty(value); } else if (type.equals(Constants.NAME_COLUMN_OBJECT)) { assert (false); // mdb change code call other ctor } }
Example #11
Source File: OneM2MContentInstanceMapper.java From SDA with BSD 2-Clause "Simplified" License | 6 votes |
public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); // return "\"" + Double.valueOf(con) + "\"^^xsd:double"; } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); // return "\"" + Float.valueOf(con) + "\"^^xsd:float"; } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); // return "\"" + con + "\"^^xsd:string"; } } }
Example #12
Source File: RdfStreamReaderDatasetTest.java From RDFUnit with Apache License 2.0 | 6 votes |
@Before public void setUp() { Model defaultModel = ModelFactory.createDefaultModel(); defaultModel.add( ResourceFactory.createResource("http://rdfunit.aksw.org"), OWL.sameAs, ResourceFactory.createResource("http://dbpedia.org/resource/Cool") ); Model namedModel = ModelFactory.createDefaultModel(); namedModel.add( ResourceFactory.createResource("http://rdfunit.aksw.org"), OWL.sameAs, ResourceFactory.createResource("http://dbpedia.org/resource/Super") ); dataset = DatasetFactory.create(defaultModel); dataset.addNamedModel("http://rdfunit.aksw.org", namedModel); }
Example #13
Source File: PrefixUtil.java From shacl with Apache License 2.0 | 5 votes |
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 #14
Source File: TriplePatternElementParserForJena.java From Server.Java with MIT License | 5 votes |
/** * * @param label * @param languageTag * @return */ @Override public RDFNode createLanguageLiteral( final String label, final String languageTag ) { return ResourceFactory.createLangLiteral( label, languageTag ); }
Example #15
Source File: SPARQLSubstitutions.java From shacl with Apache License 2.0 | 5 votes |
public static Literal withSubstitutions(Literal template, QuerySolution bindings, Function<RDFNode,String> labelFunction) { StringBuffer buffer = new StringBuffer(); String labelTemplate = template.getLexicalForm(); for(int i = 0; i < labelTemplate.length(); i++) { if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && (labelTemplate.charAt(i + 1) == '?' || labelTemplate.charAt(i + 1) == '$')) { int varEnd = i + 2; while(varEnd < labelTemplate.length()) { if(labelTemplate.charAt(varEnd) == '}') { String varName = labelTemplate.substring(i + 2, varEnd); RDFNode varValue = bindings.get(varName); if(varValue != null) { if(labelFunction != null) { buffer.append(labelFunction.apply(varValue)); } else if(varValue instanceof Resource) { buffer.append(RDFLabels.get().getLabel((Resource)varValue)); } else if(varValue instanceof Literal) { buffer.append(varValue.asNode().getLiteralLexicalForm()); } } break; } else { varEnd++; } } i = varEnd; } else { buffer.append(labelTemplate.charAt(i)); } } if(template.getLanguage().isEmpty()) { return ResourceFactory.createTypedLiteral(buffer.toString()); } else { return ResourceFactory.createLangLiteral(buffer.toString(), template.getLanguage()); } }
Example #16
Source File: Test.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
public void updateTest() { // Add a new book to the collection // String service = "http://219.248.137.7:13030/icbms/update"; // UpdateRequest ur = UpdateFactory // .create("" // + "delete { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . } " // + "insert { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> \"19\" . } " //<-- 19대신 여기 온도를 넣어주세 // + "WHERE { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }"); // UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service); // up.execute(); // Query the collection, dump output // String service1 = "http://219.248.137.7:13030/icbms/"; // QueryExecution qe = QueryExecutionFactory.sparqlService(service1, // "SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 "); // // ResultSet results = qe.execSelect(); // ResultSetFormatter.out(System.out, results); // qe.close(); Model model = ModelFactory.createDefaultModel(); Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6"))); model.add(s); String query = "select * {?s ?p ?o }"; QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet results = qe.execSelect(); ResultSetFormatter.out(System.out, results); qe.close(); }
Example #17
Source File: OneM2MContentInstanceMapper.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * typed content type 가져오기 * @param con * @return Literal */ public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); } } }
Example #18
Source File: NotFoundExceptionMapper.java From Processor with Apache License 2.0 | 5 votes |
@Override public Response toResponse(NotFoundException ex) { return getResponseBuilder(DatasetFactory.create(toResource(ex, Response.Status.NOT_FOUND, ResourceFactory.createResource("http://www.w3.org/2011/http-statusCodes#NotFound")). getModel())). status(Response.Status.NOT_FOUND). build(); }
Example #19
Source File: QueryParseExceptionMapper.java From Processor with Apache License 2.0 | 5 votes |
@Override public Response toResponse(QueryParseException ex) { return getResponseBuilder(DatasetFactory.create(toResource(ex, Response.Status.INTERNAL_SERVER_ERROR, ResourceFactory.createResource("http://www.w3.org/2011/http-statusCodes#InternalServerError")). getModel())). status(Response.Status.INTERNAL_SERVER_ERROR). build(); }
Example #20
Source File: RiotExceptionMapper.java From Processor with Apache License 2.0 | 5 votes |
@Override public Response toResponse(RiotException ex) { return getResponseBuilder(DatasetFactory.create(toResource(ex, Response.Status.BAD_REQUEST, ResourceFactory.createResource("http://www.w3.org/2011/http-statusCodes#BadRequest")). getModel())). status(Response.Status.BAD_REQUEST). build(); }
Example #21
Source File: HttpExceptionMapper.java From Processor with Apache License 2.0 | 5 votes |
@Override public Response toResponse(HttpException ex) { return getResponseBuilder(DatasetFactory.create(toResource(ex, Response.Status.INTERNAL_SERVER_ERROR, ResourceFactory.createResource("http://www.w3.org/2011/http-statusCodes#InternalServerError")). getModel())). status(Response.Status.INTERNAL_SERVER_ERROR). build(); }
Example #22
Source File: ReaderTestUtils.java From RDFUnit with Apache License 2.0 | 5 votes |
public static Model createOneTripleModel() { Model model = ModelFactory.createDefaultModel(); model.add( ResourceFactory.createResource("http://rdfunit.aksw.org"), OWL.sameAs, ResourceFactory.createResource("http://dbpedia.org/resource/Cool")); return model; }
Example #23
Source File: RdfModelHelper.java From tools with Apache License 2.0 | 5 votes |
/** * Search the model to see if there is a duplicate resource either based on the * URI or based on other information. Subclasses may choose to override this * method to prevent duplicate resource from being created with the same properties. * @param modelContainer * @param uri * @return Any duplicate resource found. Null if no duplicate resource was found. * @throws InvalidSPDXAnalysisException */ public static Resource findDuplicateResource( IModelContainer modelContainer, String uri) { if (uri == null || uri.isEmpty()) { return null; } Resource retval = ResourceFactory.createResource(uri); if (modelContainer.getModel().containsResource(retval)) { return modelContainer.getModel().getResource(uri); } else { return null; } }
Example #24
Source File: TestCaseGroupXone.java From RDFUnit with Apache License 2.0 | 5 votes |
public TestCaseGroupXone(@NonNull Set<? extends TargetBasedTestCase> testCases) { assert(! testCases.isEmpty()); target = testCases.iterator().next().getTarget(); assert(testCases.stream().map(TargetBasedTestCase::getTarget).noneMatch(x -> x != target)); this.resource = ResourceFactory.createProperty(JenaUtils.getUniqueIri()); this.testCases = ImmutableSet.copyOf(Stream.concat(testCases.stream(), Stream.of(new AlwaysFailingTestCase(this.target))).collect(Collectors.toSet())); // adding always failing test }
Example #25
Source File: ShapeTargetCoreTest.java From RDFUnit with Apache License 2.0 | 5 votes |
@Test public void testPatternUnique() { List<String> targetPatterns = Arrays.stream(ShapeTargetType.values() ) .filter( sct -> !sct.equals(ShapeTargetType.ValueShapeTarget)) .map( s -> ShapeTargetCore.create(s, ResourceFactory.createResource("http://example.com"))) .map(ShapeTarget::getPattern) .collect(Collectors.toList()); // each target results in different pattern assertThat(targetPatterns.size()) .isEqualTo(new HashSet<>(targetPatterns).size()); }
Example #26
Source File: ShapePathReaderTest.java From RDFUnit with Apache License 2.0 | 5 votes |
@Parameterized.Parameters(name= "{index}: Path: {1}") public static Collection<Object[]> resources() throws RdfReaderException { Model model = RdfReaderFactory.createResourceReader("/org/aksw/rdfunit/model/readers/shacl/ShapePathReaderTest.ttl").read(); Collection<Object[]> parameters = new ArrayList<>(); Property pathProperty = ResourceFactory.createProperty("http://ex.com/path"); Property pathExprProperty = ResourceFactory.createProperty("http://ex.com/pathExp"); for (Resource node: model.listSubjectsWithProperty(pathProperty).toList()) { Resource path = node.getPropertyResourceValue(pathProperty); String pathExpr = node.getProperty(pathExprProperty).getObject().asLiteral().getLexicalForm(); parameters.add(new Object[] {path, pathExpr}); } return parameters; }
Example #27
Source File: ComponentParameterImplTest.java From RDFUnit with Apache License 2.0 | 5 votes |
@Test public void testGetDefaultValue() { assertThat(argDef.getDefaultValue().isPresent()) .isFalse(); RDFNode node = ResourceFactory.createResource("http://example.com"); ComponentParameterImpl arg2 = ComponentParameterImpl.builder().element(element).predicate(predicate).defaultValue(node).build(); assertThat(arg2.getDefaultValue().get()) .isEqualTo(node); }
Example #28
Source File: InstancesQueryHandler.java From IGUANA with GNU Affero General Public License v3.0 | 5 votes |
@Override public Model generateTripleStats(String taskID, String resource, String property) { QueryStatistics qs = new QueryStatistics(); String rdfs = "http://www.w3.org/2000/01/rdf-schema#"; Model model = ModelFactory.createDefaultModel(); for (File queryFile : queryFiles) { try { String query = FileUtils.readLineAt(0, queryFile); Query q = QueryFactory.create(query); qs.getStatistics(q); QueryStatistics qs2 = new QueryStatistics(); qs2.getStatistics(q); String subject = resource + hashcode + "/" + queryFile.getName(); model.add(model.createResource(subject), ResourceFactory.createProperty(rdfs + "ID"), queryFile.getName().replace("sparql", "")); model.add(model.createResource(subject), RDFS.label, query); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "aggregations"), model.createTypedLiteral(qs2.aggr)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "filter"), model.createTypedLiteral(qs2.filter)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "groupBy"), model.createTypedLiteral(qs2.groupBy)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "having"), model.createTypedLiteral(qs2.having)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "triples"), model.createTypedLiteral(qs2.triples)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "offset"), model.createTypedLiteral(qs2.offset)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "optional"), model.createTypedLiteral(qs2.optional)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "orderBy"), model.createTypedLiteral(qs2.orderBy)); model.add(model.createResource(subject), ResourceFactory.createProperty(property + "union"), model.createTypedLiteral(qs2.union)); } catch (IOException e) { LOGGER.error("[QueryHandler: {{}}] Cannot read file {{}}", this.getClass().getName(), queryFile.getName()); } } return model; }
Example #29
Source File: IndexRequestProcessorForTPFs.java From Server.Java with MIT License | 5 votes |
/** * * @param s * @param p * @param o * @param offset * @param limit * @return */ @Override protected ILinkedDataFragment createFragment( final ITriplePatternElement<RDFNode,String,String> s, final ITriplePatternElement<RDFNode,String,String> p, final ITriplePatternElement<RDFNode,String,String> o, final long offset, final long limit ) { // FIXME: The following algorithm is incorrect for cases in which // the requested triple pattern contains a specific variable // multiple times; // e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn) // see https://github.com/LinkedDataFragments/Server.Java/issues/25 final Resource subject = s.isVariable() ? null : s.asConstantTerm().asResource(); final Property predicate = p.isVariable() ? null : ResourceFactory.createProperty(p.asConstantTerm().asResource().getURI()); final RDFNode object = o.isVariable() ? null : o.asConstantTerm(); StmtIterator listStatements = model.listStatements(subject, predicate, object); Model result = ModelFactory.createDefaultModel(); long index = 0; while (listStatements.hasNext() && index < offset) { listStatements.next(); index++; } while (listStatements.hasNext() && index < (offset + limit)) { result.add(listStatements.next()); } final boolean isLastPage = ( result.size() < offset + limit ); return createTriplePatternFragment( result, result.size(), isLastPage ); }
Example #30
Source File: TriplePatternElementParserForJena.java From Server.Java with MIT License | 5 votes |
/** * * @param label * @param typeURI * @return */ @Override public RDFNode createTypedLiteral( final String label, final String typeURI ) { final RDFDatatype dt = TypeMapper.getInstance() .getSafeTypeByName( typeURI ); return ResourceFactory.createTypedLiteral( label, dt ); }