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

The following are top voted examples for showing how to use org.apache.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: Stargraph   File: HDTModelFactory.java   Source Code and License 7 votes vote down vote up
@Override
protected Model createModel(String dbId) {
    Model model = null;
    try {
        File hdtFile = getHDTPath(dbId).toFile();
        if (hdtFile.exists()) {
            boolean useIdx = useIndex(dbId);
            String hdtFilePathStr = hdtFile.getAbsolutePath();
            logger.info(marker, "Loading '{}', useIndex={}", hdtFilePathStr, useIdx);
            HDT hdt = useIdx ? HDTManager.mapIndexedHDT(hdtFilePathStr, null) : HDTManager.loadHDT(hdtFilePathStr, null);
            HDTGraph graph = new HDTGraph(hdt);
            model = ModelFactory.createModelForGraph(graph);
            return model;
        }

       throw new FileNotFoundException("HDT file not found: '" + hdtFile + "'");

    } catch (Exception e) {
        throw new StarGraphException(e);
    }
    finally {
        if (model == null) {
            logger.error(marker, "No Graph Model instantiated for {}", dbId);
        }
    }
}
 
Example 2
Project: lambdora   File: LambdoraLdp.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new object.
 *
 * This originally used application/octet-stream;qs=1001 as a workaround
 * for JERSEY-2636, to ensure requests without a Content-Type get routed here.
 * This qs value does not parse with newer versions of Jersey, as qs values
 * must be between 0 and 1.  We use qs=1.000 to mark where this historical
 * anomaly had been.
 *
 * @param contentDisposition the content Disposition value
 * @param requestContentType the request content type
 * @param slug the slug value
 * @param requestBodyStream  the request body stream
 * @param link the link value
 * @param digest the digest header
 * @return 201
 * @throws InvalidChecksumException if invalid checksum exception occurred
 * @throws IOException if IO exception occurred
 * @throws MalformedRdfException if malformed rdf exception occurred
 */
@POST
@Consumes({MediaType.APPLICATION_OCTET_STREAM + ";qs=1.000", WILDCARD})
@Produces({TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8",
        N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET,
        TURTLE_X, TEXT_HTML_WITH_CHARSET, "*/*"})
public Response createObject(@HeaderParam(CONTENT_DISPOSITION) final ContentDisposition contentDisposition,
                             @HeaderParam(CONTENT_TYPE) final MediaType requestContentType,
                             @HeaderParam("Slug") final String slug,
                             @ContentLocation final InputStream requestBodyStream,
                             @HeaderParam(LINK) final String link,
                             @HeaderParam("Digest") final String digest)
        throws InvalidChecksumException, IOException, MalformedRdfException {
    LOGGER.info("POST: {}", externalPath);

    final ContainerService containerService = getContainerService();
    final URI resourceUri = createFromPath(externalPath);

    //check that resource exists
    if (!containerService.exists(resourceUri)) {
        if (!isRoot(resourceUri)) {
            return status(NOT_FOUND).build();
        } else {
            createRoot();
        }
    }

    final String newResourceName = slug == null ? UUID.randomUUID().toString() : slug;
    final String resourcePath = (isRoot(resourceUri) ? "" : resourceUri.getPath());
    final URI newResourceUri = createFromPath(resourcePath + "/" + newResourceName);
    final Container container = containerService.findOrCreate(newResourceUri);
    final Model model = ModelFactory.createDefaultModel();

    model.read(requestBodyStream, container.getIdentifier().toString(), "TTL");
    final Stream<Triple> triples = model.listStatements().toList().stream().map(Statement::asTriple);
    container.updateTriples(triples);
    return created(toExternalURI(container.getIdentifier(), headers)).build();
}
 
Example 3
Project: Stargraph   File: NTriplesModelFactory.java   Source Code and 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 4
Project: Java-APIs   File: DiffToSparqlInsertUpdateBuilderTests.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  model = ModelFactory.createDefaultModel();
  model.read("Playpen2.ttl", "TTL");

  prop1 = model.createProperty("http://foo.com/foo");
  prop2 = model.createProperty("http://foo.com/bar");
  prop3 = model.createProperty("http://foo.com/fasel");
  prop4 = model.createProperty("http://foo.com/fase2");
  prop5 = model.createProperty("http://foo.com/thisUri");
  prop6 = model.createProperty("http://foo.com/stringy");

  newConceptRes = model.createResource("http://example.com/Playpen2#newConcept");
  foobarFooRes = model.createResource("http://example/com/Playpen2#foobarFoo");

}
 
Example 5
Project: Java-APIs   File: OEBatchClientTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testLocalDiff() throws Exception {
  Model firstModel = ModelFactory.createDefaultModel();
  firstModel.read("Playpen2.ttl", "TTL");

  Model secondModel = ModelFactory.createDefaultModel();
  secondModel.add(firstModel);
  Resource res1 = secondModel.createResource(resIri1);
  res1.addProperty(RDF.type, SKOS.Concept);

  client.setCurrentModel(firstModel);
  client.setPendingModel(secondModel);
  assertEquals(firstModel, client.getCurrentModel());
  assertEquals(secondModel, client.getPendingModel());

  RDFDifference diff = client.getBatchDiff();

  assertTrue(diff.getInLeftOnly().size() == 0);
  assertTrue(diff.getInRightOnly().size() == 1);

  assertFalse(diff.getInLeftOnly().containsResource(res1));
  assertFalse(diff.getInLeftOnly().contains(res1, RDF.type, SKOS.Concept));

  assertTrue(diff.getInRightOnly().containsResource(res1));
  assertTrue(diff.getInRightOnly().contains(res1, RDF.type, SKOS.Concept));
}
 
Example 6
Project: alvisnlp   File: RDFProjector.java   Source Code and License 6 votes vote down vote up
private Model createModel(Logger logger) throws IOException {
		LoggingUtils.configureSilentLog4J();
		Model model = ModelFactory.createDefaultModel();
		model.setNsPrefixes(PrefixMapping.Standard);
		model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
		model.setNsPrefix("skos", "http://www.w3.org/2004/02/skos/core#");
		model.setNsPrefix("oboInOwl", "http://www.geneontology.org/formats/oboInOwl#");
		model.setNsPrefixes(prefixes);
		for (InputStream is : Iterators.loop(source.getInputStreams())) {
			logger.info("loading model from: " + source.getStreamName(is));
//			System.err.println("is = " + is);
//			model.read(is, null, Lang.RDFXML.toString());
			RDFDataMgr.read(model, is, Lang.RDFXML);
		}
		return model;
	}
 
Example 7
Project: dotwebstack-framework   File: ShaclValidator.java   Source Code and License 6 votes vote down vote up
private Model getJenaModel(@NonNull org.eclipse.rdf4j.model.Model model) {
  Model jenaModel = ModelFactory.createDefaultModel();
  java.util.Iterator<org.eclipse.rdf4j.model.Statement> iterator = model.iterator();

  while (iterator.hasNext()) {
    org.eclipse.rdf4j.model.Statement rdf4jStatement = iterator.next();

    // create resource / subject
    Resource resource = rdf4jResourceToJenaResource(jenaModel, rdf4jStatement.getSubject());
    // create property / predicate
    Property property =
        rdf4jPropertyToJenaProperty(jenaModel, (SimpleIRI) rdf4jStatement.getPredicate());
    // create rdfnode / object
    RDFNode node = rdf4jValueToJenaRdfNode(jenaModel, rdf4jStatement.getObject());

    Statement statement = ResourceFactory.createStatement(resource, property, node);
    jenaModel.add(statement);
  }
  return jenaModel;
}
 
Example 8
Project: linked_data_authorities   File: Loader.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
PropertyConfigurator.configure("log4j.info");
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
FileOutputStream out = new FileOutputStream(new File("/usr/local/RAID/geonames.nt"));
String buffer = null;
int count = 0;

while ((buffer = reader.readLine()) != null) {
    if (++count % 2 == 0) {
	logger.debug("processing xml: " + buffer);
	Model model = ModelFactory.createDefaultModel() ;
	model.read(new StringReader(buffer), null, "RDF/XML");
	model.write(out, "N-TRIPLE");
    } else {
	logger.info("skipping: " + buffer);
    }
}
reader.close();
   }
 
Example 9
Project: SDA   File: SDADatasetAccessor.java   Source Code and 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 10
Project: SDA   File: OneM2MContentInstanceMapper.java   Source Code and 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 11
Project: SDA   File: SDADatasetAccessor.java   Source Code and 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 12
Project: SDA   File: OneM2MAEDTO.java   Source Code and License 6 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);
	
	// gooper
	if(! model.isClosed()) {
		model.close();
	}
	if(model != null) {
		model = null;
	}

}
 
Example 13
Project: SDA   File: OneM2MCSEBaseDTO.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	String sample = "{     \"_id\" : ObjectId(\"560c9d741ee8203c53a63569\"),     \"rn\" : \"CONTENT_INST_5\",     \"ty\" : 4,     \"ri\" : \"CONTENT_INST_5\",     \"pi\" : \"CONTAINER_37\",     \"lbl\" : [          \"cnt-switch\"     ],     \"cr\" : \"C_AE-D-GASLOCK1004\",     \"cnf\" : \"text/plain:0\",     \"cs\" : 3,     \"con\" : \"Off\",     \"_uri\" : \"/herit-in/herit-cse/ae-gaslock1004/cnt-switch/CONTENT_INST_5\",     \"ct\" : \"20151001T114156\",     \"lt\" : \"20151001T114156\" , \"or\":\"http://www.iotoasis.org/ontology/StateCondition\" }";
	Gson gson = new Gson();
	OneM2MContentInstanceDTO cont = gson.fromJson(sample, OneM2MContentInstanceDTO.class);
	System.out.println(cont);

	OneM2MContentInstanceMapper mapper = new OneM2MContentInstanceMapper(cont);
	Model model = ModelFactory.createDefaultModel();
	model.add(mapper.from());

	// 스트링 변환부분
	RDFDataMgr.write(System.out, model, RDFFormat.NTRIPLES);
	
	// gooper
	if(! model.isClosed()) {
		model.close();
	}
	if(model != null) {
		model = null;
	}

}
 
Example 14
Project: Lemming   File: NumberOfTrianglesMetricTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    Model model = ModelFactory.createDefaultModel();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(GRAPH_FILE);
    model.read(is, null, "N3");
    IOUtils.closeQuietly(is);

    GraphCreator creator = new GraphCreator();
    ColouredGraph graph = creator.processModel(model);
    Assert.assertNotNull(graph);

    NumberOfTrianglesMetric metric = new NumberOfTrianglesMetric();
    double countedTriangles = metric.apply(graph);

    Assert.assertEquals(EXPECTED_TRIANGLES, countedTriangles, 0.000001);
}
 
Example 15
Project: Lemming   File: HITSTest.java   Source Code and License 6 votes vote down vote up
@Test
    public void test() {
        Model model = ModelFactory.createDefaultModel();
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(GRAPH_FILE);
        model.read(is, null, "N3");
        IOUtils.closeQuietly(is);

        GraphCreator creator = new GraphCreator();
        ColouredGraph graph = creator.processModel(model);
        
        //System.out.println("matrix: " +graph.getGraph().getAdjacencyMatrix());
//        System.out.println("graph.getInNeighborhoodsArray()" +Arrays.deepToString(graph.getInNeighborhoodsArray()));
//        System.out.println("graph.getOutNeighborhoodsArray()" +Arrays.deepToString(graph.getOutNeighborhoodsArray()));
        
        // Commented out the following line since HITS is missing.
        // new HITS(graph);
        
        
//        graph.getGraph().display();
//        try {
//            Thread.sleep(100000);
//        } catch (InterruptedException ex) {
//            Logger.getLogger(HITSTest.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }
 
Example 16
Project: Lemming   File: InDegreeDistributionMetricTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    Model model = ModelFactory.createDefaultModel();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(GRAPH_FILE);
    model.read(is, null, "N3");
    IOUtils.closeQuietly(is);

    GraphCreator creator = new GraphCreator();
    ColouredGraph graph = creator.processModel(model);

    InDegreeDistributionMetric metric = new InDegreeDistributionMetric();
    IntDistribution distribution = metric.apply(graph);

    Assert.assertArrayEquals(EXPECTED_DEGREES, distribution.sampleSpace);
    for (int i = 0; i < EXPECTED_DEGREE_VALUES.length; ++i) {
        Assert.assertEquals(EXPECTED_DEGREE_VALUES[i], distribution.values[i], DELTA);
    }
    Assert.assertEquals(EXPECTED_DEGREE_VALUES.length, distribution.values.length);
}
 
Example 17
Project: Lemming   File: OutDegreeDistributionMetricTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    Model model = ModelFactory.createDefaultModel();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(GRAPH_FILE);
    model.read(is, null, "N3");
    IOUtils.closeQuietly(is);

    GraphCreator creator = new GraphCreator();
    ColouredGraph graph = creator.processModel(model);

    OutDegreeDistributionMetric metric = new OutDegreeDistributionMetric();
    IntDistribution distribution = metric.apply(graph);

    Assert.assertArrayEquals(EXPECTED_DEGREES, distribution.sampleSpace);
    for (int i = 0; i < EXPECTED_DEGREE_VALUES.length; ++i) {
        Assert.assertEquals(EXPECTED_DEGREE_VALUES[i], distribution.values[i], DELTA);
    }
    Assert.assertEquals(EXPECTED_DEGREE_VALUES.length, distribution.values.length);
}
 
Example 18
Project: Lemming   File: EdgeColourDistributionMetricTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    Model model = ModelFactory.createDefaultModel();
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(GRAPH_FILE);
    model.read(is, null, "N3");
    IOUtils.closeQuietly(is);

    GraphCreator creator = new GraphCreator();
    ColouredGraph graph = creator.processModel(model);

    EdgeColourDistributionMetric metric = new EdgeColourDistributionMetric();
    ObjectDistribution<BitSet> distribution = metric.apply(graph);

    ObjectDoubleOpenHashMap<BitSet> expectedCounts = new ObjectDoubleOpenHashMap<BitSet>();
    ColourPalette palette = graph.getEdgePalette();
    for (int i = 0; i < EXPECTED_PROPERTY_URIS.length; ++i) {
        expectedCounts.put(palette.getColour(EXPECTED_PROPERTY_URIS[i]), EXPECTED_PROPERTY_COUNTS[i]);
    }

    for (int i = 0; i < distribution.sampleSpace.length; ++i) {
        Assert.assertTrue(expectedCounts.containsKey(distribution.sampleSpace[i]));
        Assert.assertEquals(expectedCounts.get(distribution.sampleSpace[i]), distribution.values[i]);
    }
    Assert.assertEquals(expectedCounts.size(), distribution.sampleSpace.length);
}
 
Example 19
Project: modeller   File: ResourceList.java   Source Code and License 6 votes vote down vote up
/**
 * getResourceList.
 *
 * @return resourceList
 */
public ArrayList<String> getResourceList() {
    try {
        final String resource =
                ModellerClient.doGetContainerResources(this.resourceContainerURI);
        final Model model = ModelFactory.createDefaultModel();
        model.read(
                new ByteArrayInputStream(resource != null ? resource.getBytes() : new byte[0]),
                null, "TTL");
        final ArrayList<String> resourceList = getChilden(model);
        resourceList.sort(String.CASE_INSENSITIVE_ORDER);
        return resourceList;
    } catch (final ModellerClientFailedException e) {
        System.out.println(getMessage(e));
    }
    return null;
}
 
Example 20
Project: cwlviewer   File: CWLServiceTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    File packedWorkflowRdf = new File("src/test/resources/cwl/make_to_cwl/dna.ttl");
    Model workflowModel = ModelFactory.createDefaultModel();
    workflowModel.read(new ByteArrayInputStream(readFileToString(packedWorkflowRdf).getBytes()), null, "TURTLE");
    Dataset workflowDataset = DatasetFactory.create();
    workflowDataset.addNamedModel("https://w3id.org/cwl/view/git/549c973ccc01781595ce562dea4cedc6c9540fe0/workflows/make-to-cwl/dna.cwl#main", workflowModel);

    Answer queryRdf = new Answer<ResultSet>() {
        @Override
        public ResultSet answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Query query = QueryFactory.create(args[0].toString());
            try (QueryExecution qexec = QueryExecutionFactory.create(query, workflowDataset)) {
                return ResultSetFactory.copyResults(qexec.execSelect());
            }
        }
    };

    this.rdfService = Mockito.spy(new RDFService("http://localhost:3030/cwlviewer/"));
    Mockito.doAnswer(queryRdf).when(rdfService).runQuery(anyObject());
    Mockito.doReturn(true).when(rdfService).graphExists(anyString());
}
 
Example 21
Project: platform   File: GitlabControllerImpl.java   Source Code and License 6 votes vote down vote up
protected String getCheckedModelString(String modelString, String modelType, String projectName) {
    try {
        Model model = ModelFactory.createDefaultModel();
        model.read(new StringReader(modelString), null, "TTL");
        return modelString;
    } catch (Exception e) {
        String parsingError = "Couldn't parse " + modelType + " model from " + projectName
                + ". It won't be available. " + e.getMessage();
        if (parsingErrors.contains(parsingError)) {
            LOGGER.info(parsingError + " (Error already reported before)");
        } else {
            LOGGER.info("Couldn't parse " + modelType + " model from " + projectName + ". It won't be available.",
                    e);
            sortedParsingErrors.addLast(parsingError);
            parsingErrors.add(parsingError);
            // If the cached errors become to long, remove the oldest
            if (sortedParsingErrors.size() > MAX_PARSING_ERRORS) {
                parsingErrors.remove(sortedParsingErrors.pop());
            }
        }
    }
    return null;
}
 
Example 22
Project: fcrepo-import-export   File: RoundtripIT.java   Source Code and License 6 votes vote down vote up
@Test
public void testRoundtripNested() throws Exception {
    final URI containerURI = URI.create(serverAddress + UUID.randomUUID());

    // create a new nested containers
    assertEquals(SC_CREATED, clientBuilder.build().put(containerURI).perform().getStatusCode());
    assertEquals(SC_CREATED, clientBuilder.build().post(containerURI).slug("b")
            .body(new ByteArrayInputStream("content".getBytes("UTF-8")), "text/plain").perform().getStatusCode());
    assertEquals(SC_CREATED, clientBuilder.build().post(containerURI).slug("a").perform().getStatusCode());

    final Model origModel = ModelFactory.createDefaultModel();
    origModel.read(
            clientBuilder.build().get(containerURI).accept("application/n-triples").perform().getBody(), "", "N3");

    roundtrip(containerURI, true);

    final Model roundtrippedModel = ModelFactory.createDefaultModel();
    roundtrippedModel.read(
            clientBuilder.build().get(containerURI).accept("application/n-triples").perform().getBody(), "", "N3");

    assertIdenticalGraphs(origModel, roundtrippedModel);
}
 
Example 23
Project: BENGAL   File: DBpediaGenderDictionary.java   Source Code and License 6 votes vote down vote up
public DBpediaGenderDictionary() {
	Model model = ModelFactory.createDefaultModel();

	Literal maleLit = model.createLiteral(VALUE_MALE, "en");
	Literal femaleLit = model.createLiteral(VALUE_FEMALE, "en");

	RDFDataMgr.read(model, getClass().getClassLoader().getResourceAsStream(GENDER_FILE_LOCATION), Lang.TURTLE);
	StmtIterator iter = model.listStatements(null, model.createProperty(GENDER_PROPERTY), (RDFNode) null);
	while (iter.hasNext()) {
		Statement st = iter.next();
		Literal lit = st.getObject().asLiteral();
		if (lit.equals(maleLit)) {
			male.add(st.getSubject().getURI());
		} else if (lit.equals(femaleLit)) {
			female.add(st.getSubject().getURI());
		}
	}
}
 
Example 24
Project: openregister-java   File: RecordTurtleWriter.java   Source Code and License 6 votes vote down vote up
@Override
protected Model rdfModelFor(Map.Entry<Entry, List<ItemView>> record) {
    Entry entry = record.getKey();
    ItemView itemView = record.getValue().get(0);

    Model recordModel = ModelFactory.createDefaultModel();
    Model entryModel = new EntryTurtleWriter(registerNameProvider, registerResolver).rdfModelFor(entry, false);
    Model itemModel = new ItemTurtleWriter(registerNameProvider, registerResolver).rdfModelFor(itemView);

    Resource recordResource = recordModel.createResource(recordUri(entry.getKey()).toString());
    addPropertiesToResource(recordResource, entryModel.getResource(entryUri(Integer.toString(entry.getEntryNumber())).toString()));
    addPropertiesToResource(recordResource, itemModel.getResource(itemUri(itemView.getItemHash().encode()).toString()));

    Map<String, String> prefixes = entryModel.getNsPrefixMap();
    prefixes.putAll(itemModel.getNsPrefixMap());

    recordModel.setNsPrefixes(prefixes);

    return recordModel;
}
 
Example 25
Project: openregister-java   File: EntryTurtleWriter.java   Source Code and License 6 votes vote down vote up
protected Model rdfModelFor(Entry entry, boolean includeKey) {
    Model model = ModelFactory.createDefaultModel();
    Property entryNumberProperty = model.createProperty(SPEC_PREFIX + "entry-number-field");
    Property entryTimestampProperty = model.createProperty(SPEC_PREFIX + "entry-timestamp-field");
    Property itemProperty = model.createProperty(SPEC_PREFIX + "item-resource");

    String entryNumber = Integer.toString(entry.getEntryNumber());
    Resource resource = model.createResource(entryUri(entryNumber).toString())
            .addProperty(entryNumberProperty, entryNumber)
            .addProperty(entryTimestampProperty, entry.getTimestampAsISOFormat())
            .addProperty(itemProperty, model.createResource(itemUri(entry.getItemHashes().get(0).encode()).toString()));

    if (includeKey) {
        Property keyProperty = model.createProperty(SPEC_PREFIX + "key-field");
        resource.addProperty(keyProperty, entry.getKey());
    }

    model.setNsPrefix("register-metadata", SPEC_PREFIX);
    return model;
}
 
Example 26
Project: semantic-ci   File: LocalGraph.java   Source Code and License 6 votes vote down vote up
public LocalGraph(String filename) {

		// create an empty model
		model = ModelFactory.createDefaultModel();

		// use the FileManager to find the input file
		InputStream in = FileManager.get().open(filename);
		if (in == null) {
			throw new IllegalArgumentException("File: " + filename + " not found");
		}

		// read the RDF N-Triple file
		model.read(in, null, "N-TRIPLE");

		namespacesToNames = new HashMap<String, Set<String>>();
	}
 
Example 27
Project: fcrepo-api-x   File: JenaOntologyServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void transitiveImportsTest() throws Exception {
    final OntModel transitive = toTest.getOntology(URI.create(ONT5)).model;

    // 5 includes 4, 4 includes 1
    final Model expectedTriples = ModelFactory.createDefaultModel();
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT1))
            .representation(), null, "N-TRIPLES"));
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT4))
            .representation(), null, "N-TRIPLES"));
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT5))
            .representation(), null, "N-TRIPLES"));

    expectedTriples.removeAll(null, expectedTriples.getProperty(OWL_IMPORTS), null);

    assertTrue(transitive.containsAll(expectedTriples));
}
 
Example 28
Project: fcrepo-api-x   File: JenaOntologyServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void loadOntologyTest() {
    final WebResource resource = ONTOLOGY_REGISTRY.get(URI.create(ONT5));

    final OntModel transitive = toTest.parseOntology(resource).model;

    // 5 includes 4, 4 includes 1
    final Model expectedTriples = ModelFactory.createDefaultModel();
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT1))
            .representation(), null, "N-TRIPLES"));
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT4))
            .representation(), null, "N-TRIPLES"));
    expectedTriples.add(ModelFactory.createDefaultModel().read(ONTOLOGY_REGISTRY.get(URI.create(ONT5))
            .representation(), null, "N-TRIPLES"));

    expectedTriples.removeAll(null, expectedTriples.getProperty(OWL_IMPORTS), null);

    assertTrue(transitive.containsAll(expectedTriples));

}
 
Example 29
Project: fcrepo-api-x   File: ServiceIndexingRoutesTest.java   Source Code and License 6 votes vote down vote up
@Before
public void init() throws Exception {

    // For some reason, this is necessary after upgrating to Camel 2.19.
    // Otherwise, it looks like the context doesn't start(!??)
    context.start();
    dataset = DatasetFactory.create();

    // Create two named graphs with triples. Verify that they're non-empty from the start.
    final Model a = ModelFactory.createDefaultModel();
    final Model b = ModelFactory.createDefaultModel();

    a.add(a.getResource("test:something"), a.getProperty("test:prop"), a.getResource("test:whatever"));
    b.add(b.getResource("test:somethingElse"), b.getProperty("test:prop"), b.getResource("test:whatever"));

    dataset.addNamedModel("test:unaffected", a);
    dataset.addNamedModel(SERVICE_DOC_URI, b);
}
 
Example 30
Project: DramaNLP   File: MetaDataExport.java   Source Code and License 6 votes vote down vote up
@Override
public void initialize(final UimaContext context) throws ResourceInitializationException {
	super.initialize(context);

	model = ModelFactory.createOntologyModel();
	InputStream in = null;
	try {
		in = new FileInputStream(outputFileName);
		model.read(in, "http://github.com/quadrama/metadata/ontology.owl");
		in.close();
	} catch (IOException e) {
		Ontology o = model.createOntology("http://github.com/quadrama/metadata/ontology.owl");
		o.setRDFType(OWL2.Ontology);
		model.setNsPrefix("gndo", "http://d-nb.info/standards/elementset/gnd#");
		model.setNsPrefix("gnd", "http://d-nb.info/gnd/");
		model.setNsPrefix("dc", "http://purl.org/dc/elements/1.1/");
		model.setNsPrefix("oa", "http://www.w3.org/ns/oa#");
		model.setNsPrefix("dbo", "http://dbpedia.org/ontology/");
		model.setNsPrefix("qd", QD.NS);
	} finally {
		IOUtils.closeQuietly(in);
	}

}
 
Example 31
Project: eskg   File: PODAACOntologyMapper.java   Source Code and License 6 votes vote down vote up
@Override
public void map(List<DIF> pojoList, Properties props) {
  // create the base model
  OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
  ontModel.setNsPrefix("dif_v9.8.2", MUDROD_GCMD_DIF_9_8_2);
  ontModel.setNsPrefix("geo", "http://www.opengis.net/ont/geosparql#");
  ontModel.read(SWEET_REPR_DATA_PRODUCT, null, "TURTLE");

  // get the https://sweetontology.net/reprDataProduct/Dataset class reference
  Resource dataset = ontModel.getResource(SWEET_REPR_DATA_PRODUCT_NS + "Dataset");
  // create the https://sweetontology.net/reprDataProduct/PODAACDataset class
  // reference
  OntClass podaacDataset = ontModel.createClass(PODAAC_DATASET + "PODAACDataset");
  // make PODAACDataset a subclass of Dataset
  podaacDataset.addSuperClass(dataset);
  // create an individual for each DIF POJO
  for (DIF dif : pojoList) {
    Individual gcmdDif = podaacDataset.createIndividual(PODAAC_DATASET + dif.getEntryID());
    buildIndividual(ontModel, dif, gcmdDif);
  }
  writeOntologyModel(ontModel, props);
}
 
Example 32
Project: sparql-generate   File: TestBase.java   Source Code and License 6 votes vote down vote up
public TestBase(Logger log, File exampleDir, String name) {
    this.log = log;
    this.exampleDir = exampleDir;

    log.info("constructing with " + exampleDir);

    SPARQLGenerate.init();
            
    // read location-mapping
    Model conf = ModelFactory.createDefaultModel();
    conf.add(RDFDataMgr.loadModel(new File(exampleDir, "queryset/configuration.ttl").toString(), Lang.TTL));
    conf.add(RDFDataMgr.loadModel(new File(exampleDir, "documentset/configuration.ttl").toString(), Lang.TTL));

    // initialize stream manager
    SPARQLGenerateStreamManager sm = SPARQLGenerateStreamManager.makeStreamManager(new LocatorFileAccept(exampleDir.toURI().getPath()));
    sm.setLocationMapper(conf);
    SPARQLGenerate.setStreamManager(sm);
}
 
Example 33
Project: ASPG   File: viz.java   Source Code and License 6 votes vote down vote up
private static Model readRDF(String s) {
        Model model = ModelFactory.createDefaultModel();

        if (isPath(s)) {
//            System.out.println("Parsing file " + s);
            model.read(s);
        } else {
            try {
//                System.out.println("Parsing RDF string " + s);
                RDFDataMgr.read(model, new ByteArrayInputStream(s.getBytes("UTF-8")), Lang.TTL);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return model;
    }
 
Example 34
Project: cLODg   File: AnalyseNames.java   Source Code and License 6 votes vote down vote up
public Model loadGraph(String path) {
	// load model from static dump (can find an example in
	// /cLODg/src/main/resources/data/all-names.rdf)

	Model m = ModelFactory.createDefaultModel();
	InputStream is = null;
	String syntax = null;
	if (path == null) {
		is = getClass().getClassLoader().getResourceAsStream(GRAPH_NAME);
		syntax = "RDF/XML";
	} else {
		try {
			is = new FileInputStream(new File(path));
			syntax = FileUtils.guessLang(path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	if (is != null)
		m.read(is, null, syntax);

	return m;
}
 
Example 35
Project: semiot-platform   File: Observations.java   Source Code and License 6 votes vote down vote up
private void resultSetToRfd(final AsyncResponse response,
    Observable<ResultSet> rs) {
  rs.map((result) -> {
    Model observations = ModelFactory.createDefaultModel();
    result.forEach((row) -> {
      Observation observation = new Observation(
          row.getString("system_id"), row.getString("sensor_id"),
          row.getTimestamp("event_time").toInstant().toString(),
          row.getString("property"),
          row.getString("feature_of_interest"),
          row.getString("value"));

      observations.add(observation.toRDF());
    });

    return observations;
  }).subscribe(responseModelOrError(response));
}
 
Example 36
Project: incubator-taverna-plugin-component   File: AnnotationUtils.java   Source Code and License 6 votes vote down vote up
public Model getModel(Child<WorkflowBundle> subject) throws IOException {
	WorkflowBundle bundle = subject.getParent();
	Model m = cache.get(subject);
	if (m == null) {
		m = ModelFactory.createDefaultModel();
		long initialSize = m.size();
		for (Annotation a : tools.annotationsFor(subject,
				subject.getParent()))
			if (!a.getBody().isAbsolute())
				readParse(m, bundle, a.getBody().getPath());
		if (m.size() == initialSize)
			for (ResourceEntry o : bundle.getResources()
					.listResources("annotation").values())
				readParse(m, bundle, o.getPath());
		cache.put(subject, m);
	}
	return m;
}
 
Example 37
Project: incubator-taverna-language   File: TestRoEvoSerializer.java   Source Code and License 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_o.wasRevisionOf).getResource();
	Resource oldest = older.getProperty(Prov_o.wasRevisionOf).getResource();
	assertNull(oldest.getProperty(Prov_o.wasRevisionOf));
	
}
 
Example 38
Project: semiot-platform   File: RDFUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void listResourcesWithProperty() {
  Model model = ModelFactory.createDefaultModel();
  RDFDataMgr.read(model, this.getClass().getResourceAsStream(PATH_PREFIX + "system.ttl"),
      RDFLanguages.TURTLE);

  List<Resource> actual = RDFUtils.listResourcesWithProperty(
      model, RDF.type, SSN.System, Proto.Individual);

  List<Resource> expected = new ArrayList<>();
  expected.add(ResourceFactory.createResource("http://localhost/systems/3503522021"));

  assertEquals(expected, actual);

  assertEquals(0, RDFUtils.listResourcesWithProperty(
      model, RDF.type, OWL.Class).size());
}
 
Example 39
Project: semiot-platform   File: CommandResult.java   Source Code and License 6 votes vote down vote up
public Model toRDFAsModel(Map<String, Object> configuration) {
  logger.debug(TEMPLATE_COMMANDRESULT.resolveToString(properties, configuration));
  Model result = ModelFactory.createDefaultModel().read(
      TEMPLATE_COMMANDRESULT.resolveToReader(properties, configuration),
      null,
      TEMPLATE_COMMANDRESULT.getRDFLanguage());
  Model command = ModelFactory.createDefaultModel().read(
      commandTemplate.resolveToReader(properties, configuration),
      null,
      commandTemplate.getRDFLanguage());
  result.add(command);

  Resource resourceCommandResult = result.listResourcesWithProperty(
      RDF.type, SEMIOT.CommandResult).next();
  Resource resourceCommand = result.listResourcesWithProperty(SEMIOT.forProcess).next();

  result.add(resourceCommandResult, SEMIOT.isResultOf, resourceCommand);

  return result;
}
 
Example 40
Project: Gloze   File: GlozeURL.java   Source Code and License 6 votes vote down vote up
private void rdf_to_xml( URL source, String name) throws Exception {
	Model m = ModelFactory.createDefaultModel();
	
	// derive target
	File t = this.target!=null?new File(this.target):null, target = t;
	if (t!=null && (t.isDirectory() || t.getName().indexOf('.')<0)) {
		if (!t.exists()) t.mkdirs();
		target = new File(t, XMLBean.changeSuffix(source.getFile(), "xml"));
	}
	
	// derive base
	URI base = null;
	// base is (in order of preference) user assigned, derived from the target, or the source
	if (this.base!=null && this.base.endsWith("/") && name!=null) base = new URI(this.base + name);
	else if (this.base!=null) base = new URI(this.base);
	else if (target!=null) base = target.toURI();
	else base = source.toURI();
	
	rdf_to_xml(source, target, base, m);
}