org.apache.jena.rdf.model.ModelFactory Java Examples

The following examples show how to use org.apache.jena.rdf.model.ModelFactory. 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: ExecutionForest.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
public Model generateModel() {

        ExecutorService executor = Executors.newFixedThreadPool(10);
        Model model = ModelFactory.createDefaultModel();
        Set<Future<Model>> futureModels = new HashSet<>();
        getForest().forEach(node -> {
            FetchingExecution fetchingExecution = new FetchingExecution(new HashSet<>(), node);
            futureModels.add(executor.submit(fetchingExecution));
        });
        futureModels.forEach(futureModel -> {
            try {
                model.add(futureModel.get());
            } catch (InterruptedException | ExecutionException e) {
                LOGGER.error(e);
            }
        });
        return model;
    }
 
Example #2
Source File: SolidContactsImport.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String createIndex(String url, String slug, SolidUtilities utilities) throws Exception {
  Model model = ModelFactory.createDefaultModel();
  Resource containerResource = model.createResource("#this");
  containerResource.addProperty(RDF.type, model.getResource(VCARD4.NS + "AddressBook"));
  containerResource.addProperty(
      model.createProperty(VCARD4.NS + "nameEmailIndex"),
      model.createResource("people.ttl"));
  containerResource.addProperty(
      model.createProperty(VCARD4.NS + "groupIndex"),
      model.createResource("groups.ttl"));
  containerResource.addProperty(DC_11.title, slug);
  return utilities.postContent(
      url,
      "index",
      BASIC_RESOURCE_TYPE,
      model);
}
 
Example #3
Source File: SHACLUtil.java    From shacl with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a shapes Model for a given input Model.
 * The shapes Model is the union of the input Model with all graphs referenced via
 * the sh:shapesGraph property (and transitive includes or shapesGraphs of those).
 * @param model  the Model to create the shapes Model for
 * @return a shapes graph Model
 */
private static Model createShapesModel(Dataset dataset) {
	
	Model model = dataset.getDefaultModel();
	Set<Graph> graphs = new HashSet<Graph>();
	Graph baseGraph = model.getGraph();
	graphs.add(baseGraph);
	
	for(Statement s : model.listStatements(null, SH.shapesGraph, (RDFNode)null).toList()) {
		if(s.getObject().isURIResource()) {
			String graphURI = s.getResource().getURI();
			Model sm = dataset.getNamedModel(graphURI);
			graphs.add(sm.getGraph());
			// TODO: Include includes of sm
		}
	}
	
	if(graphs.size() > 1) {
		MultiUnion union = new MultiUnion(graphs.iterator());
		union.setBaseGraph(baseGraph);
		return ModelFactory.createModelForGraph(union);
	}
	else {
		return model;
	}
}
 
Example #4
Source File: Validator.java    From Processor with Apache License 2.0 6 votes vote down vote up
public OntModel fixOntModel(OntModel ontModel)
    {
        if (ontModel == null) throw new IllegalArgumentException("Model cannot be null");
        
        OntModel fixedModel = ModelFactory.createOntologyModel(ontModel.getSpecification());
        Query fix = QueryFactory.create("CONSTRUCT\n" +
"{\n" +
"  ?s ?p ?o\n" +
"}\n" +
"WHERE\n" +
"{\n" +
"  ?s ?p ?o\n" +
"  FILTER (!(?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?o = <https://www.w3.org/ns/ldt#Constraint>))\n" +
"}");
        
        try (QueryExecution qex = QueryExecutionFactory.create(fix, ontModel))
        {
            fixedModel.add(qex.execConstruct());
        }
        
        return fixedModel;
    }
 
Example #5
Source File: TargetContainsPFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public QueryIterator exec(Binding binding, PropFuncArg argSubject,
		Node predicate, PropFuncArg argObject, ExecutionContext execCxt) {

	argSubject = Substitute.substitute(argSubject, binding);
	argObject = Substitute.substitute(argObject, binding);
	
	if(!argObject.getArg().isVariable()) {
		throw new ExprEvalException("Right hand side of tosh:targetContains must be a variable");
	}
	
	Node targetNode = argSubject.getArgList().get(0);
	Node shapesGraphNode = argSubject.getArgList().get(1);
	
	Model currentModel = ModelFactory.createModelForGraph(execCxt.getActiveGraph());
	Dataset dataset = new DatasetWithDifferentDefaultModel(currentModel, DatasetImpl.wrap(execCxt.getDataset()));

	Model model = dataset.getNamedModel(shapesGraphNode.getURI());
	Resource target = (Resource) model.asRDFNode(targetNode);

	Set<Node> focusNodes = new HashSet<Node>();
	SHACLUtil.addNodesInTarget(target, dataset, focusNodes);
	return new QueryIterExtendByVar(binding, (Var) argObject.getArg(), focusNodes.iterator(), execCxt);
}
 
Example #6
Source File: QueryExecutionTest.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTTLStarString()
{
	final String ttlsString =
			"@prefix ex: <http://example.com/> ." +
			"<< ex:s ex:p ex:o >>  ex:m1  ex:x1 . " +
			"<< ex:s ex:p ex:o >>  ex:m2  ex:x2 . ";

	final String queryString = prefixes + "SELECT ?o WHERE { ?t ex:m1 ex:x1 . ?t ex:m2 ?o }";

	final Graph g = RDFStarUtils.createRedundancyAugmentedGraphFromTurtleStarSnippet(ttlsString);
	final Model m = ModelFactory.createModelForGraph(g);


	final Query query = QueryFactory.create( queryString, null, SPARQLStar.syntax );
       final ResultSet rs = QueryExecutionFactory.create(query, m).execSelect();

       consume( rs, "o", "http://example.com/x2" );
}
 
Example #7
Source File: TestRdfModelObject.java    From tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindSetElementsPropertyValue() throws InvalidSPDXAnalysisException {
	final Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	Resource r = model.createResource();
	EmptyRdfModelObject empty = new EmptyRdfModelObject(modelContainer, r.asNode());
	SpdxElement result = empty.findElementPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1);
	assertTrue(result == null);
	String elementName1 = "element name 1";
	String elementComment1 = "element comment 1";
	SpdxElement element1 = new SpdxElement(elementName1, elementComment1, null, null);
	empty.setPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1, element1);
	result = empty.findElementPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1);
	assertEquals(element1, result);
	String elementName2 = "element name 2";
	String elementComment2 = "element comment 2";
	SpdxElement element2 = new SpdxElement(elementName2, elementComment2, null, null);
	empty.setPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1, element2);
	result = empty.findElementPropertyValue(TEST_NAMESPACE, TEST_PROPNAME1);
	assertEquals(element2, result);
}
 
Example #8
Source File: TestCaseWriterTest.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrite() {
    Collection<GenericTestCase> testCaseCollection = BatchTestCaseReader.create().getTestCasesFromModel(inputModel);

    Model modelWritten = ModelFactory.createDefaultModel();
    for (GenericTestCase tc : testCaseCollection) {
        TestCaseWriter.create(tc).write(modelWritten);
    }

    // See the difference...
    //Model difference = inputModel.difference(modelWritten);
    //new RDFFileWriter("tmp" + label.replace("/", "_") + ".in.ttl", "TTL").write(inputModel);
    //new RDFFileWriter("tmp" + label.replace("/", "_") + ".out.ttl", "TTL").write(modelWritten);
    //new RDFFileWriter("tmp" + label.replace("/", "_") + ".diff.ttl", "TTL").write(difference);

    assertThat(inputModel.isIsomorphicWith(modelWritten)).isTrue();
}
 
Example #9
Source File: ARQTest.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testQuerySetValuesDataBlock() {
	List<Var> header = vars("a", "b");
	Binding b1 = binding(header, "1", "2");
	Binding b2 = binding(header, "3", "4");

	Query q = QueryFactory.create("SELECT * {}");
	q.setValuesDataBlock(header, bindings(b1, b2));
	ResultSet rs = QueryExecutionFactory.create(q, 
			ModelFactory.createDefaultModel()).execSelect();

	assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars());
	assertTrue(rs.hasNext());
	assertEquals(b1, rs.nextBinding());
	assertTrue(rs.hasNext());
	assertEquals(b2, rs.nextBinding());
	assertFalse(rs.hasNext());
}
 
Example #10
Source File: CustomAggregate.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    
    // Example aggregate that counts literals.
    // Returns unbound for no rows. 
    String aggUri = "http://example/countLiterals" ;
    
    
    /* Registration */
    AggregateRegistry.register(aggUri, myAccumulatorFactory, NodeConst.nodeMinusOne);
    
    
    // Some data.
    Graph g = SSE.parseGraph("(graph (:s :p :o) (:s :p 1))") ;
    String qs = "SELECT (<http://example/countLiterals>(?o) AS ?x) {?s ?p ?o}" ;
    
    // Execution as normal.
    Query q = QueryFactory.create(qs) ;
    try ( QueryExecution qexec = QueryExecutionFactory.create(q, ModelFactory.createModelForGraph(g)) ) {
        ResultSet rs = qexec.execSelect() ;
        ResultSetFormatter.out(rs);
    }
}
 
Example #11
Source File: String2Node.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
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 #12
Source File: Main.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) {
    OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, null );

    // we have a local copy of the wine ontology
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine",
                                        "file:testing/reasoners/bugs/wine.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine.owl",
                                        "file:testing/reasoners/bugs/wine.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/food",
                                        "file:testing/reasoners/bugs/food.owl" );
    m.getDocumentManager().addAltEntry( "http://www.w3.org/2001/sw/WebOnt/guide-src/food.owl",
                                        "file:testing/reasoners/bugs/food.owl" );

    m.read( "http://www.w3.org/2001/sw/WebOnt/guide-src/wine" );

    new ClassHierarchy().showHierarchy( System.out, m );
}
 
Example #13
Source File: ComponentParameterWriterTest.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void testRead() {
    // read the ComponentParameter
    ComponentParameter componentParameter = ComponentParameterReader.create().read(resource);

    // write in new model
    Model m1 = ModelFactory.createDefaultModel();
    Resource r1 = ComponentParameterWriter.create(componentParameter).write(m1);
    // reread
    ComponentParameter componentParameter2 = ComponentParameterReader.create().read(r1);
    Model m2 = ModelFactory.createDefaultModel();
    ComponentParameterWriter.create(componentParameter2).write(m2);

    assertThat(m1.isIsomorphicWith(m2))
        .isTrue();
}
 
Example #14
Source File: TestRoEvoSerializer.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@Test
public void workflowUUIDs() throws Exception {
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	roEvo.workflowHistory(helloWorld.getMainWorkflow(), os);
	System.out.write(os.toByteArray());
	assertTrue(500 < os.size());
	String ttl = os.toString("UTF-8");
	assertTrue(ttl.contains("01348671-5aaa-4cc2-84cc-477329b70b0d"));
	assertTrue(ttl.contains("VersionableResource"));
	assertTrue(ttl.contains("Entity"));
	
	OntModel m = ModelFactory.createOntologyModel();
	m.read(new ByteArrayInputStream(os.toByteArray()), "http://example.com/", "Turtle");
	Resource mainWf = m.getResource(helloWorld.getMainWorkflow().getIdentifier().toASCIIString());		
	Resource older = mainWf.getProperty(prov.wasRevisionOf).getResource();
	Resource oldest = older.getProperty(prov.wasRevisionOf).getResource();
	assertNull(oldest.getProperty(prov.wasRevisionOf));
	
}
 
Example #15
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 #16
Source File: TestSPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataLicense() throws InvalidSPDXAnalysisException, InvalidLicenseStringException {
	Model model = ModelFactory.createDefaultModel();
	SPDXDocument doc = new SPDXDocument(model);
	String testDocUri = "https://olex.openlogic.com/spdxdoc/package_versions/download/4832?path=openlogic/zlib/1.2.3/zlib-1.2.3-all-src.zip&amp;package_version_id=1082";
	doc.createSpdxAnalysis(testDocUri);
	// check default
	SpdxListedLicense dataLicense = doc.getDataLicense();
	assertEquals(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID, dataLicense.getLicenseId());
	// check set correct license
	AnyLicenseInfo cc0License = LicenseInfoFactory.parseSPDXLicenseString(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID);
	doc.setDataLicense((SpdxListedLicense)cc0License);
	dataLicense = doc.getDataLicense();
	assertEquals(org.spdx.rdfparser.SpdxRdfConstants.SPDX_DATA_LICENSE_ID, dataLicense.getLicenseId());
	// check error when setting wrong license
	AnyLicenseInfo ngplLicense = LicenseInfoFactory.parseSPDXLicenseString("NGPL");
	try {
		doc.setDataLicense((SpdxListedLicense)ngplLicense);
		fail("Incorrect license allowed to be set for data license");
	} catch(InvalidSPDXAnalysisException e) {
		// expected - do nothing
	}
}
 
Example #17
Source File: TestSPDXDocument.java    From tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNextSpdxRef() throws InvalidSPDXAnalysisException {
	String docUri = "http://www.spdx.org/spdxdocs/uniquenameofsomesort";
	Model model = ModelFactory.createDefaultModel();
	SPDXDocument doc = new SPDXDocument(model);
	doc.createSpdxAnalysis(docUri);
	String nextSpdxElementRef = doc.getNextSpdxElementRef();
	String expected = SpdxRdfConstants.SPDX_ELEMENT_REF_PRENUM + String.valueOf(1);
	assertEquals(expected, nextSpdxElementRef);
	nextSpdxElementRef = doc.getNextSpdxElementRef();
	expected = SpdxRdfConstants.SPDX_ELEMENT_REF_PRENUM + String.valueOf(2);
	assertEquals(expected, nextSpdxElementRef);
	// test that it survives across a new doc
	doc.createSpdxPackage(doc.getDocumentNamespace() + nextSpdxElementRef);
	SPDXDocument doc2 = new SPDXDocument(model);
	nextSpdxElementRef = doc2.getNextSpdxElementRef();
	expected = SpdxRdfConstants.SPDX_ELEMENT_REF_PRENUM + String.valueOf(3);
	assertEquals(expected, nextSpdxElementRef);
	nextSpdxElementRef = doc.getNextSpdxElementRef();
	expected = SpdxRdfConstants.SPDX_ELEMENT_REF_PRENUM + String.valueOf(3);
	assertEquals(expected, nextSpdxElementRef);	// original SPDX doc should maintain its own
}
 
Example #18
Source File: NTriplesModelFactory.java    From Stargraph with MIT License 6 votes vote down vote up
@Override
protected Model createModel(String dbId) {
    File ntriplesFile = getNTriplesPath(dbId).toFile();
    if (!ntriplesFile.exists()) {
        logger.warn(marker, "Can't find NT file {}", ntriplesFile);
    } else {

        try (InputStream is = new FileInputStream(ntriplesFile)) {
            Model model = ModelFactory.createDefaultModel();
            model.read(is, null, "N-TRIPLES");
            return model;
        } catch (Exception e) {
            throw new StarGraphException(e);
        }
    }

    return null;
}
 
Example #19
Source File: OneM2MContentInstanceMapper.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		File f = new File("/Users/rosenc/Documents/business/[2015]icbms/json_sample1.txt");
		BufferedReader br = new BufferedReader(new FileReader(f));
		String line = null;
		String s = "";
		while ((line = br.readLine()) != null) {
			s = s + line + "\n";
		}

		System.out.println(s);
		Gson gson = new Gson();
		OneM2MContentInstanceDTO cont = gson.fromJson(s, OneM2MContentInstanceDTO.class);
		OneM2MContentInstanceMapper mapper = new OneM2MContentInstanceMapper(cont);

		Model model = ModelFactory.createDefaultModel();
		model.add(mapper.from());
		System.out.println("content type ; " + mapper.getContentType());
		// 스트링 변환부분
		RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);
		// System.out.println(mapper.getTypedContent("2k42kk"));
		// mapper.getTypedContent("2.4");

	}
 
Example #20
Source File: TestExternalDocumentRef.java    From tools with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.spdx.rdfparser.model.ExternalDocumentRef#setSpdxDocument(org.spdx.rdfparser.model.SpdxDocument)}.
 * @throws InvalidSPDXAnalysisException
 */
@Test
public void testSetSpdxDocument() throws InvalidSPDXAnalysisException {
	SpdxDocumentContainer container1 = new SpdxDocumentContainer(DOCUMENT_URI1);
	SpdxDocument doc1 = container1.getSpdxDocument();
	doc1.setName("DocumentName");
	ExternalDocumentRef edf = new ExternalDocumentRef(DOCUMENT_URI2, CHECKSUM1,
			DOCUMENT_ID1);
	Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	Resource r = edf.createResource(modelContainer);
	edf.setSpdxDocument(doc1);
	assertEquals(DOCUMENT_URI1, edf.getSpdxDocumentNamespace());
	assertEquals(doc1.getName(), edf.getSpdxDocument().getName());
	ExternalDocumentRef edf2 = new ExternalDocumentRef(modelContainer, r.asNode());
	assertEquals(DOCUMENT_URI1, edf2.getSpdxDocumentNamespace());
	SpdxDocumentContainer container2 = new SpdxDocumentContainer(DOCUMENT_URI2);
	SpdxDocument doc2 = container2.getSpdxDocument();
	doc2.setName("name2");
	edf2.setSpdxDocument(doc2);
	assertEquals(DOCUMENT_URI2, edf2.getSpdxDocumentNamespace());
	assertEquals(doc2.getName(), edf2.getSpdxDocument().getName());
	assertEquals(DOCUMENT_URI2, edf.getSpdxDocumentNamespace());
}
 
Example #21
Source File: SimpleSubClassInferencerTest.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Model createModel() {
    Model classModel = ModelFactory.createDefaultModel();
    Resource A = classModel.createResource("http://example.org/A");
    Resource B = classModel.createResource("http://example.org/B");
    Resource C = classModel.createResource("http://example.org/C");
    Resource C2 = classModel.createResource("http://example2.org/C");
    Resource C3 = classModel.createResource("http://example3.org/C");
    Resource D2 = classModel.createResource("http://example2.org/D");
    Resource D3 = classModel.createResource("http://example3.org/D");
    classModel.add(A, RDF.type, RDFS.Class);
    classModel.add(B, RDF.type, RDFS.Class);
    classModel.add(C, RDF.type, RDFS.Class);
    classModel.add(C2, RDF.type, RDFS.Class);
    classModel.add(C3, RDF.type, RDFS.Class);
    classModel.add(D2, RDF.type, RDFS.Class);
    classModel.add(D3, RDF.type, RDFS.Class);
    classModel.add(B, RDFS.subClassOf, A);
    classModel.add(C, RDFS.subClassOf, B);
    classModel.add(C, OWL.sameAs, C2);
    classModel.add(C3, OWL.equivalentClass, C);
    classModel.add(D2, RDFS.subClassOf, C2);
    classModel.add(D3, RDFS.subClassOf, C3);
    return classModel;
}
 
Example #22
Source File: TestLineCharPointer.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
@Before
public void setUp() throws Exception {
	this.model = ModelFactory.createDefaultModel();
	modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	REFERENCED1 = new SpdxElement(REFERENCED_ELEMENT_NAME1, "", null, null);
	REFERENCED_RESOURCE1 = REFERENCED1.createResource(modelContainer);
	REFERENCED2 = new SpdxElement(REFERENCED_ELEMENT_NAME2, "", null, null);
	REFERENCED_RESOURCE2 = REFERENCED2.createResource(modelContainer);
}
 
Example #23
Source File: OntologyProvider.java    From Processor with Apache License 2.0 5 votes vote down vote up
public OntologyProvider(final OntDocumentManager ontDocumentManager, final String ontologyURI,
        final OntModelSpec materializationSpec, final boolean materialize)
{
    super(Ontology.class);
    
    if (ontDocumentManager == null) throw new IllegalArgumentException("OntDocumentManager cannot be null");
    if (ontologyURI == null) throw new IllegalArgumentException("URI cannot be null");
    if (materializationSpec == null) throw new IllegalArgumentException("OntModelSpec cannot be null");
    
    this.ontDocumentManager = ontDocumentManager;
    this.ontologyURI = ontologyURI;
    
    // materialize OntModel inferences to avoid invoking rules engine on every request
    if (materialize && materializationSpec.getReasoner() != null)
    {
        OntModel ontModel = getOntModel(ontDocumentManager, ontologyURI, materializationSpec);
        Ontology ontology = ontModel.getOntology(ontologyURI);

        ImportCycleChecker checker = new ImportCycleChecker();
        checker.check(ontology);
        if (checker.getCycleOntology() != null)
        {
            if (log.isErrorEnabled()) log.error("Sitemap contains an ontology which forms an import cycle: {}", checker.getCycleOntology());
            throw new OntologyException("Sitemap contains an ontology which forms an import cycle: " + checker.getCycleOntology().getURI());
        }
        
        OntModel materializedModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        materializedModel.add(ontModel);
        ontDocumentManager.addModel(ontologyURI, materializedModel, true);
    }
}
 
Example #24
Source File: OneM2MAEDTO.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
	String sample = " {     \"_id\" : ObjectId(\"561e1e1e1ee82041fac258b6\"),     \"rn\" : \"SAE_0\",     \"ty\" : 2,     \"ri\" : \"SAE_0\",     \"pi\" : \"herit-in\",     \"lbl\" : [          \"home1\",          \"home_service\"     ],     \"et\" : \"20151203T122321\",     \"at\" : [          \"//onem2m.hubiss.com/cse1\",          \"//onem2m.hubiss.com/cse2\"     ],     \"aa\" : [          \"poa\",          \"apn\"     ],     \"apn\" : \"onem2mPlatformAdmin\",     \"api\" : \"NHeritAdmin\",     \"aei\" : \"/SAE_0\",     \"poa\" : [          \"10.101.101.111:8080\"     ],     \"rr\" : false,     \"_uri\" : \"/herit-in/herit-cse/SAE_0\",     \"ct\" : \"20151014T181926\",     \"lt\" : \"20151014T181926\" }";
	Gson gson = new Gson();
	OneM2MAEDTO cont = gson.fromJson(sample, OneM2MAEDTO.class);


	System.out.println(cont);
	
	OneM2MAEMapper mapper = new OneM2MAEMapper(cont);
	Model model = ModelFactory.createDefaultModel();
	model.add(mapper.from());
	
	//스트링 변환부분
	RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);
}
 
Example #25
Source File: OneM2MContainerDTO.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
		String sample = "{     \"_id\" : ObjectId(\"561f27831ee8202c5e307d37\"),     \"rn\" : \"CONTAINER_268\",     \"ty\" : 3,     \"ri\" : \"CONTAINER_268\",     \"pi\" : \"SAE_0\",     \"lbl\" : [          \"switch\",          \"key1\",          \"key2\"     ],     \"et\" : \"20151203T122321\",     \"cr\" : \"//onem2m.herit.net/herit-cse/SAE_5\",     \"mni\" : 100,     \"mbs\" : 1.024e+006,     \"mia\" : 36000,     \"cni\" : 1,     \"cbs\" : 2,     \"_uri\" : \"/herit-in/herit-cse/SAE_0/CONTAINER_268\",     \"ct\" : \"20151015T131147\",     \"lt\" : \"20151015T131147\", \"or\":\"http://www.pineone.com/m2m/SwitchStatusSensor\" }";
		Gson gson = new Gson();
		OneM2MContainerDTO cont = gson.fromJson(sample, OneM2MContainerDTO.class);


		System.out.println(cont);
		
		OneM2MContainerMapper mapper = new OneM2MContainerMapper(cont);
		Model model = ModelFactory.createDefaultModel();
		model.add(mapper.from());
		
		//스트링 변환부분
		RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);

		//스트링 변환부분
//		String serviceURI = "http://219.248.137.7:13030/icbms";
//
//		DatasetAccessor	accessor = DatasetAccessorFactory.createHTTP(serviceURI);
//		accessor.deleteDefault();
//		accessor.add(model);
//		
//		
//		QueryExecution q = QueryExecutionFactory.sparqlService(serviceURI	,"select * {?s ?p ?o}"	);
//		ResultSet rs = q.execSelect();
//		ResultSetFormatter.out(rs);;
		
//		model = DatasetAccessorFactory.createHTTP(serviceURI).getModel();
//		System.out.println(model.size());

	}
 
Example #26
Source File: RDFWriterCanonicalTestCase.java    From ontopia with Apache License 2.0 5 votes vote down vote up
@Test
public void testFile() throws IOException {
  TestFileUtils.verifyDirectory(base, "out");
  TestFileUtils.verifyDirectory(base, "tmp");

  // export
  String in = TestFileUtils.getTestInputFile(testdataDirectory, "in", filename);
  String tmp = base + File.separator + "tmp" + File.separator + filename;
  String bline = TestFileUtils.getTestInputFile(testdataDirectory, "baseline",
      filename);
  TopicMapReaderIF reader = ImportExportUtils.getReader(in);
  if (reader instanceof XTMTopicMapReader)
    ((XTMTopicMapReader) reader).setValidation(false);
  TopicMapIF tm = reader.read();
  FileOutputStream fos = new FileOutputStream(tmp);
  new RDFTopicMapWriter(fos).write(tm);
  fos.close();

  // read in base line and export
  Model baseline = ModelFactory.createDefaultModel().read(StreamUtils.getInputStream(bline),
      bline, "RDF/XML");
  Model result = ModelFactory.createDefaultModel().read(new FileInputStream(tmp), "file:"
      + tmp, "RDF/XML");

  // compare results
  Assert.assertTrue("test file " + filename + " produced non-isomorphic model: " + 
				 bline + " " + tmp,
      result.isIsomorphicWith(baseline));
}
 
Example #27
Source File: TestAnnotation.java    From tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testClone() throws InvalidSPDXAnalysisException {
	Annotation a1 = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1);
	final Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	a1.createResource(modelContainer);
	Annotation a2 = a1.clone();
	assertEquals(a1.getAnnotationType(), a2.getAnnotationType());
	assertEquals(a1.getAnnotator(), a2.getAnnotator());
	assertEquals(a1.getComment(), a2.getComment());
	assertEquals(a1.getAnnotationDate(), a2.getAnnotationDate());
	assertTrue(a2.model == null);
}
 
Example #28
Source File: TestRdfModelObject.java    From tools with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link org.spdx.rdfparser.model.RdfModelObject#createResource(org.apache.jena.rdf.model.Model, java.lang.String)}.
 * @throws InvalidSPDXAnalysisException 
 */
@Test
public void testCreateResource() throws InvalidSPDXAnalysisException {
	final Model model = ModelFactory.createDefaultModel();
	IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com");
	EmptyRdfModelObject empty = new EmptyRdfModelObject();
	// Anon.
	String URI = "http://a/uri#r";
	empty.setUri(URI);
	Resource r = empty.createResource(modelContainer);
	assertTrue(r.isURIResource());
	Node p = model.getProperty(TEST_NAMESPACE, TEST_PROPNAME1).asNode();
	Triple m = Triple.createMatch(r.asNode(), p, null);
	ExtendedIterator<Triple> tripleIter = model.getGraph().find(m);	
	assertTrue(tripleIter.hasNext());
	Triple t = tripleIter.next();
	assertEquals(TEST_PROPVALUE1,t.getObject().toString(false));
	assertFalse(tripleIter.hasNext());
	// Anon
	empty.setUri(null);
	Resource anon = empty.createResource(modelContainer);
	assertFalse(anon.isURIResource());
	p = model.getProperty(TEST_NAMESPACE, TEST_PROPNAME1).asNode();
	m = Triple.createMatch(anon.asNode(), p, null);
	tripleIter = model.getGraph().find(m);	
	assertTrue(tripleIter.hasNext());
	t = tripleIter.next();
	assertEquals(TEST_PROPVALUE1,t.getObject().toString(false));
	assertFalse(tripleIter.hasNext());
}
 
Example #29
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void write(IndentedWriter out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) {
	Model model = ModelFactory.createModelForGraph(graph);
	if(baseURI != null) {
		out.println("BASE <" + baseURI + ">");
		out.println();
	}
	writeImports(out, model.getResource(baseURI));
	writePrefixes(out, prefixMap);
	writeShapes(out, model);
	out.flush();
}
 
Example #30
Source File: AbstractTool.java    From shacl with Apache License 2.0 5 votes vote down vote up
protected Model getShapesModel(String[] args) throws IOException {
	for(int i = 0; i < args.length - 1; i++) {
		if(SHAPES_FILE.equals(args[i])) {
			String fileName = args[i + 1];
			OntModel model = ModelFactory.createOntologyModel(spec);
			File file = new File(fileName);
			String lang = file.getName().endsWith(".shaclc") ? SHACLC.langName : FileUtils.langTurtle;
			model.read(new FileInputStream(file), "urn:x:base", lang);
			return model;
		}
	}
	return null;
}