com.hp.hpl.jena.graph.Triple Java Examples

The following examples show how to use com.hp.hpl.jena.graph.Triple. 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: D2RQQueryHandler.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public BindingQueryPlan prepareBindings(GraphQuery q, Node[] variables) {   
	this.variables = variables;
	this.indexes = new HashMap<Node,Integer>();
	for (int i = 0; i < variables.length; i++) {
		indexes.put(variables[i], new Integer(i));
	}
	BasicPattern pattern = new BasicPattern();
	for (Triple t: q.getPattern()) {
		pattern.add(t);
	}
	Plan plan = QueryEngineD2RQ.getFactory().create(new OpBGP(pattern), dataset, null, null);
	final ExtendedIterator<Domain> queryIterator = new Map1Iterator<Binding,Domain>(new BindingToDomain(), plan.iterator());
	return new BindingQueryPlan() {
		public ExtendedIterator<Domain> executeBindings() {
			return queryIterator;
		}
	};
}
 
Example #2
Source File: NeoGraph.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
/**
 * Delete the given triple from the graph.
 */
@Override
public void delete(Triple triple) throws DeleteDeniedException {
	Transaction tx=graphdb.beginTx();
	org.neo4j.graphdb.Node subject = nodeFactory.get(triple.getSubject());
	System.out.println("Subject node:" + subject.getProperty("uri"));
	if(subject!=null) {
		org.neo4j.graphdb.Node object = nodeFactory.get(triple.getObject());
		System.out.println("Object node:" + object.getProperty("uri"));
		if(object!=null) {
			Relationship relation = relationshipFactory.get(subject, triple.getPredicate().getURI(), object);
			System.out.println("Relationship:" +relation.getProperty("uri"));
			if(!subject.hasRelationship())
				subject.delete();
			if(triple.getObject().isLiteral())
				object.delete();
			else if(!object.hasRelationship())
				object.delete();
		}
		tx.success();
	}	
}
 
Example #3
Source File: IsLiteralTestEvaluator.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
public Var evaluate(NodeSelector nodeSelector, ElementGroup elementGroup, Var var, LDPathEvaluatorConfiguration evaluatorConfiguration) {
    TestingSelector testingSelector = (TestingSelector) nodeSelector;
    FunctionTest functionTest = (FunctionTest) testingSelector.getTest();

    if(functionTest.getArgSelectors().get(0) instanceof PropertySelector) {
        PropertySelector arg = (PropertySelector) functionTest.getArgSelectors().get(0);
        PropertySelector delegate = (PropertySelector) testingSelector.getDelegate();

        Var target = Var.alloc(VarIDGenerator.createID());
        elementGroup.addTriplePattern(new Triple(var.asNode(), NodeFactory.createURI(delegate.getProperty().toString()), target));

        Var selector = Var.alloc(VarIDGenerator.createID());
        elementGroup.addTriplePattern(new Triple(target.asNode(), NodeFactory.createURI(arg.getProperty().toString()), selector.asNode()));

        elementGroup.addElementFilter(new ElementFilter(new E_IsLiteral(new ExprVar(selector))));

        return selector;
    } else {
        throw new IllegalStateException("Argument of function isLiteral has to be a PropertySelector");
    }
}
 
Example #4
Source File: DeepPagingIterator.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
@Override
public Triple next() {
	try {
		final int nextDocId = iterator().nextDoc();
		
		Triple triple = null;
		if (consumer.requireTripleBuild()) { 
			final Document document = searcher.doc(nextDocId, TRIPLE_FIELDS);
			triple = Triple.create(
					NTriples.asURIorBlankNode((String) document.get(Field.S)), 
					NTriples.asURI((String) document.get(Field.P)),
					NTriples.asNode((String) document.get(Field.O)));
		} else {
			triple = DUMMY_TRIPLE;
		}
		consumer.afterTripleHasBeenBuilt(triple, nextDocId);
		return triple;
	} catch (final IOException exception) {
		throw new RuntimeException(exception);
	}
}
 
Example #5
Source File: ExecutionResultIterator.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
@Override
	public Triple next() {
		//System.out.println("ExecutionResultIterator#next");
		try(Transaction tx = graphdb.beginTx()) {
		Map<String,Object> row = delegate.next();
		//System.out.println("In execution iterator subject: " + row.get("subject") + row.get("subject").getClass());
		
		//Node nsubject = (Node) row.get("subject");
//		JenaNeoNode neonode = new JenaNeoNode(nsubject);
//		System.out.println("Node is uri:" + neonode.isURI());
		
		//System.out.println("Subject: "+ new JenaNeoNode((Node)row.get("subject")));
		
		Triple t = new Triple(new JenaNeoNode((Node)row.get("subject")),
				ResourceFactory.createProperty((String)row.get("type(predicate)")).asNode(),
				new JenaNeoNode((Node)row.get("object")));
		return t;
		}
	}
 
Example #6
Source File: RDFReader.java    From marklogic-contentpump with Apache License 2.0 6 votes vote down vote up
protected boolean nextStreamingTripleKeyValue() throws IOException, InterruptedException {
    if(rdfIter == null) return false;
    setKey();
    write("<sem:triples xmlns:sem='http://marklogic.com/semantics'>");
    int max = MAXTRIPLESPERDOCUMENT;
    while (max > 0 && rdfIter.hasNext()) {
        Triple triple = (Triple) rdfIter.next();
        write("<sem:triple>");
        write(subject(triple.getSubject()));
        write(predicate(triple.getPredicate()));
        write(object(triple.getObject()));
        write("</sem:triple>");
        notifyUser();
        max--;
    }
    write("</sem:triples>\n");

    if (!rdfIter.hasNext()) {
        pos = 1;
    }

    writeValue();
    return true;
}
 
Example #7
Source File: DeepPagingIterator.java    From SolRDF with Apache License 2.0 6 votes vote down vote up
@Override
public Triple next() {
	final SolrDocument document = iterator().next();
	
	Triple triple = null;
	if (consumer.requireTripleBuild()) { 
		triple = Triple.create(
				NTriples.asURIorBlankNode((String) document.getFieldValue(Field.S)), 
				NTriples.asURI((String) document.getFieldValue(Field.P)),
				NTriples.asNode((String) document.getFieldValue(Field.O)));
	} else {
		triple = DUMMY_TRIPLE;
	}
	// FIXME
	// consumer.afterTripleHasBeenBuilt(triple, nextDocId);
	return triple;
}
 
Example #8
Source File: GeneralResourceCollection.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public Model getInventoryModel(int limit) {
	log.info("Listing entity set: " + entityMaker);
	Model result = ModelFactory.createDefaultModel();
	result.setNsPrefixes(mapping.getPrefixes());
	GeneralFindQuery query = new GeneralFindQuery(Triple.ANY, inventory, limit, 
			new ExecutionContext(mapping.getContext(), null, null, null));
	Iterator<Triple> it = TripleQueryIter.create(query.iterator());
	while (it.hasNext()) {
		result.getGraph().add(it.next());
	}
	return result;
}
 
Example #9
Source File: GraphD2RQ.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<Triple> graphBaseFind(TripleMatch m) {
	checkOpen();
	Triple t = m.asTriple();
	if (log.isDebugEnabled()) {
		log.debug("Find: " + PrettyPrinter.toString(t, getPrefixMapping()));
	}
	FindQuery query = new FindQuery(t, mapping.getTripleRelations(), 
			new ExecutionContext(mapping.getContext(), this, null, null));
	ExtendedIterator<Triple> result = TripleQueryIter.create(query.iterator());
	result = result.andThen(mapping.getAdditionalTriples().find(t));
	return result;
   }
 
Example #10
Source File: CachingGraphD2RQ.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
/**
 * Overloaded to reuse and update the cache.
 */
@Override
public ExtendedIterator<Triple> graphBaseFind(TripleMatch m) {
	List<Triple> cached = queryCache.get(m);
	if (cached != null) {
           return WrappedIterator.create(cached.iterator());
	}
	ExtendedIterator<Triple> it = super.graphBaseFind(m);
	final List<Triple> list = it.toList();
	queryCache.put(m, list);
	return WrappedIterator.create(list.iterator());
}
 
Example #11
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performDelete(final Triple triple) {
	final DeleteUpdateCommand deleteCommand = new DeleteUpdateCommand(request);
	deleteCommand.query = deleteQuery(triple);
	try {
		updateProcessor.processDelete(deleteCommand);
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new DeleteDeniedException(exception.getMessage(), triple);
	}		
}
 
Example #12
Source File: ResourceCollection.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
private Collection<TripleRelation> filterTripleRelations(Collection<TripleRelation> entityDescription) {
	List<TripleRelation> result = new ArrayList<TripleRelation>();
	for (TripleRelation triples: entityDescription) {
		triples = triples.orderBy(TripleRelation.SUBJECT, true);
		if (triples.selectTriple(new Triple(Node.ANY, RDF.Nodes.type, Node.ANY)) != null) {
			result.add(triples);
		}
		// TODO: The list of label properties is redundantly specified in PageServlet
		if (triples.selectTriple(new Triple(Node.ANY, RDFS.label.asNode(), Node.ANY)) != null) {
			result.add(triples);
		} else if (triples.selectTriple(new Triple(Node.ANY, SKOS.prefLabel.asNode(), Node.ANY)) != null) {
			result.add(triples);
		} else if (triples.selectTriple(new Triple(Node.ANY, DC.title.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		} else if (triples.selectTriple(new Triple(Node.ANY, DCTerms.title.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		} else if (triples.selectTriple(new Triple(Node.ANY, FOAF.name.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		}
	}
	if (result.isEmpty()) {
		result.add(new TripleRelation(sqlConnection, entityTable, 
				entityMaker, 
				new FixedNodeMaker(RDF.type.asNode()), 
				new FixedNodeMaker(RDFS.Resource.asNode())));
	}
	return result;
}
 
Example #13
Source File: GeneralFindQuery.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public GeneralFindQuery(Triple triplePattern, Collection<GeneralTripleRelation> tripleRelations, int limit,
		ExecutionContext context) {
	this.triplePattern = triplePattern;
	this.tripleRelations = tripleRelations;
	this.limitPerRelation = limit;
	this.context = context;
}
 
Example #14
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void removeStatement(org.ontoware.rdf2go.model.node.Resource subject, URI predicate,
        org.ontoware.rdf2go.model.node.Node object) throws ModelRuntimeException {
	assertModel();
	
	log.debug("removing a statement (" + subject + "," + predicate + "," + object + ")");
	this.modificationCount++;
	this.jenaModel.getGraph().delete(
	        new Triple(
	        
	        TypeConversion.toJenaNode(subject, this.jenaModel), TypeConversion.toJenaNode(
	                predicate, this.jenaModel), TypeConversion.toJenaNode(object,
	                this.jenaModel)));
}
 
Example #15
Source File: GeneralResourceCollection.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
private Collection<GeneralTripleRelation> filterTripleRelations(Collection<GeneralTripleRelation> entityDescription) {
	List<GeneralTripleRelation> result = new ArrayList<GeneralTripleRelation>();
	for (GeneralTripleRelation triples: entityDescription) {
		triples = triples.orderBy(TripleRelation.SUBJECT, true);
		if (triples.selectTriple(new Triple(Node.ANY, RDF.Nodes.type, Node.ANY)) != null) {
			result.add(triples);
		}
		// TODO: The list of label properties is redundantly specified in PageServlet
		if (triples.selectTriple(new Triple(Node.ANY, RDFS.label.asNode(), Node.ANY)) != null) {
			result.add(triples);
		} else if (triples.selectTriple(new Triple(Node.ANY, SKOS.prefLabel.asNode(), Node.ANY)) != null) {
			result.add(triples);
		} else if (triples.selectTriple(new Triple(Node.ANY, DC.title.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		} else if (triples.selectTriple(new Triple(Node.ANY, DCTerms.title.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		} else if (triples.selectTriple(new Triple(Node.ANY, FOAF.name.asNode(), Node.ANY)) != null) {
			result.add(triples);					
		}
	}
	if (result.isEmpty()) {
		result.add(new GeneralTripleRelation(connection, entityTable, 
				entityMaker, 
				new FixedNodeMaker(RDF.type.asNode()), 
				new FixedNodeMaker(RDFS.Resource.asNode())));
	}
	return result;
}
 
Example #16
Source File: GeneralGraphD2RQ.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<Triple> graphBaseFind(TripleMatch m) {
	checkOpen();
	Triple t = m.asTriple();
	if (log.isDebugEnabled()) {
		log.debug("Find: " + PrettyPrinter.toString(t, getPrefixMapping()));
	}
	ExecutionContext context = new ExecutionContext(mapping.getContext(), this, null, null);
	GeneralFindQuery query = new GeneralFindQuery(t, mapping.getTripleRelations(), context);
	ExtendedIterator<Triple> result = TripleQueryIter.create(query.iterator());
	result = result.andThen(mapping.getAdditionalTriples().find(t));
	return result;
   }
 
Example #17
Source File: GeneralTripleQueryIter.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public Triple next() {
	Binding b = wrapped.next();
	return new Triple(
			b.get(TripleRelation.SUBJECT), 
			b.get(TripleRelation.PREDICATE), 
			b.get(TripleRelation.OBJECT));
}
 
Example #18
Source File: JenaGraphExample.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	// Load mapping file
	Model mapModel = FileManager.get().loadModel("doc/example/mapping-iswc.ttl");
	
	// Read mapping file
	D2RQReader reader = new D2RQReader(mapModel, "http://localhost:2020/");
	Mapping mapping = reader.getMapping();
	
	// Compile mapping for D2RQ engine
	CompiledMapping compiled = mapping.compile();

	// Set up the GraphD2RQ
	GraphD2RQ g = new GraphD2RQ(compiled);

	// Create a find(spo) pattern 
	Node subject = Node.ANY;
	Node predicate = DC.date.asNode();
	Node object = Node.createLiteral("2003", null, XSDDatatype.XSDgYear);
	Triple pattern = new Triple(subject, predicate, object);

	// Query the graph
	Iterator<Triple> it = g.find(pattern);
	
	// Output query results
	while (it.hasNext()) {
		Triple t = it.next();
	    System.out.println("Published in 2003: " + t.getSubject());
	}
	g.close();
}
 
Example #19
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performAdd(final Triple triple) {
	updateCommand.clear();
	
	final SolrInputDocument document = new SolrInputDocument();
	this.updateCommand.solrDoc = document;
	document.setField(Field.C, graphNodeStringified);
	document.setField(Field.S, asNt(triple.getSubject()));
	document.setField(Field.P, asNtURI(triple.getPredicate()));
	document.setField(Field.ID, UUID.nameUUIDFromBytes(
			new StringBuilder()
				.append(graphNodeStringified)
				.append(triple.getSubject())
				.append(triple.getPredicate())
				.append(triple.getObject())
				.toString().getBytes()).toString());
	
	final String o = asNt(triple.getObject());
	document.setField(Field.O, o);

	final Node object = triple.getObject();
	if (object.isLiteral()) {
		final String language = object.getLiteralLanguage();
		document.setField(Field.LANG, isNotNullOrEmptyString(language) ? language : NULL_LANGUAGE);				

		final RDFDatatype dataType = object.getLiteralDatatype();
		final Object value = object.getLiteralValue();
		registry.get(dataType != null ? dataType.getURI() : null).inject(document, value);
	} else {
		registry.catchAllFieldInjector.inject(document, o);
	}			

	try {
		updateProcessor.processAdd(updateCommand);
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new AddDeniedException(exception.getMessage(), triple);
	}
}
 
Example #20
Source File: LocalGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public long getStatistic(final Node s, final Node p, final Node o) {
	final SolrIndexSearcher.QueryResult result = new SolrIndexSearcher.QueryResult();
    try {
	    return searcher.search(
	    		result, 
	    		queryCommand(Triple.create(s, p, o), sortSpec())).getDocListAndSet().docList.matches();
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new SolrException(ErrorCode.SERVER_ERROR, exception);
	}	    
}
 
Example #21
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void addStatement(org.ontoware.rdf2go.model.node.Resource subject, URI predicate,
        org.ontoware.rdf2go.model.node.Node object) throws ModelRuntimeException {
	assertModel();
	try {
		log.debug("adding a statement (" + subject + "," + predicate + "," + object + ")");
		this.modificationCount++;
		if(!(object instanceof DatatypeLiteral)) {
			this.jenaModel.getGraph().add(
			        new Triple(TypeConversion.toJenaNode(subject, this.jenaModel),
			                TypeConversion.toJenaNode(predicate, this.jenaModel),
			                TypeConversion.toJenaNode(object, this.jenaModel)));
		} else
		// DatatypeLiteral
		{
			// build Resources/Literals
			Resource s = null;
			if(subject instanceof URI) {
				s = this.jenaModel.createResource(subject.toString());
			} else
			// subject is a BlankNode
			{
				s = this.jenaModel.createResource(((Node)((AbstractBlankNodeImpl)subject)
				        .getUnderlyingBlankNode()).getBlankNodeId());
			}
			
			Property p = this.jenaModel.createProperty(predicate.toString());
			
			String datatypeValue = ((DatatypeLiteral)object).getValue();
			String datatypeURI = ((DatatypeLiteral)object).getDatatype().toString();
			Literal o = this.jenaModel.createTypedLiteral(datatypeValue, datatypeURI);
			
			// Add the statement to the model
			this.jenaModel.add(s, p, o);
		}
	} catch(BadURIException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #22
Source File: IsATestEvaluator.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@Override
public Var evaluate(NodeSelector nodeSelector, ElementGroup elementGroup, Var var, LDPathEvaluatorConfiguration evaluatorConfiguration) {
    TestingSelector testingSelector = (TestingSelector) nodeSelector;
    NodeTest nodeTest = testingSelector.getTest();
    Var delVar = LDPathEvaluator.evaluate(testingSelector.getDelegate(), elementGroup, var, evaluatorConfiguration);

    IsATest isATest = (IsATest) nodeTest;
    elementGroup.addTriplePattern(new Triple(delVar.asNode(), RDF.type.asNode(), NodeFactory.createURI(isATest.getPathExpression(new SesameValueBackend()).replace("<", "").replace(">", "").replaceFirst("is-a ", ""))));

    return delVar;
}
 
Example #23
Source File: CloudGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performAdd(final Triple triple) {
	final SolrInputDocument document = new SolrInputDocument();
	document.setField(Field.C, graphNodeStringified);
	document.setField(Field.S, asNt(triple.getSubject()));
	document.setField(Field.P, asNtURI(triple.getPredicate()));
	document.setField(Field.ID, UUID.nameUUIDFromBytes(
			new StringBuilder()
				.append(graphNodeStringified)
				.append(triple.getSubject())
				.append(triple.getPredicate())
				.append(triple.getObject())
				.toString().getBytes()).toString());
	
	final Node object = triple.getObject();
	final String o = asNt(object);
	document.setField(Field.O, o);

	if (object.isLiteral()) {
		final String language = object.getLiteralLanguage();
		document.setField(Field.LANG, isNotNullOrEmptyString(language) ? language : NULL_LANGUAGE);				

		final RDFDatatype dataType = object.getLiteralDatatype();
		final Object value = object.getLiteralValue();
		registry.get(dataType != null ? dataType.getURI() : null).inject(document, value);
	} else {
		registry.catchAllFieldInjector.inject(document, o);
	}			

	try {
		cloud.add(document);
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new AddDeniedException(exception.getMessage(), triple);
	}
}
 
Example #24
Source File: CloudGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a DELETE query.
 * 
 * @param triple the triple (maybe a pattern?) that must be deleted.
 * @return a DELETE query.
 */
String deleteQuery(final Triple triple) {
	final StringBuilder builder = new StringBuilder();
	if (triple.getSubject().isConcrete()) {
		and(builder).append(fq(Field.S, asNt(triple.getSubject()))); 
	}
	
	if (triple.getPredicate().isConcrete()) {
		and(builder).append(fq(Field.P, asNtURI(triple.getPredicate())));
	}
		
	if (triple.getObject().isConcrete()) {
		and(builder);
		
		final Node o = triple.getObject();
		if (o.isLiteral()) {
			final String language = o.getLiteralLanguage();
			if (Strings.isNotNullOrEmptyString(language)) {
				builder
					.append(fq(Field.LANG, language))
					.append(" AND ");
			}
			
			final String literalValue = o.getLiteralLexicalForm(); 
			final RDFDatatype dataType = o.getLiteralDatatype();
			registry.get(dataType != null ? dataType.getURI() : null).addConstraint(builder, literalValue);
		} else {
			registry.catchAllInjector().addConstraint(builder, asNt(o));
		}
	}
	
	return and(builder).append(fq(Field.C, graphNodeStringified)).toString();
}
 
Example #25
Source File: RDFStoreDAO.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, 
 * to get the discovered links.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param graphName 			the graphName, null in case of default graph.
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param offset				causes the solutions generated to start after 
 *                              the specified number of solutions.
 * @param limit					upper bound on the number of solutions returned.
 * @return a list of triples with the discovered links.
 * @since 2.0
 */
public Triple[] getDiscoveredLinks(final String sparqlEndpointURI, final String graphName, final String user, final String password, final int offset, final int limit) {
	final String query = "select * FROM <" + graphName + "> " + 
					"where {?source ?rel ?target }" +
					" ORDER BY ?source ?target" +
					" OFFSET " + offset + " LIMIT " + limit;
  	ArrayList<Triple> linksList = new ArrayList<Triple>();
 	try {
        // Execute the query and obtain results
        final QueryExecution qexec = QueryExecutionFactory.sparqlService(
        		sparqlEndpointURI, 
        		QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
        qexec.setTimeout(2000, 5000);
           final ResultSet results = qexec.execSelect() ;
           while (results.hasNext())
           {
           	final QuerySolution soln = results.nextSolution() ;
           	final Resource sourceResType = soln.getResource("source");
           	final Resource targetResType = soln.getResource("target");
           	final Resource relResType = soln.getResource("rel");
       		final Triple triple = new Triple(sourceResType.asNode(), relResType.asNode(), targetResType.asNode());
       		linksList.add(triple);
           }
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
	if (linksList.isEmpty()) {
		return new Triple[0];
	}
	return (Triple[]) linksList.toArray(new Triple[linksList.size()]);
}
 
Example #26
Source File: RDFStoreDAO.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, 
 * to get the ambiguous discovered links of a source URI.
 *
 * @param ambiguousLink			a {@link eu.aliada.shared.rdfstore.AmbiguousLink} that contains the source URI.  
 * @param localRes				the source resource of the link.  
 * @param extResBegin			the beginning string of the target link.  
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param graphName 			the graphName, null in case of default graph.
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param offset				causes the solutions generated to start after 
 *                              the specified number of solutions.
 * @param limit					upper bound on the number of solutions returned.
 * @since 2.0
 */
public void getSourceURIAmbiguousLinks(final AmbiguousLink ambiguousLink, final Resource localRes, final String extResBegin, final String sparqlEndpointURI, final String graphName, final String user, final String password) {
	final String query = "SELECT ?rel ?extRes FROM <" + graphName + "> " + 
			" WHERE {<" + ambiguousLink.getSourceURI() + "> ?rel ?extRes ." +
			" FILTER regex(?extRes, \"^" + extResBegin + "\", \"i\")" +
			" }";
	try {
		// Execute the query and obtain results
		final QueryExecution qexec = QueryExecutionFactory.sparqlService(
				sparqlEndpointURI, 
				QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
		qexec.setTimeout(2000, 5000);
		final ResultSet results = qexec.execSelect() ;
		while (results.hasNext())
		{
			final QuerySolution soln = results.nextSolution() ;
	    	final Resource extRes = soln.getResource("extRes");
           	final Resource relResType = soln.getResource("rel");
           	final Triple triple = new Triple(localRes.asNode(), relResType.asNode(), extRes.asNode());
	    	ambiguousLink.addLink(triple);
	    }
	    qexec.close() ;
	  } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
}
 
Example #27
Source File: CloudGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void performDelete(final Triple triple) {
	try {
		cloud.deleteByQuery(deleteQuery(triple));
	} catch (final Exception exception) {
		LOGGER.error(MessageCatalog._00113_NWS_FAILURE, exception);
		throw new DeleteDeniedException(exception.getMessage(), triple);
	}	
}
 
Example #28
Source File: NeoGraph.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
/**
 * Add triple in the graph. 
 * First convert Jena triple to Neo4j node and relationship and then add it in the neo4j graph
 */
@Override
public void add(Triple triple) throws AddDeniedException {
	try (Transaction tx = graphdb.beginTx()) {
		// Get or create a node for subject
		org.neo4j.graphdb.Node subject = nodeFactory.getOrCreate(triple.getSubject());
		// Get or create a node for object
		org.neo4j.graphdb.Node object = nodeFactory.getOrCreate(triple.getObject());
		// Don't add triple if relationship already exists
		relationshipFactory.getOrCreate(subject, triple.getPredicate().getURI(), object);
		tx.success();
	}
}
 
Example #29
Source File: SolRDFGraph.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<Triple> graphBaseFind(final Triple pattern) {	
	try {
		return WrappedIterator.createNoRemove(query(pattern));
	} catch (final SyntaxError exception) {
		logger().error(MessageCatalog._00113_NWS_FAILURE, exception);
		return new NullIterator<Triple>();
	}
}
 
Example #30
Source File: RdfBulkUpdateRequestHandler.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
@Override
public void load(
		final SolrQueryRequest request, 
		final SolrQueryResponse response,
		final ContentStream stream, 
		final UpdateRequestProcessor processor) throws Exception {
	
	final PipedRDFIterator<Triple> iterator = new PipedRDFIterator<Triple>();
	final StreamRDF inputStream = new PipedTriplesStream(iterator);
	
	executor.submit(new Runnable() {
		@Override
		public void run() {
			try {
				RDFDataMgr.parse(
						inputStream, 
						stream.getStream(), 
						RDFLanguages.contentTypeToLang(stream.getContentType()));
			} catch (final IOException exception) {
				throw new SolrException(ErrorCode.SERVER_ERROR, exception);
			}					
		}
	});
		
	// Graph Store Protocol indicates the target graph URI separately.
	// So the incoming Content-type here is one that maps "Triples Loader" but
	// the indexed tuple could be a Quad.
	final String graphUri = request.getParams().get(Names.GRAPH_URI_ATTRIBUTE_NAME);
	
	final DatasetGraph dataset = new LocalDatasetGraph(request, response, null, null);
	final Graph defaultGraph = graphUri == null 
			? dataset.getDefaultGraph() 
			: dataset.getGraph(NodeFactory.createURI(graphUri));
	while (iterator.hasNext()) {
		defaultGraph.add(iterator.next());
	}		
}