Java Code Examples for org.apache.jena.rdf.model.Literal
The following examples show how to use
org.apache.jena.rdf.model.Literal.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Stargraph Author: Lambda-3 File: FactIterator.java License: MIT License | 6 votes |
@Override protected Indexable buildNext(Statement statement) { InstanceEntity instanceEntity = createInstance(applyNS(statement.getSubject().getURI())); PropertyEntity propertyEntity = createProperty(applyNS(statement.getPredicate().getURI())); LabeledEntity labeledEntity; if (!statement.getObject().isLiteral()) { //Is created as an instance but can be changed to a class down on the workflow in EntityClassifierProcessor. labeledEntity = createInstance(applyNS(statement.getObject().asResource().getURI())); } else { Literal literal = statement.getObject().asLiteral(); String dataType = literal.getDatatypeURI(); String langTag = literal.getLanguage(); String value = literal.getLexicalForm(); labeledEntity = new ValueEntity(value, dataType, langTag); } return new Indexable(new Fact(kbId, instanceEntity, propertyEntity, labeledEntity), kbId); }
Example #2
Source Project: Heracles Author: KSchouten File: ReasoningOntology.java License: GNU General Public License v3.0 | 6 votes |
public HashMap<String, String> lexToURI(){ StmtIterator iter = ontology.listStatements(new SimpleSelector(null, ontology.getProperty(NS+"#lex"),(Literal)null)); HashMap<String, String> ontoConcepts=new HashMap<String,String>(); while (iter.hasNext()) { Statement stmt = iter.nextStatement(); Resource subject = stmt.getSubject(); // get the subject RDFNode lex = stmt.getObject(); StmtIterator iter2 = ontology.listStatements(new SimpleSelector( subject, ontology.getProperty("http://www.w3.org/2000/01/rdf-schema#subClassOf"), ontology.getResource(this.URI_Mention))); if (iter2.hasNext()){ ontoConcepts.put(lex.toString(), subject.getURI()); } else { System.out.println("No subclass of Mention: "+subject.toString()); } // } return ontoConcepts; }
Example #3
Source Project: SDA Author: iotoasis File: OneM2MContentInstanceMapper.java License: BSD 2-Clause "Simplified" License | 6 votes |
public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); // return "\"" + Double.valueOf(con) + "\"^^xsd:double"; } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); // return "\"" + Float.valueOf(con) + "\"^^xsd:float"; } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); // return "\"" + con + "\"^^xsd:string"; } } }
Example #4
Source Project: NLIWOD Author: dice-group File: SPARQL.java License: GNU Affero General Public License v3.0 | 6 votes |
/** * For use with {@link #sparql(String)} Extracts answer strings. Can be directly set as golden answers in an IQuestion. * * @param answers * @return */ public static Set<String> extractAnswerStrings(final Set<RDFNode> answers) { Set<String> set = Sets.newHashSet(); for (RDFNode answ : answers) { if (answ.isResource()) { set.add(answ.asResource().getURI()); } else if (answ.isLiteral()) { Literal l = (Literal) answ; try { set.add(l.getString()); } catch (Exception e) { e.printStackTrace(); set.add(l.getLexicalForm()); } } else { set.add(answ.toString()); } } return set; }
Example #5
Source Project: SDA Author: iotoasis File: OneM2MContentInstanceMapper.java License: BSD 2-Clause "Simplified" License | 6 votes |
public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); // return "\"" + Double.valueOf(con) + "\"^^xsd:double"; } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); // return "\"" + Float.valueOf(con) + "\"^^xsd:float"; } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); // return "\"" + con + "\"^^xsd:string"; } } }
Example #6
Source Project: Processor Author: AtomGraph File: Skolemizer.java License: Apache License 2.0 | 6 votes |
protected Map<String, String> getNameValueMap(Resource resource, UriTemplateParser parser) { if (resource == null) throw new IllegalArgumentException("Resource cannot be null"); if (parser == null) throw new IllegalArgumentException("UriTemplateParser cannot be null"); Map<String, String> nameValueMap = new HashMap<>(); List<String> names = parser.getNames(); for (String name : names) { Literal literal = getLiteral(resource, name); if (literal != null) nameValueMap.put(name, literal.getString()); } return nameValueMap; }
Example #7
Source Project: Processor Author: AtomGraph File: SkolemizerTest.java License: Apache License 2.0 | 6 votes |
/** * Test of getNameValueMap method, of class Skolemizer. */ @Test public void testGetNameValueMap() { UriTemplateParser parser = new UriTemplateParser("{name}/{title}|{smth}|{primaryTopic.title}"); Model model = ModelFactory.createDefaultModel(); Literal secondTitle = model.createLiteral("Second"); Literal firstTitle = model.createLiteral("First"); Resource second = model.createResource(). addLiteral(DCTerms.title, secondTitle); Resource first = model.createResource(). addLiteral(DCTerms.title, firstTitle). addProperty(FOAF.primaryTopic, second); Map<String, String> expected = new HashMap<>(); expected.put("title", firstTitle.getString()); expected.put("primaryTopic.title", secondTitle.getString()); Map<String, String> result = skolemizer.getNameValueMap(first, parser); assertEquals(expected, result); }
Example #8
Source Project: Processor Author: AtomGraph File: SkolemizerTest.java License: Apache License 2.0 | 6 votes |
/** * Test of getLiteral method, of class Skolemizer. */ @Test public void testGetLiteral() { Model model = ModelFactory.createDefaultModel(); Literal secondTitle = model.createLiteral("Second"); Literal firstTitle = model.createLiteral("First"); Resource second = model.createResource(). addLiteral(DCTerms.title, secondTitle); Resource first = model.createResource(). addLiteral(DCTerms.title, firstTitle). addProperty(FOAF.primaryTopic, second); Literal firstResult = skolemizer.getLiteral(first, "title"); assertEquals(firstTitle, firstResult); Literal secondResult = skolemizer.getLiteral(first, "primaryTopic.title"); assertEquals(secondTitle, secondResult); Literal resultFail1 = skolemizer.getLiteral(first, "primaryTopic"); assertNull(resultFail1); // primaryTopic is a resource, not a literal Literal resultFail2 = skolemizer.getLiteral(first, "whatever"); assertNull(resultFail2); // no such property }
Example #9
Source Project: ontopia Author: ontopia File: RDFIntroSpector.java License: Apache License 2.0 | 6 votes |
private static void parseN3(GrabMappingsHandler handler, String infileurl) { Model model = ModelFactory.createDefaultModel(); model.read(infileurl, "N3"); AResourceImpl sub = new AResourceImpl(); AResourceImpl pred = new AResourceImpl(); AResourceImpl objres = new AResourceImpl(); ALiteralImpl objlit = new ALiteralImpl(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement stmt = it.nextStatement(); RDFNode object = stmt.getObject(); sub.setResource(stmt.getSubject()); pred.setResource(stmt.getPredicate()); if (object instanceof Literal) { objlit.setLiteral((Literal) object); handler.statement(sub, pred, objlit); } else { objres.setResource((Resource) object); handler.statement(sub, pred, objres); } } }
Example #10
Source Project: Server.Java Author: LinkedDataFragments File: TriplePatternFragmentBase.java License: MIT License | 6 votes |
@Override public void addMetadata( final Model model ) { super.addMetadata( model ); final Resource fragmentId = model.createResource( fragmentURL ); final Literal totalTyped = model.createTypedLiteral( totalSize, XSDDatatype.XSDinteger ); final Literal limitTyped = model.createTypedLiteral( getMaxPageSize(), XSDDatatype.XSDinteger ); fragmentId.addLiteral( CommonResources.VOID_TRIPLES, totalTyped ); fragmentId.addLiteral( CommonResources.HYDRA_TOTALITEMS, totalTyped ); fragmentId.addLiteral( CommonResources.HYDRA_ITEMSPERPAGE, limitTyped ); }
Example #11
Source Project: Server.Java Author: LinkedDataFragments File: LinkedDataFragmentBase.java License: MIT License | 6 votes |
/** * Adds some basic metadata to the given RDF model. * This method may be overridden in subclasses. * @param model */ public void addMetadata( final Model model ) { final Resource datasetId = model.createResource( getDatasetURI() ); final Resource fragmentId = model.createResource( fragmentURL ); datasetId.addProperty( CommonResources.RDF_TYPE, CommonResources.VOID_DATASET ); datasetId.addProperty( CommonResources.RDF_TYPE, CommonResources.HYDRA_COLLECTION ); datasetId.addProperty( CommonResources.VOID_SUBSET, fragmentId ); Literal itemsPerPage = model.createTypedLiteral(this.getMaxPageSize()); datasetId.addProperty( CommonResources.HYDRA_ITEMSPERPAGE, itemsPerPage); fragmentId.addProperty( CommonResources.RDF_TYPE, CommonResources.HYDRA_COLLECTION ); fragmentId.addProperty( CommonResources.RDF_TYPE, CommonResources.HYDRA_PAGEDCOLLECTION ); }
Example #12
Source Project: quetzal Author: Quetzal-RDF File: TriplesToRuleSystem.java License: Eclipse Public License 2.0 | 6 votes |
/** * converts a {@link Node} into an {[email protected] Expr} * @param n * @return */ protected Expr toExpr(Node n) { if (n.isVariable()) { return new VariableExpr(n.getName()); } else if (n.isURI()) { try { return new ConstantExpr(new URI(n.getURI())); } catch (URISyntaxException e) { throw new RuntimeException(e); } } else if (n.isLiteral()) { Literal l = (Literal) n; return new ConstantExpr(l.getValue()); } else { throw new RuntimeException("Unsuported node type in query : "+n); } }
Example #13
Source Project: BioSolr Author: flaxsearch File: JenaOntologySearch.java License: Apache License 2.0 | 6 votes |
private Map<String, String> extractResultMap(QuerySolution qs, List<String> vars) { Map<String, String> resultMap = new HashMap<>(); for (String var : vars) { RDFNode node = qs.get(var); if (node != null) { if (node instanceof Literal) { resultMap.put(var, ((Literal)node).getLexicalForm()); } else { resultMap.put(var, node.toString()); } } } return resultMap; }
Example #14
Source Project: RDFUnit Author: AKSW File: NodeFormatter.java License: Apache License 2.0 | 6 votes |
public static String formatNode(RDFNode node) { if (node.isURIResource()) { return "<" + node.asResource().getURI().trim().replace(" ", "") + ">"; } if (node.isLiteral()){ Literal value = node.asLiteral(); String formattedValue = "\"" + value.getLexicalForm() + "\""; if (!value.getLanguage().isEmpty()) { formattedValue += "@" + value.getLanguage() ; } if (!value.getDatatypeURI().isEmpty() && !value.getDatatypeURI().endsWith("langString") && !value.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) { formattedValue += "^^<" + value.getDatatypeURI() + ">" ; } return formattedValue; } throw new IllegalArgumentException("cannot support blank nodes as targets"); }
Example #15
Source Project: Heracles Author: KSchouten File: ReasoningOntology.java License: GNU General Public License v3.0 | 5 votes |
public HashSet<String> getLexicalizedConcepts(String superclassURI, String annotationType, String lemma){ Literal literal; if (lemma == null){ literal = null; } else { literal = ontology.createLiteral(lemma); } StmtIterator iter = ontology.listStatements(new SimpleSelector(null, ontology.getProperty(annotationType),literal)); HashSet<String> ontoConcepts=new HashSet<String>(); // System.out.println(literal); while (iter.hasNext()) { Statement stmt = iter.nextStatement(); Resource subject = stmt.getSubject(); // get the subject StmtIterator iter2 = ontology.listStatements(new SimpleSelector( subject, ontology.getProperty("http://www.w3.org/2000/01/rdf-schema#subClassOf"), // ontology.getProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), ontology.getResource(superclassURI))); if (iter2.hasNext()) ontoConcepts.add(subject.getURI()); // System.out.println(subject.toString()); } return ontoConcepts; }
Example #16
Source Project: Knowage-Server Author: KnowageLabs File: SPARQLDataReader.java License: GNU Affero General Public License v3.0 | 5 votes |
private void getMetaData(RDFNode rdfNode, IFieldMetaData fieldMeta) { if (rdfNode.isLiteral()) { Literal literal = (Literal) rdfNode; Class classType = getClassType(literal); fieldMeta.setType(classType); FieldType type = getDefaultFieldType(literal); fieldMeta.setFieldType(type); } else if (rdfNode.isResource()) { fieldMeta.setType(String.class); fieldMeta.setFieldType(FieldType.ATTRIBUTE); } }
Example #17
Source Project: Knowage-Server Author: KnowageLabs File: SPARQLDataReader.java License: GNU Affero General Public License v3.0 | 5 votes |
private FieldType getDefaultFieldType(Literal literal) { if (literal.getValue().getClass().equals(Character.class) || literal.getValue().getClass().equals(Boolean.class) || literal.getValue().getClass().equals(Date.class) || literal.getValue().getClass().equals(Timestamp.class) || literal.getValue().getClass().equals(Byte.class) || literal.getValue().getClass().equals(String.class) ) { return FieldType.ATTRIBUTE; } else { return FieldType.MEASURE; } }
Example #18
Source Project: SDA Author: iotoasis File: OneM2MContentInstanceMapper.java License: BSD 2-Clause "Simplified" License | 5 votes |
/** * typed content type 가져오기 * @param con * @return Literal */ public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); } } }
Example #19
Source Project: SDA Author: iotoasis File: OneM2MContentInstanceMapper.java License: BSD 2-Clause "Simplified" License | 5 votes |
/** * typed content type 가져오기 * @param con * @return Literal */ public Literal getTypedContent(String con) { try { return ResourceFactory.createTypedLiteral(Double.valueOf(con)); } catch (java.lang.NumberFormatException e) { try { return ResourceFactory.createTypedLiteral(Float.valueOf(con)); } catch (Exception e2) { return ResourceFactory.createTypedLiteral(String.valueOf(con)); } } }
Example #20
Source Project: shacl Author: TopQuadrant File: RDFLabels.java License: Apache License 2.0 | 5 votes |
/** * Renders a template call's label template into a label by inserting the * evaluated SPARQL expressions into appropriate spaces marked with {expression}. * Currently only simple variables are supported, e.g. {?test }. * @param buffer the StringBuffer to write to * @param labelTemplate the labelTemplate * @param args the arguments a Map of pre-bound variables (supplied arguments) */ public static void appendTemplateCallLabel(StringBuffer buffer, String labelTemplate, Map<String, RDFNode> args) { for(int i = 0; i < labelTemplate.length(); i++) { if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && labelTemplate.charAt(i + 1) == '?') { int varEnd = i + 2; while(varEnd < labelTemplate.length()) { if(labelTemplate.charAt(varEnd) == '}') { String varName = labelTemplate.substring(i + 2, varEnd); RDFNode varValue = args.get(varName); if(varValue instanceof Resource) { buffer.append(get().getLabel((Resource)varValue)); } else if(varValue instanceof Literal) { buffer.append(varValue.asNode().getLiteralLexicalForm()); } break; } else { varEnd++; } } i = varEnd; } else { buffer.append(labelTemplate.charAt(i)); } } }
Example #21
Source Project: shacl Author: TopQuadrant File: JenaUtil.java License: Apache License 2.0 | 5 votes |
public static Literal getBestStringLiteral(Resource resource, List<String> langs, Iterable<Property> properties, BiFunction<Resource,Property,Iterator<Statement>> getter) { Literal label = null; int bestLang = -1; for(Property predicate : properties) { Iterator<Statement> it = getter.apply(resource, predicate); while(it.hasNext()) { RDFNode object = it.next().getObject(); if(object.isLiteral()) { Literal literal = (Literal)object; String lang = literal.getLanguage(); if(lang.length() == 0 && label == null) { label = literal; } else { // 1) Never use a less suitable language // 2) Never replace an already existing label (esp: skos:prefLabel) unless new lang is better // 3) Fall back to more special languages if no other was found (e.g. use en-GB if only "en" is accepted) int startLang = bestLang < 0 ? langs.size() - 1 : (label != null ? bestLang - 1 : bestLang); for(int i = startLang; i >= 0; i--) { String langi = langs.get(i); if(langi.equals(lang)) { label = literal; bestLang = i; } else if(lang.contains("-") && NodeFunctions.langMatches(lang, langi) && label == null) { label = literal; } } } } } } return label; }
Example #22
Source Project: shacl Author: TopQuadrant File: JenaUtil.java License: Apache License 2.0 | 5 votes |
public static List<Literal> getLiteralProperties(Resource subject, Property predicate) { List<Literal> results = new LinkedList<>(); StmtIterator it = subject.listProperties(predicate); while(it.hasNext()) { Statement s = it.next(); if(s.getObject().isLiteral()) { results.add(s.getLiteral()); } } return results; }
Example #23
Source Project: shacl Author: TopQuadrant File: SPARQLSubstitutions.java License: Apache License 2.0 | 5 votes |
public static Literal withSubstitutions(Literal template, QuerySolution bindings, Function<RDFNode,String> labelFunction) { StringBuffer buffer = new StringBuffer(); String labelTemplate = template.getLexicalForm(); for(int i = 0; i < labelTemplate.length(); i++) { if(i < labelTemplate.length() - 3 && labelTemplate.charAt(i) == '{' && (labelTemplate.charAt(i + 1) == '?' || labelTemplate.charAt(i + 1) == '$')) { int varEnd = i + 2; while(varEnd < labelTemplate.length()) { if(labelTemplate.charAt(varEnd) == '}') { String varName = labelTemplate.substring(i + 2, varEnd); RDFNode varValue = bindings.get(varName); if(varValue != null) { if(labelFunction != null) { buffer.append(labelFunction.apply(varValue)); } else if(varValue instanceof Resource) { buffer.append(RDFLabels.get().getLabel((Resource)varValue)); } else if(varValue instanceof Literal) { buffer.append(varValue.asNode().getLiteralLexicalForm()); } } break; } else { varEnd++; } } i = varEnd; } else { buffer.append(labelTemplate.charAt(i)); } } if(template.getLanguage().isEmpty()) { return ResourceFactory.createTypedLiteral(buffer.toString()); } else { return ResourceFactory.createLangLiteral(buffer.toString(), template.getLanguage()); } }
Example #24
Source Project: shacl Author: TopQuadrant File: PathEvaluator.java License: Apache License 2.0 | 5 votes |
public ExtendedIterator<RDFNode> evalReverse(RDFNode valueNode, NodeExpressionContext context) { // See isReversible, this only supports trivial cases for now if(isInverse) { if(valueNode instanceof Literal) { return WrappedIterator.emptyIterator(); } else { return context.getDataset().getDefaultModel().listObjectsOfProperty((Resource)valueNode, predicate); } } else { return context.getDataset().getDefaultModel().listSubjectsWithProperty(predicate, valueNode).mapWith(r -> (RDFNode)r); } }
Example #25
Source Project: Processor Author: AtomGraph File: Skolemizer.java License: Apache License 2.0 | 5 votes |
protected Literal getLiteral(Resource resource, String namePath) { if (resource == null) throw new IllegalArgumentException("Resource cannot be null"); if (namePath.contains(".")) { String name = namePath.substring(0, namePath.indexOf(".")); String nameSubPath = namePath.substring(namePath.indexOf(".") + 1); Resource subResource = getResource(resource, name); if (subResource != null) return getLiteral(subResource, nameSubPath); } StmtIterator it = resource.listProperties(); try { while (it.hasNext()) { Statement stmt = it.next(); if (stmt.getObject().isLiteral() && stmt.getPredicate().getLocalName().equals(namePath)) { if (log.isTraceEnabled()) log.trace("Found Literal {} for property name: {} ", stmt.getLiteral(), namePath); return stmt.getLiteral(); } } } finally { it.close(); } return null; }
Example #26
Source Project: ontopia Author: ontopia File: RDFTopicMapWriter.java License: Apache License 2.0 | 5 votes |
private Literal convert(ALiteral lit) { String dt = lit.getDatatypeURI(); if (dt == null) return model.createLiteral(lit.toString(), lit.getLang()); else return model.createTypedLiteral(lit.toString(), dt); }
Example #27
Source Project: ontopia Author: ontopia File: RDFToTopicMapConverter.java License: Apache License 2.0 | 5 votes |
private void doConversion(Model model) throws JenaException { StatementHandler totm = new ToTMStatementHandler(); AResourceWrapper subjw = new AResourceWrapper(); AResourceWrapper propw = new AResourceWrapper(); AResourceWrapper objtw = new AResourceWrapper(); ALiteralWrapper litlw = new ALiteralWrapper(); ResIterator it = model.listSubjects(); while (it.hasNext()) { Resource subject = (Resource) it.next(); StmtIterator it2 = subject.listProperties(); // get all statements while (it2.hasNext()) { Statement stmt = (Statement) it2.next(); subjw.resource = stmt.getSubject(); propw.resource = stmt.getPredicate(); RDFNode obj = stmt.getObject(); if (obj instanceof Resource) { objtw.resource = (Resource) obj; totm.statement(subjw, propw, objtw); } else { litlw.literal = (Literal) obj; totm.statement(subjw, propw, litlw); } } } }
Example #28
Source Project: RDFUnit Author: AKSW File: Shape.java License: Apache License 2.0 | 5 votes |
default Optional<Literal> getMessage() { return getPropertyValuePairSets().getPropertyValues(SHACL.message).stream() .filter(RDFNode::isLiteral) .map(RDFNode::asLiteral) //.map(Literal::getLexicalForm) .findFirst(); }
Example #29
Source Project: egeria Author: odpi File: GlossaryModel.java License: Apache License 2.0 | 4 votes |
public Map<String, Map<String, Literal>> getObjectPropertyTermLiteralMap() { return objectPropertyTermLiteralMap; }
Example #30
Source Project: egeria Author: odpi File: GlossaryModel.java License: Apache License 2.0 | 4 votes |
public void setObjectPropertyTermLiteralMap(Map<String, Map<String, Literal>> objectPropertyTermLiteralMap) { this.objectPropertyTermLiteralMap = objectPropertyTermLiteralMap; }