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

The following examples show how to use org.apache.jena.rdf.model.Literal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TriplesToRuleSystem.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * converts a {@link Node} into an {l@ink 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 #2
Source File: LinkedDataFragmentBase.java    From Server.Java with MIT License 6 votes vote down vote up
/**
 * 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 #3
Source File: OneM2MContentInstanceMapper.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 File: TriplePatternFragmentBase.java    From Server.Java with MIT License 6 votes vote down vote up
@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 #5
Source File: SPARQL.java    From NLIWOD with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #6
Source File: RDFIntroSpector.java    From ontopia with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: OneM2MContentInstanceMapper.java    From SDA with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #8
Source File: Skolemizer.java    From Processor with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: ReasoningOntology.java    From Heracles with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: FactIterator.java    From Stargraph with MIT License 6 votes vote down vote up
@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 #11
Source File: JenaOntologySearch.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #13
Source File: NodeFormatter.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: SkolemizerTest.java    From Processor with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: Skolemizer.java    From Processor with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: RDFTopicMapWriter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: PathEvaluator.java    From shacl with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: SPARQLSubstitutions.java    From shacl with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: RDFToTopicMapConverter.java    From ontopia with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: RDFLabels.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #23
Source File: OneM2MContentInstanceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #24
Source File: OneM2MContentInstanceMapper.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #25
Source File: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #26
Source File: SPARQLDataReader.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #27
Source File: ReasoningOntology.java    From Heracles with GNU General Public License v3.0 5 votes vote down vote up
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 #28
Source File: Shape.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
default Optional<Literal> getMessage() {
    return getPropertyValuePairSets().getPropertyValues(SHACL.message).stream()
            .filter(RDFNode::isLiteral)
            .map(RDFNode::asLiteral)
            //.map(Literal::getLexicalForm)
            .findFirst();
}
 
Example #29
Source File: JenaTDBBasedRequestProcessorForTPFs.java    From Server.Java with MIT License 4 votes vote down vote up
/**
 *
 * @param subject
 * @param predicate
 * @param object
 * @param offset
 * @param limit
 * @return
 */
@Override
protected ILinkedDataFragment createFragment(
           final ITriplePatternElement<RDFNode,String,String> subject,
           final ITriplePatternElement<RDFNode,String,String> predicate,
           final ITriplePatternElement<RDFNode,String,String> object,
           final long offset,
           final long limit )
{
    // FIXME: The following algorithm is incorrect for cases in which
    //        the requested triple pattern contains a specific variable
    //        multiple times;
    //        e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn)
    // see https://github.com/LinkedDataFragments/Server.Java/issues/24

    Model model;
    if (defaultGraph == null) {
        model = tdb.getDefaultModel();
    } else {
        model = tdb.getNamedModel(defaultGraph);
    }

    QuerySolutionMap map = new QuerySolutionMap();
    if ( ! subject.isVariable() ) {
        map.add("s", subject.asConstantTerm());
    }
    if ( ! predicate.isVariable() ) {
        map.add("p", predicate.asConstantTerm());
    }
    if ( ! object.isVariable() ) {
        map.add("o", object.asConstantTerm());
    }

    query.setOffset(offset);
    query.setLimit(limit);

    Model triples = ModelFactory.createDefaultModel();

    try (QueryExecution qexec = QueryExecutionFactory.create(query, model, map)) {
        qexec.execConstruct(triples);
    }

    if (triples.isEmpty()) {
        return createEmptyTriplePatternFragment();
    }

    // Try to get an estimate
    long size = triples.size();
    long estimate = -1;

    try (QueryExecution qexec = QueryExecutionFactory.create(countQuery, model, map)) {
        ResultSet results = qexec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.nextSolution() ;
            Literal literal = soln.getLiteral("count");
            estimate = literal.getLong();
        }
    }

    /*GraphStatisticsHandler stats = model.getGraph().getStatisticsHandler();
    if (stats != null) {
        Node s = (subject != null) ? subject.asNode() : null;
        Node p = (predicate != null) ? predicate.asNode() : null;
        Node o = (object != null) ? object.asNode() : null;
        estimate = stats.getStatistic(s, p, o);
    }*/

    // No estimate or incorrect
    if (estimate < offset + size) {
        estimate = (size == limit) ? offset + size + 1 : offset + size;
    }

    // create the fragment
    final boolean isLastPage = ( estimate < offset + limit );
    return createTriplePatternFragment( triples, estimate, isLastPage );
}
 
Example #30
Source File: RDFIntroSpector.java    From ontopia with Apache License 2.0 4 votes vote down vote up
public void setLiteral(Literal literal) {
  this.literal = literal;
}