本文整理汇总了Java中org.apache.jena.rdf.model.Model类的典型用法代码示例。如果您正苦于以下问题:Java Model类的具体用法?Java Model怎么用?Java Model使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Model类属于org.apache.jena.rdf.model包,在下文中一共展示了Model类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Wrong arguments");
showUsage();
}
System.out.println("Model file : " + args[0]);
System.out.println("Model URI : " + args[1]);
System.out.println("Model tdb dir: " + args[2]);
Dataset dataset = TDBFactory.createDataset(args[2]);
try {
Model model = dataset.getNamedModel(args[1]);
TDBLoader.loadModel(model, args[0]);
} finally {
dataset.close();
}
}
示例2: createObject
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
/**
* 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();
}
示例3: getCount
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
public static int getCount(String q, Model m) {
Query query = QueryFactory.create(q);
QueryExecution queryExec = QueryExecutionFactory.create(query, m);
ResultSet rs = queryExec.execSelect();
String vName = "";
for (String v: rs.getResultVars()) {
if (v.contains("count")) {
vName = v;
break;
}
}
while (rs.hasNext()) {
QuerySolution s = rs.nextSolution();
Literal c = s.getLiteral(vName);
queryExec.close();
return c.getInt();
}
queryExec.close();
return 0;
}
示例4: toTriple
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
/**
* This method converts a string (in n-triples format) into a Jena triple
*
* @param string containing single n-triples triple
* @return Triple
*/
public static Triple toTriple(final String string) {
// Create Jena model
Model inputModel = createDefaultModel();
try {
// Load model with arg string (expecting n-triples)
inputModel = inputModel.read(new StringInputStream(string), null, strLangNTriples);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Since there is only one statement, get it
final Statement stmt = inputModel.listStatements().nextStatement();
// Return the Jena triple which the statement represents
return stmt.asTriple();
}
示例5: createModel
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
@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;
}
示例6: main
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
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();
}
示例7: loadOEModelToTdb
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
/**
* Fetch a model from Ontology Editor, load and return as TDB-backed Jena model.
*
* @param endpoint
* @param tDbDirectoryPath
* @return
* @throws OEConnectionException
* @throws IOException
*/
public static Model loadOEModelToTdb(OEModelEndpoint endpoint, String tDbDirectoryPath) throws IOException, OEConnectionException {
Preconditions.checkNotNull(endpoint);
Preconditions.checkArgument(!Strings.isNullOrEmpty(tDbDirectoryPath));
if (logger.isDebugEnabled()) {
logger.debug("OEModelEndpoint: {}", endpoint);
logger.debug("TDB Dir path : {}", tDbDirectoryPath);
}
String modelAsTTL = endpoint.fetchData();
Dataset dataset = TDBFactory.createDataset(tDbDirectoryPath);
Model model = dataset.getNamedModel(endpoint.modelIri);
model.read(new ByteArrayInputStream(modelAsTTL.getBytes()), "TTL");
return model;
}
示例8: testConceptGroupedDiff
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
@Test
public void testConceptGroupedDiff() throws IOException {
Model model2 = hydrateAndModifySecondModel();
List<Property> chaseProperties = Lists.newArrayList();
chaseProperties.add(SKOSXL.prefLabel);
chaseProperties.add(SKOSXL.altLabel);
Collection<RDFSubjectDifference> diffs = RDFDifferenceBuilder.buildSubjectBatches(
RDFDifferenceBuilder.buildDifference(model, model2), chaseProperties);
for (RDFSubjectDifference subjDiff : diffs) {
String sparql = DiffToSparqlInsertUpdateBuilder.buildSparqlInsertUpdate(subjDiff);
System.out.println("Batch for subject: " + subjDiff.subject.toString());
System.out.println(sparql);
}
}
开发者ID:Smartlogic-Semaphore-Limited,项目名称:Java-APIs,代码行数:18,代码来源:DiffToSparqlInsertUpdateBuilderTests.java
示例9: testBsbmEmbedded
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
@Test
public void testBsbmEmbedded() {
SerializerModel serializer = new SerializerModel();
Generator.init(new String[] {});
Generator.setSerializer(serializer);
Generator.run();
TestDriverParams testDriverParams = Generator.getTestDriverParams();
Model model = serializer.getModel();
QueryExecutionFactory qef = FluentQueryExecutionFactory.from(model).create();
TestDriver testDriver = new TestDriver();
testDriver.processProgramParameters(new String[]{"http://example.org/foobar/sparql", "-w", "0", "-runs", "1"});
testDriver.setParameterPool(new LocalSPARQLParameterPool(testDriverParams, testDriver.getSeed()));
testDriver.setServer(new SPARQLConnection2(qef));
testDriver.init();
testDriver.run();
}
示例10: fillTrie
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
@Override
protected void fillTrie(Logger logger, Trie<Resource> trie, Corpus corpus) throws IOException, ModuleException {
Model model = createModel(logger);
Property typeProp = model.getProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
Property[] labelPropertyProps = getProperties(model, labelURIs);
int nEntries = 0;
for (String resourceTypeURI : resourceTypeURIs) {
Property resourceType = model.getProperty(model.expandPrefix(resourceTypeURI));
for (Resource res : Iterators.loop(model.listSubjectsWithProperty(typeProp , resourceType))) {
if (res.isAnon()) {
continue;
}
for (Property prop : labelPropertyProps) {
for (RDFNode node : Iterators.loop(model.listObjectsOfProperty(res, prop))) {
String label = getNodeValue(node);
trie.addEntry(label, res);
nEntries++;
}
}
}
}
logger.info("Entries: " + nEntries);
}
示例11: createModel
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
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;
}
示例12: get
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
@Override
public RESTResource get(URI uri, Map<String, String> parameters) throws RESTException {
RESTResource resource = new RESTResource(uri.toString(),this);
Dataset dataset = ThingDirectory.get().dataset;
dataset.begin(ReadWrite.READ);
try {
Model result = dataset.getNamedModel(uri.toString());
if (!result.isEmpty()) {
resource.contentType = "text/turtle";
ByteArrayOutputStream out = new ByteArrayOutputStream();
result.write(out, "Turtle");
resource.content = out.toString();
} else {
throw new RESTException();
}
} finally {
dataset.end();
}
return resource;
}
示例13: getLabelFromLinkedData
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
/**
* Dereference the IRI and look for label property value.
* @param iri the IRI
* @return the label if exist, otherwise <code>null</code>
*/
private String getLabelFromLinkedData(String iri){
logger.debug("Get label for " + iri + " from Linked Data...");
try {
// 1. get triples for the IRI by sending a Linked Data request
Model model = uriDereferencer.dereference(iri);
// 2. check if we find a label in the triples
for (String labelProperty : labelProperties) {
for(Statement st : model.listStatements(model.getResource(iri), model.getProperty(labelProperty), (RDFNode)null).toList()){
Literal literal = st.getObject().asLiteral();
// language check
String language = literal.getLanguage();
if(language != null && language.equals(this.language)){
return literal.getLexicalForm();
}
}
}
} catch (DereferencingFailedException e) {
logger.error(e.getMessage(), e);
}
return null;
}
示例14: write
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
private static void write(final RdfStream rdfStream,
final OutputStream output,
final Lang dataFormat,
final MediaType dataMediaType) throws IOException {
final RDFFormat format = defaultSerialization(dataFormat);
// For formats that can be block-streamed (n-triples, turtle)
if (format != null) {
LOGGER.debug("Stream-based serialization of {}", dataFormat.toString());
final StreamRDF stream = getWriterStream(output, format);
stream.start();
rdfStream.forEach(stream::triple);
stream.finish();
// For formats that require analysis of the entire model and cannot be streamed directly (rdfxml, n3)
} else {
LOGGER.debug("Non-stream serialization of {}", dataFormat.toString());
final Model model = rdfStream.collect(toModel());
// use block output streaming for RDFXML
if (RDFXML.equals(dataFormat)) {
RDFDataMgr.write(output, model.getGraph(), RDFXML_PLAIN);
} else if (JSONLD.equals(dataFormat)) {
final RDFFormat jsonldFormat = getFormatFromMediaType(dataMediaType);
RDFDataMgr.write(output, model.getGraph(), jsonldFormat);
} else {
RDFDataMgr.write(output, model.getGraph(), dataFormat);
}
}
}
示例15: toModel
import org.apache.jena.rdf.model.Model; //导入依赖的package包/类
/**
* @return a Collector for use with aggregating an RdfStream into a Model.
*/
public static Collector<Triple, ?, Model> toModel() {
return Collector.of(ModelFactory::createDefaultModel,
(m, t) -> m.add(m.asStatement(t)),
(left, right) -> {
left.add(right);
return left;
},
Collector.Characteristics.UNORDERED);
}