Java Code Examples for com.hp.hpl.jena.rdf.model.ModelFactory

The following are top voted examples for showing how to use com.hp.hpl.jena.rdf.model.ModelFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DoSeR   File: DbpediaGraphModification.java   Source Code and License 7 votes vote down vote up
public Set<String> initializeCategories() {
	Model model = ModelFactory.createDefaultModel();
	model.read("/home/zwicklbauer/HDTGeneration/skos_categories_en.nt");
	StmtIterator it = model.listStatements();
	Set<String> set = new HashSet<String>();
	
	System.out.println("Los gehts");
	while (it.hasNext()) {
		Statement s = it.next();
		Resource r = s.getSubject();
		Property p = s.getPredicate();
		RDFNode n = s.getObject();
		if (p.getURI().equalsIgnoreCase(
				"http://www.w3.org/2004/02/skos/core#broader")
				&& n.isResource()) {
			Resource target = n.asResource();
			if(!hasSubCategory(target.getURI())) 
			set.add(target.getURI());
			if(!hasSubCategory(r.getURI())) 
			set.add(r.getURI());
		}
	}
	return set;
}
 
Example 2
Project: IKB4Stream   File: RDFParser.java   Source Code and License 6 votes vote down vote up
/**
 * Parse RDF input as string
 *
 * @param input RDF values as String
 * @return an {@link Request} object which contains information about latitude, longitude and date
 * @throws IllegalStateException if RDF is not literal
 * @throws NullPointerException  if input is null
 */
public static Request parse(String input) {
    Objects.requireNonNull(input);
    Model model = ModelFactory.createDefaultModel();
    model.read(new ByteArrayInputStream(input.getBytes()), null, "TURTLE");

    Map<String, Object> map = new HashMap<>();
    model.listStatements().forEachRemaining(statement -> {
        RDFNode rdfNode = statement.getObject();
        if (rdfNode.isLiteral()) {
            try {
                map.put(statement.getPredicate().getLocalName(), statement.getObject().asLiteral().getValue());
            } catch (Exception e) {
                LOGGER.error("RDF statement is not literal");
                throw new IllegalStateException(e.getMessage());
            }
        }
    });

    model.close();
    return getDataFromMap(map);
}
 
Example 3
Project: r2rml-kit   File: R2RMLTest.java   Source Code and License 6 votes vote down vote up
@Test
public void run() {
	SystemLoader loader = new SystemLoader();
	loader.setJdbcURL(db.getJdbcURL());
	loader.setUsername(db.getUser());
	loader.setMappingFile(mappingFile);
	loader.setStartupSQLScript(sqlFile);
	loader.setSystemBaseURI(BASE_URI);
	if (resultFile == null) {
		R2RMLReader reader = loader.getR2RMLReader();
		MappingValidator validator = new MappingValidator(
				reader.getMapping(), loader.getSQLConnection());
		validator.setReport(reader.getReport());
		validator.run();
		if (!reader.getReport().hasError()) {
			fail("Expected validation error");
		}
		return;
	}
	Model actualTriples = ModelFactory.createDefaultModel();
	actualTriples.add(loader.getModelD2RQ());
	Model expectedTriples = FileManager.get().loadModel(resultFile, "N-TRIPLES");
	ModelAssert.assertIsomorphic(expectedTriples, actualTriples);
}
 
Example 4
Project: r2rml-kit   File: ConstantValueClassMapTest.java   Source Code and License 6 votes vote down vote up
public void setUp() {
	this.model = ModelFactory.createDefaultModel();
	this.mapping = new Mapping();
	this.database = new Database(this.model.createResource());
	this.mapping.addDatabase(this.database);
	
	concept = createClassMap("http://example.com/concept#@@[email protected]@");
	conceptTypeBridge = createPropertyBridge(concept, RDF.type.getURI());
	conceptTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Concept"));
	
	collection = createConstantClassMap("http://example.com/collection#MyConceptCollection");
	collectionTypeBridge = createPropertyBridge(collection, RDF.type.getURI());
	collectionTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Collection"));

	memberBridge = createPropertyBridge(collection, "http://www.w3.org/2004/02/skos/core#member");
	memberBridge.setRefersToClassMap(concept);
	memberBridge.addCondition("c.foo = 1");
}
 
Example 5
Project: r2rml-kit   File: ProcessorTestBase.java   Source Code and License 6 votes vote down vote up
public static Collection<Object[]> getTestListFromManifest(String manifestFileURL) {
		// We'd like to use FileManager.loadModel() but it doesn't work on jar: URLs
//		Model m = FileManager.get().loadModel(manifestFileURL);
		Model m = ModelFactory.createDefaultModel();
		m.read(manifestFileURL, "TURTLE");

		IRI baseIRI = D2RQTestUtil.createIRI(m.getNsPrefixURI("base"));
		ResultSet rs = QueryExecutionFactory.create(TEST_CASE_LIST, m).execSelect();
		List<Object[]> result = new ArrayList<Object[]>();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource mapping = qs.getResource("mapping");
			Resource schema = qs.getResource("schema");
//			if (!mapping.getLocalName().equals("constant-object.ttl")) continue;
			QueryExecution qe = QueryExecutionFactory.create(TEST_CASE_TRIPLES, m);
			qe.setInitialBinding(qs);
			Model expectedTriples = qe.execConstruct();
			result.add(new Object[]{baseIRI.relativize(mapping.getURI()).toString(), mapping.getURI(), 
					schema.getURI(), expectedTriples});
		}
		return result;
	}
 
Example 6
Project: c4a_data_repository   File: AutoReloadableDataset.java   Source Code and License 6 votes vote down vote up
private void reload() {
	loader.getMapping().connect();
	GraphD2RQ graph = loader.getGraphD2RQ();
	
	datasetGraph = DatasetGraphFactory.createOneGraph(graph);
	defaultModel = ModelFactory.createModelForGraph(datasetGraph.getDefaultGraph());		

	hasTruncatedResults = false;
	for (Database db: loader.getMapping().databases()) {
		if (db.getResultSizeLimit() != Database.NO_LIMIT) {
			hasTruncatedResults = true;
		}
	}

	if (autoReload) {
		lastModified = watchedFile.lastModified();
		lastReload = System.currentTimeMillis();
	}
}
 
Example 7
Project: c4a_data_repository   File: CompileTest.java   Source Code and License 6 votes vote down vote up
public void setUp() {
	this.model = ModelFactory.createDefaultModel();
	this.mapping = new Mapping();
	this.database = new Database(this.model.createResource());
	database.useConnectedDB(new DummyDB());
	this.mapping.addDatabase(this.database);

	employees = createClassMap("http://test/[email protected]@[email protected]@");
	employees.addAlias("employees AS e");
	employees.addJoin("e.ID = foo.bar");
	employees.addCondition("e.status = 'active'");
	managerBridge = createPropertyBridge(employees, "http://terms.example.org/manager");
	managerBridge.addAlias("e AS m");
	managerBridge.setRefersToClassMap(this.employees);
	managerBridge.addJoin("e.manager = m.ID");
	
	cities = createClassMap("http://test/[email protected]@[email protected]@");
	citiesTypeBridge = createPropertyBridge(cities, RDF.type.getURI());
	citiesTypeBridge.setConstantValue(model.createResource("http://terms.example.org/City"));
	citiesNameBridge = createPropertyBridge(cities, "http://terms.example.org/name");
	citiesNameBridge.setColumn("c.name");
	countries = createClassMap("http://test/countries/@@[email protected]@");
	countries.setContainsDuplicates(true);
	countriesTypeBridge = createPropertyBridge(countries, RDF.type.getURI());
	countriesTypeBridge.setConstantValue(model.createResource("http://terms.example.org/Country"));
}
 
Example 8
Project: c4a_data_repository   File: ConstantValueClassMapTest.java   Source Code and License 6 votes vote down vote up
public void setUp() {
	this.model = ModelFactory.createDefaultModel();
	this.mapping = new Mapping();
	this.database = new Database(this.model.createResource());
	this.mapping.addDatabase(this.database);
	
	concept = createClassMap("http://example.com/concept#@@[email protected]@");
	conceptTypeBridge = createPropertyBridge(concept, RDF.type.getURI());
	conceptTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Concept"));
	
	collection = createConstantClassMap("http://example.com/collection#MyConceptCollection");
	collectionTypeBridge = createPropertyBridge(collection, RDF.type.getURI());
	collectionTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Collection"));

	memberBridge = createPropertyBridge(collection, "http://www.w3.org/2004/02/skos/core#member");
	memberBridge.setRefersToClassMap(concept);
	memberBridge.addCondition("c.foo = 1");
}
 
Example 9
Project: phenopacket-reference-implementation   File: RdfGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Convert a PhenoPacket to RDF triples using the JSON-LD context
 * 
 * @param packet
 * @param base
 *            URI base for generated RDF; if `null` a UUID-based base will
 *            be used
 * @return model containing RDF triples
 * @throws JsonLdError
 * @throws JsonProcessingException
 */
public static Model toRdf(PhenoPacket packet, String base)
		throws JsonLdError, JsonProcessingException {
	PhenoPacket packetWithContext;
	if (packet.getContext() == null) {
		packetWithContext = PhenoPacket.newBuilder(packet)
                           .context(ContextUtil.defaultContextURI)
                           .build();
	} else {
		packetWithContext = packet;
	}
	Model rdfModel = ModelFactory.createDefaultModel();
	StringReader reader = new StringReader(
			JsonGenerator.render(packetWithContext));
	String baseToUse;
	if (base != null) {
		baseToUse = base;
	} else {
		String uuid = UUID.randomUUID().toString();
		baseToUse = "http://phenopackets.org/local/" + uuid + "/";
	}
	RDFDataMgr.read(rdfModel, reader, baseToUse, Lang.JSONLD);
	return rdfModel;
}
 
Example 10
Project: BimSPARQL   File: BimSPARQL.java   Source Code and License 6 votes vote down vote up
private static Model loadDefaultRules(){
	Model rules=ModelFactory.createDefaultModel();
	rules.add(SPIN.getModel());
	rules.add(SP.getModel());
	InputStream in=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/schm.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in, null,"TTL");
	InputStream in2=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/pset.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in2, null,"TTL");
	InputStream in3=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/pdt.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in3, null,"TTL");
	InputStream in4=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/qto.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in4, null,"TTL");
	InputStream in5=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/geom.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in5, null,"TTL");
	InputStream in6=BimSPARQL.class.getClassLoader().getResourceAsStream("bimsparql/spt.ttl"); //new FileInputStream("IFC2X3_Schema.rdf");
	rules.read(in6, null,"TTL");
	return rules;
}
 
Example 11
Project: BimSPARQL   File: QueryFunctionTest.java   Source Code and License 6 votes vote down vote up
public static OntModel loadDefaultModel(){
	InputStream in = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("Duplex_A_20110505.ttl");
	Model model=ModelFactory.createDefaultModel();
	model.read(in,null,"TTL");
	InputStream ins = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("IFC2X3_TC1.ttl");
	InputStream input = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("Duplex_A_20110505_geometry.ttl");
	Model geometryModel=ModelFactory.createDefaultModel();
	geometryModel.read(input,null,"TTL");
	Model schema=ModelFactory.createDefaultModel();
	schema.read(ins,null,"TTL");	
		try {
			BimSPARQL.init(model,geometryModel);
		} catch (ClassNotFoundException | IOException | ParserConfigurationException | SAXException
				| URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	OntModel ontology=ModelFactory.createOntologyModel();
	ontology.add(schema);
	ontology.add(model);
	ontology.add(geometryModel);
	return ontology;
}
 
Example 12
Project: BimSPARQL   File: FireSeparationDistance.java   Source Code and License 6 votes vote down vote up
public static Model loadIbcData(){
	Model table=loadModel("Table_705.8.ttl","TTL");
	Model tableFunction=loadModel("Table_705.8_Function.ttl","TTL");
	Model qudtExpr=loadModel("QudtExpr.ttl","TTL");
	Model qudtSpin=loadModel("http://www.qudt.org/qudt/owl/1.0.0/qudt-spin.owl",null);
	Model unit=loadModel("http://www.qudt.org/qudt/owl/1.0.0/unit.owl",null);
	Model union=ModelFactory.createDefaultModel();
	Model spModel = SP.getModel();
	Model spinModel = SPIN.getModel();
	union.add(table);
	union.add(tableFunction);
	union.add(qudtExpr);
	union.add(qudtSpin);
	union.add(unit);
	union.add(spModel);
	union.add(spinModel);
	return union;
}
 
Example 13
Project: OpenCollegeGraph   File: ConstantValueClassMapTest.java   Source Code and License 6 votes vote down vote up
public void setUp() {
	this.model = ModelFactory.createDefaultModel();
	this.mapping = new Mapping();
	this.database = new Database(this.model.createResource());
	this.mapping.addDatabase(this.database);
	
	concept = createClassMap("http://example.com/concept#@@[email protected]@");
	conceptTypeBridge = createPropertyBridge(concept, RDF.type.getURI());
	conceptTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Concept"));
	
	collection = createConstantClassMap("http://example.com/collection#MyConceptCollection");
	collectionTypeBridge = createPropertyBridge(collection, RDF.type.getURI());
	collectionTypeBridge.setConstantValue(model.createResource("http://www.w3.org/2004/02/skos/core#Collection"));

	memberBridge = createPropertyBridge(collection, "http://www.w3.org/2004/02/skos/core#member");
	memberBridge.setRefersToClassMap(concept);
	memberBridge.addCondition("c.foo = 1");
}
 
Example 14
Project: europeana   File: FormatHandlerServlet.java   Source Code and License 6 votes vote down vote up
/***************************************************************************
 * Private Methods - Handle Translation
 **************************************************************************/

private Model sendRequest(HttpServletRequest req, String url)
    throws ResponseThrowable
{
    HttpClient client = new HttpClient();
    GetMethod  method = new GetMethod(url);
    method.setRequestHeader("Accept-Encoding", "gzip");
    method.setRequestHeader("Accept"         , _format.getMimetype());
    InputStream is = null;
    try {
        int rspCode = client.executeMethod(method);
        if ( rspCode != 200 ) { throw new ResponseThrowable(rspCode); }

        is = getInputStream(method);
        Model m = ModelFactory.createDefaultModel();
        m.read(is, null, _format.getJenaFormat().getLang().getLabel());
        return m;
    }
    catch (RiotException | IOException e) {
        throw new ResponseThrowable(e, 502);
    }
    finally { IOUtils.closeQuietly(is); method.releaseConnection(); }
}
 
Example 15
Project: u-qasar.platform   File: UQasarUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the user entities to rdf
 */
private static OntModel writeUserEntries() {
	OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
	try {
		thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
		InitialContext ic = new InitialContext();
		UserService userService = (UserService) ic.lookup("java:module/UserService");
		List<User> users = userService.getAll();
		for (User u : users) {
			writer.save(u);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return model;
}
 
Example 16
Project: europeana   File: DatasetProcessor.java   Source Code and License 6 votes vote down vote up
public void process(File src, File all, File dst, File enrich) throws IOException
{
    Model m = ModelFactory.createDefaultModel();
    loadFiles(src, ".xml", m);

    storeAsEDM(m, all);

    _type      = m.getProperty(RDF_TYPE);
    _prefLabel = m.getProperty(SKOS_PREF_LABEL);
    _foafName  = m.getProperty(FOAF_NAME);
    Resource pcho = m.getResource(EDM_PROVIDEDCHO);

    CSVWriter printer = new CSVWriter(enrich, CSVFormat.EXCEL);
    printer.start();
    try {
        enrichImpl(m.listSubjectsWithProperty(_type, pcho), printer);
    }
    finally {
        printer.end();
    }

    storeAsEDM(m, dst);

    new CHOAnalysis().analyse(dst);
}
 
Example 17
Project: europeana   File: MergeRDFDatasets.java   Source Code and License 6 votes vote down vote up
public void merge(File src, File dst) throws IOException
{
	Model m = ModelFactory.createDefaultModel();
	m.setNsPrefix("cc", "http://creativecommons.org/ns#");
	m.setNsPrefix("dc", "http://purl.org/dc/elements/1.1/");
	m.setNsPrefix("dcterms", "http://purl.org/dc/terms/");
	m.setNsPrefix("edm", "http://www.europeana.eu/schemas/edm/");
	m.setNsPrefix("foaf", "http://xmlns.com/foaf/0.1/");
	m.setNsPrefix("odrl", "http://www.w3.org/ns/odrl/2/");
	m.setNsPrefix("ore", "http://www.openarchives.org/ore/terms/");
	m.setNsPrefix("owl", "http://www.w3.org/2002/07/owl#");
	m.setNsPrefix("rdaGr2", "http://rdvocab.info/ElementsGr2/");
	m.setNsPrefix("skos", "http://www.w3.org/2004/02/skos/core#");
	m.setNsPrefix("wgs84_pos", "http://www.w3.org/2003/01/geo/wgs84_pos#");
	m.setNsPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");
	m.setNsPrefix("xml", "http://www.w3.org/XML/1998/namespace");

	merge(src, m);
	//store(m, dst, "RDF/XML-ABBREV");
	store(m, dst, "RDF/XML");
}
 
Example 18
Project: europeana   File: VocsUtils.java   Source Code and License 6 votes vote down vote up
public static boolean loadModel(Model m, String url)
{
	String sContent = getRDF(url);
	if ( sContent == null ) { return false; }

	Model mTemp = ModelFactory.createDefaultModel();
	try {
		mTemp.read(new StringReader(sContent), url, "RDF/XML");
	}
	catch (Exception e) {
		System.err.println("error parsing: " + url + ", error: " + e.getMessage());
		return false;
	}

	m.add(mTemp);

	return true;
}
 
Example 19
Project: europeana   File: BabelNetAnalysis.java   Source Code and License 6 votes vote down vote up
public ObjectStat analyse(File srcList, File src, File dst) throws IOException
{
	Collection<String> c = loadDataURLs(srcList, PATTERN_BABELNET);

	Model m = ModelFactory.createDefaultModel();
	loadModel(m, src, null);

	ObjectStat  stat = new ObjectStat("BabelNet", true, false, true);
	stat.addPropertyValue(m.getProperty("http://babelnet.org/model/babelnet#gloss"));

	ResIterator iter = m.listSubjects();
	while ( iter.hasNext() )
	{
		Resource r = iter.next();
		if ( !c.contains(r.getURI()) ) { continue; }
		stat.newObject(r);
	}

	if ( dst != null ) { stat.print(new PrintStream(dst, "UTF-8")); }

	return stat;
}
 
Example 20
Project: Tapioca   File: AbstractEngine.java   Source Code and License 6 votes vote down vote up
public static Model readRDFMetaDataFile(File rdfMetaDataFile){
    RDFReader reader = new TurtleReader();
    Model rdfMetaDataModel = ModelFactory.createDefaultModel();
    
    LOGGER.info("Loading meta data file from " + rdfMetaDataFile.getAbsolutePath());
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(rdfMetaDataFile);
        reader.read(rdfMetaDataModel, fin, "");
    } catch (FileNotFoundException e) {
        LOGGER.error("Couldn't read meta data from file. Returning null.", e);
        return null;
    } finally {
        IOUtils.closeQuietly(fin);
    }  
    return rdfMetaDataModel;
}
 
Example 21
Project: europeana   File: TestEntityContext.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException
{
	File file = new File("C:\\Users\\Hugo\\Google Drive\\Europeana\\EDM\\jsonld\\agent.xml");

	Model m = ModelFactory.createDefaultModel();
	
	try {
		m.read(new FileInputStream(file), null, "RDF/XML");
	}
	catch (Exception e) {
		e.printStackTrace(System.err);
		return;
	}

	URL url = new URL("file:///C:/Users/Hugo/Google%20Drive/Europeana/EDM/jsonld/context.jsonld");
	new JsonLdWriter(url).write(m, new OutputStreamWriter(System.out));
}
 
Example 22
Project: freme-ner   File: FremeNERLabelMatch.java   Source Code and License 6 votes vote down vote up
private Integer getNumberOfLinks(String nif) {
    Model model = ModelFactory.createDefaultModel();
    model.read(new ByteArrayInputStream(nif.getBytes()), null, "TTL");
    StmtIterator iter = model.listStatements();

    Integer result = 0;

    while (iter.hasNext()) {
        Statement stm = iter.nextStatement();
        if (NIF21Format.RDF_PROPERTY_IDENTREF.equals(stm.getPredicate().toString())) {
            result += 1;
        }
    }

    return result;
}
 
Example 23
Project: JenaKBClient   File: KBIndividualImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSomeMethod2() throws Exception {
  Dataset ds = TDBFactory.createDataset("/scratch/WORK2/jena/dataset2/");
  
  OntModel model1 = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, ds.getNamedModel("vijaym1"));
  OntModel model2 = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, ds.getNamedModel("vijaym2"));
  OntClass thing = model1.createClass("http://www.w3.org/2002/07/owl#Thing");
  model1.createIndividual("http://example.com/onto1#VijayRaj", thing);
  model2.createIndividual("http://example.;cegilovcom/onto2#VijayRaj", thing);
  Model m = model1.union(model2);
  
  FileWriter fw = new FileWriter("/scratch/WORK2/jena/testModels/mergetestds.xml");
  RDFDataMgr.write(fw, ds, RDFFormat.NQUADS_UTF8);
  

}
 
Example 24
Project: t5-doc   File: CSVSToRDFConverter.java   Source Code and License 6 votes vote down vote up
public CSVSToRDFConverter(String sourceFilesDir, String className, String baseNameSpace, String separator,
		String textFieldSeparator, int keyColIndex) {

	nsTBox = baseNameSpace + "model#";
	nsABox = baseNameSpace + "data#";

	this.sourceFilesDir = sourceFilesDir;
	this.className = className;
	this.separator = separator;
	this.textFieldSeparator = textFieldSeparator;

	tboxModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
	aboxModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);

	pathSeparator = System.getProperty("file.separator");
	this.keyColIndex = keyColIndex;
}
 
Example 25
Project: spring-usc   File: GenerateContextFromModel.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws JSONException, KarmaException, IOException {
	Options options = createCommandLineOptions();
	CommandLine cl = CommandLineArgumentParser.parse(args, options, GenerateContextFromModel.class.getSimpleName());
	if(cl == null)
	{
		return;
	}
	String fileName = (String) cl.getOptionValue("modelpath");
	String output = (String) cl.getOptionValue("outputfile");
	if (fileName == null) {
		System.out.println("No model file specified!");
		return;
	}
	if (output == null) {
		output = fileName + ".json";
	}
	File file = new File(fileName);
	Model model = ModelFactory.createDefaultModel();
       InputStream s = new FileInputStream(file);
       model.read(s, null, "TURTLE");
       JSONObject top = new ContextGenerator(model, true).generateContext();
       PrintWriter pw = new PrintWriter(output);
       pw.println(top.toString(4));
       pw.close();
}
 
Example 26
Project: Cetus   File: ExtendedCetusSurfaceFormExtractorTest.java   Source Code and License 6 votes vote down vote up
public static List<Document> loadDataset() {
    Model nifModel = ModelFactory.createDefaultModel();
    InputStream inputStream = ExtendedCetusSurfaceFormExtractorTest.class.getClassLoader().getResourceAsStream(
            DATASET_NAME);
    if (inputStream == null) {
        LOGGER.error("Couldn't get InputStream for the dataset. Returning null");
        return null;
    }
    try {
        LocalNIFParser parser = new LocalNIFParser(Lang.TTL);
        return parser.parseNIF(inputStream, nifModel);
    } catch (Exception e) {
        LOGGER.error("Exception while parsing dataset. Returning null", e);
        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 27
Project: entityclassifier-core   File: YagoOntologyManager.java   Source Code and License 6 votes vote down vote up
public Model getHierarchyModel(String uri){
    
    // returns all subclasses for given URI
    Model m = ModelFactory.createDefaultModel();
    OntoRecord initRecord = new OntoRecord();
    initRecord.setUri(uri);
    
    while(initRecord !=null){
        
        initRecord = getSuperclass(initRecord.getUri());
        
        if(initRecord != null){
            StmtIterator iter1 = model.listStatements( new SimpleSelector(ResourceFactory.createResource(uri), RDFS.subClassOf,  (RDFNode)null));                
            m.add(iter1);
        }
    }
     
    return m;
}
 
Example 28
Project: Tapioca   File: LabelExtractionHandlerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for LabelExtractionHandler#addExtractedLabels(), 5.nt
 */
@Test
public final void test03AddExtractedLabels() {
	// set input file
	String inFile = "src/test/data/expected_5.nt";

	// set expected result
	Model expected = null;
	try {
		expected = ModelFactory.createDefaultModel();
		expected.read( inFile, "N-TRIPLES" );
	}
	catch( Exception e ) {
		fail( e.toString() );
	}
	
	// run test
	handler.addExtractedLabels();
	assertTrue( expected.isIsomorphicWith( handler.getVoidModel() ) );		
}
 
Example 29
Project: OpenCollegeGraph   File: AutoReloadableDataset.java   Source Code and License 6 votes vote down vote up
private void reload() {
	loader.getMapping().connect();
	GraphD2RQ graph = loader.getGraphD2RQ();
	
	datasetGraph = DatasetGraphFactory.createOneGraph(graph);
	defaultModel = ModelFactory.createModelForGraph(datasetGraph.getDefaultGraph());		

	hasTruncatedResults = false;
	for (Database db: loader.getMapping().databases()) {
		if (db.getResultSizeLimit() != Database.NO_LIMIT) {
			hasTruncatedResults = true;
		}
	}

	if (autoReload) {
		lastModified = watchedFile.lastModified();
		lastReload = System.currentTimeMillis();
	}
}
 
Example 30
Project: p3-osm-transformer   File: OsmXmlParser.java   Source Code and License 6 votes vote down vote up
/**
 * Performs the actual transformation mapping the data extracted from OSM XML data to a Jena model.
 * @return
 */
public Model jenaTransform() {
    Model model = ModelFactory.createDefaultModel();
    processXmlBinary();
    for(String wayId:  osmWayNodeMap.keySet()) {
        OsmWay wayObj = osmWayNodeMap.get(wayId);
        Resource wayUri = model.createResource("http://fusepoolp3.eu/osm/way/" + wayId);
        wayUri.addProperty(model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), model.createResource("http://schema.org/PostalAddress"));
        wayUri.addProperty(model.createProperty("http://schema.org/streetAddress"), wayObj.getTagName());
        Resource geometryUri = model.createResource("http://fusepoolp3.eu/osm/geometry/" + wayId);
        wayUri.addProperty(model.createProperty("http://www.opengis.net/ont/geosparql#geometry"), geometryUri);
        String linestring = getWktLineString(wayObj.getNodeReferenceList());
        geometryUri.addProperty(model.createProperty("http://www.opengis.net/ont/geosparql#asWKT"), linestring);            
    }
    log.info("Number of triples transformed: " + model.size());
    return model;
}
 
Example 31
Project: ATTIC-osit   File: SPDXDocumentFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Encoding Treating
 * 
 * Date: 2013. 5. 22. ���� 12:30:31
 * Author: ytaek.kim
 * 
 * Method Brief : 
 * @param fileNameOrUrl
 * @return
 * @throws IOException
 * @throws InvalidSPDXAnalysisException
 *
 * #Logs:
 */
public static SPDXDocument creatSpdxDocument(String fileNameOrUrl, String charsetName) throws IOException, InvalidSPDXAnalysisException {
	try {
		Class.forName("net.rootdev.javardfa.jena.RDFaReader");
	} catch(java.lang.ClassNotFoundException e) {
		logger.warn("Unable to load the RDFaReader Class");
	}  

	InputStream spdxRdfInput = FileManager.get().open(fileNameOrUrl);
	if (spdxRdfInput == null)
		throw new FileNotFoundException("Unable to open \"" + fileNameOrUrl + "\" for reading");
	
	InputStreamReader inputReader = new InputStreamReader(spdxRdfInput, charsetName);
	
	Model model = ModelFactory.createDefaultModel();
	model.read(inputReader, figureBaseUri(fileNameOrUrl), fileType(fileNameOrUrl));
	return new SPDXDocument(model);
}
 
Example 32
Project: u-qasar.platform   File: UQasarUtil.java   Source Code and License 6 votes vote down vote up
/**
	 * Read the RDF model from files.
	 */
	public static void readSemanticModelFiles() {
		logger.debug("Reading the model from a file");
		// Read the model to an existing model
		String dataDir = UQasarUtil.getDataDirPath();
		String modelPath = "file:///" + dataDir + ONTOLOGYFILE;
//		String modelPath = "file:///C:/nyrhinen/Programme/jboss-as-7.1.1.Final/standalone/data/uq-ontology-model.rdf";

		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
		RDFDataMgr.read(model, modelPath);
		// Test output to standard output
		//		RDFDataMgr.write(System.out, uqModel, RDFFormat.RDFXML_PRETTY);
		logger.debug("Model read from file " +modelPath);
		UQasarUtil.setUqModel(model);
		System.out.println("Reading done.");
	}
 
Example 33
Project: europeana   File: VocsUtils.java   Source Code and License 6 votes vote down vote up
public static Model getModel(File f)
{
	Model m = ModelFactory.createDefaultModel();
	if ((f == null) || !f.exists()) { return m; }

	try {
		FileInputStream fis = new FileInputStream(f);
		try {
			 m.read(fis, "RDF/XML");
		}
		finally { fis.close(); }
	}
	catch(Exception e) {
		e.printStackTrace();
	}

	return m;
}
 
Example 34
Project: semweb4j   File: DataTypeTesting.java   Source Code and License 6 votes vote down vote up
@Test
public void testNewToJenaNode() throws ModelRuntimeException {
	com.hp.hpl.jena.rdf.model.Model model = ModelFactory.createDefaultModel();
	
	DatatypeLiteralImpl l1 = new DatatypeLiteralImpl("test", new URIImpl("test:funky", false));
	DatatypeLiteralImpl l2 = new DatatypeLiteralImpl("test", new URIImpl("test:funky", false));
	
	Node n1 = TypeConversion.toJenaNode(l1, model);
	Node n2 = TypeConversion.toJenaNode(l2, model);
	
	assertTrue(n1.equals(n2));
	
	Object o1 = TypeConversion.toRDF2Go(n1);
	Object o2 = TypeConversion.toRDF2Go(n2);
	
	assertTrue(o1 instanceof DatatypeLiteral);
	assertTrue(o2 instanceof DatatypeLiteral);
	
	DatatypeLiteralImpl new1 = (DatatypeLiteralImpl)o1;
	DatatypeLiteralImpl new2 = (DatatypeLiteralImpl)o2;
	
	assertTrue(new1.getValue().equals("test"));
	assertTrue(new2.getValue().equals("test"));
	assertTrue(new1.getDatatype().equals(new URIImpl("test:funky", false)));
	assertTrue(new2.getDatatype().equals(new URIImpl("test:funky", false)));
}
 
Example 35
Project: europeana   File: TestContextualEntities.java   Source Code and License 6 votes vote down vote up
public static void parseJSONLD(File file, PrintStream ps)
{
	System.out.println("Parsing file: " + file.getName());

	Model m = ModelFactory.createDefaultModel();
	
	try {
		m.read(new FileInputStream(file), null, "JSONLD");
	}
	catch (Exception e) {
		e.printStackTrace(ps);
		System.out.println();
		return;
	}

	//new Test().test(new OutputStreamWriter(ps), m.getGraph());
	//WriterGraphRIOT r = RDFDataMgr.createGraphWriter(Lang.JSONLD);
	//.write(ps, m.getGraph(), pm, null, null);
	//RDFDataMgr.write(ps, m, Lang.JSONLD);
	m.write(ps, "RDF/XML");
	System.out.println();
}
 
Example 36
Project: DoSeR   File: S1CategoryToEntities.java   Source Code and License 6 votes vote down vote up
public static final void main(String[] args) throws MalformedURLException, FileNotFoundException {
	Model model = ModelFactory.createDefaultModel();
	model.read(args[0]);
	StmtIterator iter = model.listStatements();
	System.out.println("Start");
	while (iter.hasNext()) {
		Statement stmt = iter.next();
		Resource subject = stmt.getSubject();
		String url[] = subject.getURI().split("/");
		String subjectIdent = url[url.length - 1];
		RDFNode object = stmt.getObject();
		String s[] = object.asResource().getURI().split("/");
		String objIdent = s[s.length - 1];
		try {
			System.out.println(objIdent+"    "+subjectIdent);
			HBaseOperations.getInstance().addRecord("DBPEDIA_CatToEnts", objIdent, "data", String.valueOf(subjectIdent.hashCode()), subjectIdent);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example 37
Project: spring-usc   File: DataSourcePublisher.java   Source Code and License 6 votes vote down vote up
@Override
public Model exportToJenaModel() {
	
	Model model = ModelFactory.createDefaultModel();
	
	String baseNS = source.getUri();
	model.setNsPrefix("", baseNS);
	model.setNsPrefix(Prefixes.KARMA, Namespaces.KARMA);
	model.setNsPrefix(Prefixes.RDF, Namespaces.RDF);
	model.setNsPrefix(Prefixes.RDFS, Namespaces.RDFS);
	model.setNsPrefix(Prefixes.SWRL, Namespaces.SWRL);

	addSourceInfoPart(model);
	
	return model;
	
}
 
Example 38
Project: DoSeR   File: ExtractRelevantDBpediaCategories.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	Model m = ModelFactory.createDefaultModel();
	m.read(args[0]);
	StmtIterator iter = m.listStatements();
	HashSet<String> hash = new HashSet<String>();
	while (iter.hasNext()) {
		Statement stmt = iter.next();
		RDFNode node = stmt.getObject();
		String uri = node.asResource().getURI();
		hash.add(uri);
	}
	File output = new File(args[1]);
	try {
		PrintWriter writer = new PrintWriter(output);
		for(String s : hash) {
			writer.println(s);
		}
		writer.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
}
 
Example 39
Project: Jena-Based-Semantic-Web-Tutorial   File: RDFDataManipulation.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	Model model = ModelFactory.createDefaultModel();
	ModelUtils.fillModel(model, FOAF_BASE_URI, FOAF_SCHEMA_FilePath);

	// renderer all namespaces
	System.out.println(model.getNsPrefixMap());

	// insert foaf:me rdf:type foaf:Person
	Resource me = model.createResource(FOAF_BASE_URI + "me");
	Property rdfType = model.getProperty(Constants.RDF_TYPE_URL);
	Resource FOAFPersonClass = model.getResource(FOAF_BASE_URI + "Person");
	model.add(me, rdfType, FOAFPersonClass);

	// query the inserted facts
	StringBuilder query = SPARQLUtils.getRegualrSPARQLPREFIX();
	query.append("PREFIX foaf: <http://xmlns.com/foaf/0.1/>").append(Constants.NEWLINE);
	query.append("SELECT DISTINCT ?person WHERE {?person rdf:type foaf:Person}");
	SPARQLUtils.query(model, query.toString(), "?person");
}
 
Example 40
Project: ontonethub   File: JenaModelReader.java   Source Code and License 5 votes vote down vote up
@Override
public Model readFrom(Class<Model> type, Type genericType, Annotation[] annotations,
		MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
		throws IOException, WebApplicationException {
	
	Model model = ModelFactory.createDefaultModel();
	model.read(entityStream, null);
	return model;
}
 
Example 41
Project: harvesters   File: SubprojectsSellersImpl.java   Source Code and License 5 votes vote down vote up
public static void subprojectsSellers() {

        //services for each table
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        SubProjectSellersService sub = (SubProjectSellersService) ctx.getBean("subProjectSellersServiceImpl");

        List<SubProjectSellers> subProjectSeller = sub.getSubProjectSellers();

        //--------------RDF Model--------------//
        Model model = ModelFactory.createDefaultModel();
        Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
        InfModel infModel = ModelFactory.createInfModel(reasoner, model);

        model.setNsPrefix("elod", OntologySpecification.elodPrefix);
        model.setNsPrefix("gr", OntologySpecification.goodRelationsPrefix);


        for (SubProjectSellers subProjectSeller1 : subProjectSeller) {
            Resource instanceSeller = infModel.createResource(OntologySpecification.instancePrefix
                    + "Organization/" + subProjectSeller1.getSellerId());
            Resource instanceSubProject = infModel.createResource(OntologySpecification.instancePrefix
                    + "Subproject/" + subProjectSeller1.getOps() + "/" + subProjectSeller1.getSubProjectId());
            infModel.add(instanceSeller, RDF.type, OntologySpecification.organizationResource);
            infModel.add(instanceSeller, RDF.type, OntologySpecification.businessResource);
            infModel.add(instanceSubProject, RDF.type, OntologySpecification.subProjectResource);
            instanceSubProject.addProperty(OntologySpecification.seller, instanceSeller);
        }

        try {
            FileOutputStream fout = new FileOutputStream(
                    "/Users/giovaf/Documents/yds_pilot1/espa_tests/22-02-2016_ouput/subProjectSellersEspa.rdf");
            model.write(fout);
        } catch (IOException e) {
            System.out.println("Exception caught" + e.getMessage());
        }
    }
 
Example 42
Project: harvesters   File: SellersImpl.java   Source Code and License 5 votes vote down vote up
public static void espaSellers() {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        SellersService sellers = (SellersService) ctx.getBean("sellersServiceImpl");

        List<Sellers> seller = sellers.getSellers();

        //--------------RDF Model--------------//
        Model model = ModelFactory.createDefaultModel();
        Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
        InfModel infModel = ModelFactory.createInfModel(reasoner, model);

        model.setNsPrefix("elod", OntologySpecification.elodPrefix);
        model.setNsPrefix("gr", OntologySpecification.goodRelationsPrefix);
        model.setNsPrefix("vcard", OntologySpecification.vcardPrefix);

        for (Sellers seller1 : seller) {
            Resource instanceSeller = infModel.createResource(OntologySpecification.instancePrefix + "Organization/" + seller1.getId());
            infModel.add(instanceSeller, RDF.type, OntologySpecification.organizationResource);
            instanceSeller.addProperty(OntologySpecification.name, seller1.getEponimia(), XSDDatatype.XSDstring);
        }

        try {
            FileOutputStream fout = new FileOutputStream(
                    "/Users/giovaf/Documents/yds_pilot1/espa_tests/22-02-2016_ouput/sellersEspa.rdf");
            model.write(fout);
        } catch (IOException e) {
            System.out.println("Exception caught" + e.getMessage());
        }
    }
 
Example 43
Project: karma2vivo   File: VIVOSPARQLClient.java   Source Code and License 5 votes vote down vote up
/**
 * Get all existing triples in a named graph
 *
 * @param namedGraph String with graph name.
 * @return Jena model with the existing triples.
 * @throws IOException
 */
public Model getExistingNamedGraph(String namedGraph) throws IOException {
    String rq = "construct {?s ?p ?o} where { GRAPH <?g> {?s ?p ?o}}";
    String query = rq.replace("?g", namedGraph);
    //Accepting n-triples only.
    Header header = new BasicHeader(HttpHeaders.ACCEPT, "text/plain");

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        log.debug("Connecting to SPARQL query API at: " + queryApi);
        log.debug("SPARQL query: " + query);
        HttpPost httpPost = new HttpPost(queryApi);
        httpPost.addHeader(header);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("query", query));
        nvps.add(new BasicNameValuePair("email", vivoEmail));
        nvps.add(new BasicNameValuePair("password", vivoPassword));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            //read response into Jena model and return
            Model model = ModelFactory.createDefaultModel();
            model.read(is, null, "N-TRIPLES");
            return model;
        } finally {
            response.close();
        }

    } finally {
        httpclient.close();
    }
}
 
Example 44
Project: karma2vivo   File: VIVOSPARQLClient.java   Source Code and License 5 votes vote down vote up
/**
 * Method called to Chunk the triples into N-Sized batches and post to VIVO.
 * This is designed to work around / handle errors when posting sets of triples
 * over 10,000 to the API.
 *
 * @param namedGraph String with named graph.
 * @param changeModel Jena model with set of changes to sync to store.
 * @param changeType Either add or remove.
 * @return Boolean true if update was successful.
 * @throws IOException
 */
private Boolean bulkUpdate(String namedGraph, Model changeModel, String changeType) throws IOException {
    // Temporary model to hold
    Model tmpModel = ModelFactory.createDefaultModel();
    Integer bSize = Integer.parseInt(batchSize);
    // Use an integer to count triples rather than calling size on the model
    // during each loop.
    Integer size = 0;
    StmtIterator iter = changeModel.listStatements();
    while (iter.hasNext()) {
        Statement stmt = iter.nextStatement();  // get next statement
        tmpModel.add(stmt);
        size++;
        if (size >= bSize) {
            // Submit
            log.info("Submitting " + size + " triples to " + namedGraph);
            submitBatch(tmpModel, namedGraph, changeType);
            // Reset the tmp model.
            tmpModel.removeAll();
            // Reset the counter.
            size = 0;
        }
    }
    log.info("model size:" + tmpModel.size());
    // Submit the remaining statements, if any.
    if (tmpModel.size() > 0) {
        submitBatch(tmpModel, namedGraph, changeType);
    }
    return true;
}
 
Example 45
Project: KBox   File: TDB.java   Source Code and License 5 votes vote down vote up
public static Model createModel(String... dbDirs) {
	Model mainModel = null; 
	Dataset dataset = null;
	for(String dbDir : dbDirs) {
		dataset = TDBFactory.createDataset(dbDir);
		if(mainModel == null) {
			mainModel = dataset.getDefaultModel();				
		} else {
			Model secondaryModel = dataset.getDefaultModel();
			mainModel = ModelFactory.createUnion(mainModel, secondaryModel);
		}
	}
	mainModel = ModelFactory.createRDFSModel(mainModel);
	return mainModel;
}
 
Example 46
Project: r2rml-kit   File: VocabularySummarizer.java   Source Code and License 5 votes vote down vote up
public Model triplesInvolvingVocabulary(Model model) {
	Model result = ModelFactory.createDefaultModel();
	result.getNsPrefixMap().putAll(model.getNsPrefixMap());
	StmtIterator it = model.listStatements();
	while (it.hasNext()) {
		Statement stmt = it.next();
		if (properties.contains(stmt.getPredicate())
				|| (stmt.getPredicate().equals(RDF.type) && classes.contains(stmt.getObject()))) {
			result.add(stmt);
		}
	}
	return result;
}
 
Example 47
Project: r2rml-kit   File: ResourceCollection.java   Source Code and License 5 votes vote down vote up
public Model getInventoryModel(int limit) {
	log.info("Listing entity set: " + entityMaker);
	Model result = ModelFactory.createDefaultModel();
	result.setNsPrefixes(mapping.getPrefixes());
	FindQuery query = new FindQuery(Triple.ANY, inventory, limit, 
			new ExecutionContext(mapping.getContext(), null, null, null));
	Iterator<Triple> it = TripleQueryIter.create(query.iterator());
	while (it.hasNext()) {
		result.getGraph().add(it.next());
	}
	return result;
}
 
Example 48
Project: r2rml-kit   File: CompatibilityFileManager.java   Source Code and License 5 votes vote down vote up
public static Model loadModel(String filenameOrURL, String baseIRI, String lang) {
	if (!filenameOrURL.toLowerCase().startsWith("jar:")) {
		return FileManager.get().loadModel(filenameOrURL, baseIRI, lang);
	}
	Model result = ModelFactory.createDefaultModel();
	result.read(filenameOrURL, baseIRI, lang);
	return result;
}
 
Example 49
Project: r2rml-kit   File: ProcessorTestBase.java   Source Code and License 5 votes vote down vote up
@Test
public void testReadWrite() {
	StringWriter out = new StringWriter();
	loader.getWriter().write(out);
	Model parsed = ModelFactory.createDefaultModel();
	parsed.read(new StringReader(out.toString()), 
			BASE_IRI, "TURTLE");
	assertIsomorphic(loader.getMappingModel(), parsed);
}
 
Example 50
Project: SemanticSCo   File: SemanticReasoner.java   Source Code and License 5 votes vote down vote up
public LinkedList<SemanticConcept> findAllLabels(String ontologyUri,String rootClass){
    
    LinkedList<SemanticConcept> list = new LinkedList<>();
    
    try{
    
        //Create a reasoner
        OntModel model = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);

        //Create new URL of ontology
        URL url = new URL(ontologyUri);
    
        //Create model for the ontology
        model.read(url.openStream(),null);
    
        //Load model to the reasoner
        model.prepare();
    
        //Compute the classification tree
        ((PelletInfGraph) model.getGraph()).getKB().classify();
        
        //Set OWL root element (e.g., it could be thing: model.getOntClass(OWL.Thing.getURI()))
        OntClass owlRoot = model.getOntClass(rootClass);
        
        SemanticConcept sc = new SemanticConcept();
        sc.setUrl(owlRoot.getURI());
        sc.setName("");
        sc.setSemanticSimilarity("");
        list.add(sc);
    
        //For each subclass (direct or indirect)
        for (Iterator it = owlRoot.listSubClasses(false); it.hasNext();) {

            OntClass subclass = (OntClass) it.next();

            //If subclass is not anonymous
            if (!subclass.isAnon()) {

                //If subclass is not nothing
                if(!subclass.getURI().equals(com.hp.hpl.jena.vocabulary.OWL.Nothing.getURI())){
                    
                    sc = new SemanticConcept();
                    sc.setUrl(subclass.getURI());
                    sc.setName("");
                    sc.setSemanticSimilarity("");
                
                    list.add(sc);
                }
            }
        }
        
    }catch(IOException ex){}
    
    return list;
    
}
 
Example 51
Project: zebra-puzzle-workshop   File: Exercise4.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 52
Project: zebra-puzzle-workshop   File: Exercise32.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel(String modelInput) {
    Reasoner reasoner = PelletReasonerFactory.theInstance().create();
    Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
    OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
    ontModel.read(getClass().getResourceAsStream("/" + modelInput), null, TTL);
    return ontModel;
}
 
Example 53
Project: zebra-puzzle-workshop   File: Exercise4Jena.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 54
Project: zebra-puzzle-workshop   File: Exercise2.java   Source Code and License 5 votes vote down vote up
private Model createModel() {
  Model model = ModelFactory.createDefaultModel();
  String NS = "http://www.computas.no/zebra/";
  model.setNsPrefix("", NS);
  model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
  Resource subject = model.createResource(NS + "Joe");
  Property predicate = model.createProperty(NS + "hasSentMessage");
  String object = "Hello World!";
  subject.addProperty(predicate, object, XSDDatatype.XSDstring);
  return model;
}
 
Example 55
Project: zebra-puzzle-workshop   File: Exercise4.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 56
Project: zebra-puzzle-workshop   File: Exercise2.java   Source Code and License 5 votes vote down vote up
private Model createModel() {
  Model model = ModelFactory.createDefaultModel();
  String NS = "http://www.computas.no/zebra/";
  model.setNsPrefix("", NS);
  model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
  //TODO
  return model;
}
 
Example 57
Project: c4a_data_repository   File: MetadataCreator.java   Source Code and License 5 votes vote down vote up
public static Model loadMetadataTemplate(InputStream is) {
	try {
		Model tplModel = ModelFactory.createDefaultModel();
		tplModel.read(is, "about:prefix:", "TTL");
		return tplModel;
	} catch (JenaException e) {
		// ignore
	}
	return null;
}
 
Example 58
Project: c4a_data_repository   File: ClassMapServlet.java   Source Code and License 5 votes vote down vote up
private Model classMapListModel() {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	Model result = ModelFactory.createDefaultModel();
	Resource list = result.createResource(server.baseURI() + "all");
	list.addProperty(RDFS.label, "D2R Server contents");
	for (String classMapName: getClassMapLister().classMapNames()) {
		Resource instances = result.createResource(server.baseURI() + "all/" + classMapName);
		list.addProperty(RDFS.seeAlso, instances);
		instances.addProperty(RDFS.label, "List of all instances: " + classMapName);
	}
	server.addDocumentMetadata(result, list);
	return result;
}
 
Example 59
Project: c4a_data_repository   File: ClassMapLister.java   Source Code and License 5 votes vote down vote up
public Model classMapInventory(String classMapName, int limitPerClassMap) {
	log.info("Listing class map: " + classMapName);
	List<TripleRelation> inventoryBridges = classMapInventoryBridges.get(classMapName);
	if (inventoryBridges == null) {
		return null;
	}
	Model result = ModelFactory.createDefaultModel();
	result.setNsPrefixes(mapping.getPrefixMapping());
	FindQuery query = new FindQuery(Triple.ANY, inventoryBridges, limitPerClassMap, null);
	result.getGraph().getBulkUpdateHandler().add(TripleQueryIter.create(query.iterator()));
	return result;
}
 
Example 60
Project: c4a_data_repository   File: MappingGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an in-memory Jena model containing the D2RQ mapping.
 * 
 * @param baseURI Base URI for resolving relative URIs in the mapping, e.g., map namespace
 * @return In-memory Jena model containing the D2RQ mapping
 */
public Model mappingModel(String baseURI) {
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	writeMapping(out);
	try {
		String mappingAsTurtle = out.toString("UTF-8");
		Model result = ModelFactory.createDefaultModel();
		result.read(new StringReader(mappingAsTurtle), baseURI, "TURTLE");
		return result;
	} catch (UnsupportedEncodingException ex) {
		throw new RuntimeException("UTF-8 is always supported");
	}
}