Java Code Examples for org.openrdf.repository.RepositoryConnection#prepareTupleQuery()

The following examples show how to use org.openrdf.repository.RepositoryConnection#prepareTupleQuery() . 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: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get total number of distinct objects for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static long getDistinctSbj(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?subjs) " + // 
			"WHERE " +
			"{" +
       		"?s <" + pred + "> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("subjs").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 2
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get total number of distinct objects of a dataset
 * @return count
 */
public static long getObjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("objts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 3
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get Predicate List
 * @param endPointUrl SPARQL endPoint Url
 * @param graph Named graph
 * @return  predLst Predicates List
 */
private static List<String> getPredicates(String endPointUrl, String graph) throws Exception
{
	List<String>  predLst = new ArrayList<String>();
	String strQuery = getPredQuery(graph);
	SPARQLRepository repo = new SPARQLRepository(endPointUrl);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult res = query.evaluate();
		while (res.hasNext()) 
		{
			String pred = res.next().getValue("p").toString();
			predLst.add(pred);	  		
		}
	} finally {
		conn.close();
		repo.shutDown();
	}
	return predLst;
}
 
Example 4
Source File: SampleBlazegraphSesameEmbedded.java    From blazegraph-samples with GNU General Public License v2.0 6 votes vote down vote up
public static TupleQueryResult executeSelectQuery(final Repository repo, final String query,
		final QueryLanguage ql) throws OpenRDFException  {

	RepositoryConnection cxn;
	if (repo instanceof BigdataSailRepository) {
		cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
	} else {
		cxn = repo.getConnection();
	}

	try {

		final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
		tupleQuery.setIncludeInferred(true /* includeInferred */);
		return tupleQuery.evaluate();
		
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example 5
Source File: TestTicket4249.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 6
Source File: TestTicket632.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example 7
Source File: TestTicket4249.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final String string, final double start, final double length, final String expected)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException, VisitorException {

	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", vf.createLiteral(string));
	q.setBinding("start", vf.createLiteral(start));
	q.setBinding("length", vf.createLiteral(length));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue().stringValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 8
Source File: SPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example 9
Source File: TestTicket353.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException,
		RDFHandlerException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			final ValueFactory vf = conn.getValueFactory();
			conn.add(vf.createURI("os:subject"), vf.createURI("os:prop"), vf.createLiteral("value"));
			conn.commit();

			String query = 
				"SELECT ?b { {} union { ?a ?b ?c } }"
				;
			
			TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			TupleQueryResult tqr = tq.evaluate();
			assertTrue(tqr.hasNext());
			
			while (tqr.hasNext()) {
				System.err.println(tqr.next());
			}
			
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 10
Source File: TestTicket275.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			conn.add(getClass().getResourceAsStream("TestTicket275.ttl"), "",
					RDFFormat.TURTLE);
			conn.commit();

			final String query = "SELECT ?lookup WHERE { ?lookup <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <os:class/Lookup> . ?lookup <os:prop/lookup/majorType> ?majorType . OPTIONAL{?lookup <os:prop/lookup/minorType> ?minorType}. FILTER(STR(?majorType) = ?argMajorType). FILTER(!bound(?minorType))}";
			final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					query);
			q.setBinding("argMajorType", conn.getValueFactory()
					.createLiteral("majoor"));
			final TupleQueryResult tqr = q.evaluate();
			while (tqr.hasNext()) {
			    final Set<String> bindingNames = tqr.next().getBindingNames();
			    if(log.isInfoEnabled())
			        log.info("bindingNames="+bindingNames);
			}
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 11
Source File: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a SELECT SPARQL query against the graphs
 * 
 * @param qs
 *            SELECT SPARQL query
 * @return list of solutions, each containing a hashmap of bindings
 */
public List<HashMap<String, Value>> runSPARQL(String qs) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			TupleQuery query = con.prepareTupleQuery(
					org.openrdf.query.QueryLanguage.SPARQL, qs);
			//System.exit(0);
			TupleQueryResult qres = query.evaluate();
			ArrayList<HashMap<String, Value>> reslist = new ArrayList<HashMap<String, Value>>();
			while (qres.hasNext()) {
				BindingSet b = qres.next();

				Set<String> names = b.getBindingNames();
				HashMap<String, Value> hm = new HashMap<String, Value>();
				for (String n : names) {
					hm.put(n, b.getValue(n));
				}
				reslist.add(hm);
			}
			return reslist;
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 12
Source File: TestTicket2043.java    From database with GNU General Public License v2.0 4 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final String value, final int expectedCnt)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException, VisitorException {

	final String query = "PREFIX :    <http://example/>\r\n" + 
			"\r\n" + 
			"SELECT ?a ?y ?d ?z\r\n" + 
			"{\r\n" + 
			"    ?a :p ?c OPTIONAL { ?a :r ?d }.  \r\n" + 
			"    ?a ?p "+value+" { ?p a ?y } UNION { ?a ?z ?p } \r\n" + 
			"}";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
			query);
	int cnt = 0;
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
		    final Set<String> bindingNames = tqr.next().getBindingNames();
		    cnt++;
		    if(log.isInfoEnabled())
		        log.info("bindingNames="+bindingNames);
		}
	} finally {
		tqr.close();
	}
	// assert number of solutions
	assertEquals(expectedCnt, cnt);
	
	// also assert class of constant node value is TermId, as inlining is disabled
	ASTContainer ast = ((BigdataSailTupleQuery)q).getASTContainer();
	QueryRoot qr = ast.getOptimizedAST();
	GraphPatternGroup<?> gp = qr.getGraphPattern();
	int ivsCnt = 0;
	for (int i=0; i<gp.arity(); i++) {
		BOp bop = gp.get(i);
		if (bop instanceof StatementPatternNode && bop.get(2) instanceof ConstantNode) {
			IV<?, ?> x = ((ConstantNode)bop.get(2)).getValueExpression().get();
			assertTrue(x instanceof TermId);
			ivsCnt++;
		}
	}
	assertEquals(1, ivsCnt);
}
 
Example 13
Source File: StressTest_ClosedByInterrupt_RW.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {

    RepositoryConnection conn = null;
    TupleQueryResult result = null;
    int loop = 0;

    while (stopRequested == false) {

        try {

            System.out.println("[Read      ] snooze");
            snooze(MILLIS_BETWEEN_QUERY_BURSTS);
            System.out.println("[Read      ] enter loop " + loop);

            for (int invocation = 0; invocation < NUM_SELECTS; ++invocation) {

                conn = repo.getReadOnlyConnection();
                conn.setAutoCommit(false);

                final String sparql = "SELECT ?s WHERE { ?s ?p ?o } LIMIT "
                        + NUM_STATEMENTS_PER_SELECT;
                final TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, sparql);
                result = query.evaluate();

                final List<String> duds = new ArrayList<String>();

                while (result.hasNext()) {
                    final BindingSet bindingSet = result.next();
                    for (final Iterator<Binding> i = bindingSet.iterator(); i.hasNext();) {
                        final Binding b = i.next();
                        if (b.getValue() != null) {
                            duds.add(b.getValue().stringValue());
                        }
                    }
                }

                result.close();
                result = null;

                conn.close();
                conn = null;

            }

        } catch (Throwable t) {
            printError("Read Only threw in loop " + loop, t);
        } finally {
            closeNoException(result);
            closeNoException(conn);
        }

        System.out.println("[Read      ] leave loop " + loop);
        ++loop;

    }
}
 
Example 14
Source File: TestSingleTailRule.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testOptionalFilter()
        throws Exception
    {
        final BigdataSail sail = getSail();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
//        final Sail sail = new MemoryStore();
//        final Repository repo = new SailRepository(sail);
        
        repo.initialize();
        final RepositoryConnection cxn = repo.getConnection();
        cxn.setAutoCommit(false);
        
        try {
    
            final ValueFactory vf = sail.getValueFactory();

            URI s = vf.createURI("urn:test:s");
            URI p1 = vf.createURI("urn:test:p1");
            URI p2 = vf.createURI("urn:test:p2");
            Literal v1 = vf.createLiteral(1);
            Literal v2 = vf.createLiteral(2);
            Literal v3 = vf.createLiteral(3);
            cxn.add(s, p1, v1);
            cxn.add(s, p2, v2);
            cxn.add(s, p1, v3);
            cxn.commit();
            
            String qry = 
                "PREFIX :<urn:test:> " +
                "SELECT ?s ?v1 ?v2 " +
                "WHERE { " +
                "  ?s :p1 ?v1 . " +
                "  OPTIONAL {?s :p2 ?v2 FILTER(?v1 < 3) } " +
                "}";
            
            TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, qry);
            TupleQueryResult result = query.evaluate();
            
//            while (result.hasNext()) {
//                System.err.println(result.next());
//            }
            
            Collection<BindingSet> solution = new LinkedList<BindingSet>();
            solution.add(createBindingSet(new Binding[] {
                new BindingImpl("s", s),
                new BindingImpl("v1", v1),
                new BindingImpl("v2", v2),
            }));
            solution.add(createBindingSet(new Binding[] {
                new BindingImpl("s", s),
                new BindingImpl("v1", v3),
            }));
            
            compare(result, solution);
            
        } finally {
            cxn.close();
            if (sail instanceof BigdataSail)
                ((BigdataSail)sail).__tearDownUnitTest();
        }
            
    }
 
Example 15
Source File: ScaleOut.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Issue the query.
 * 
 * @throws Exception
 */
private void doQuery() throws Exception {
   
    // this is how you get a read-only transaction.  MUST be
    // committed or aborted later, see below.
    long transactionId = 
        fed.getTransactionService().newTx(ITx.READ_COMMITTED);
    
    try {

        // open the read-only triple store
        final AbstractTripleStore tripleStore = 
            openTripleStore(fed, transactionId);
        
        // wrap it in a Sesame SAIL
        final BigdataSail sail = new BigdataSail(tripleStore);
        final Repository repo = new BigdataSailRepository(sail);
        repo.initialize();
        
        RepositoryConnection cxn = repo.getConnection();
        try {

            final TupleQuery tupleQuery = 
                cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            tupleQuery.setIncludeInferred(true /* includeInferred */);
            TupleQueryResult result = tupleQuery.evaluate();
            // do something with the results
            int resultCount = 0;
            while (result.hasNext()) {
                BindingSet bindingSet = result.next();
                // log.info(bindingSet);
                resultCount++;
            }
            log.info(resultCount + " results");
            
        } finally {
            // close the repository connection
            cxn.close();
        }
        
        repo.shutDown();
        
    } finally {
        
        // MUST close the transaction, abort is sufficient
        fed.getTransactionService().abort(transactionId);
        
    }
    
}
 
Example 16
Source File: TestMaterialization.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testRegex() throws Exception {
        
      final BigdataSail sail = getSail();
      try {
      sail.initialize();
      final BigdataSailRepository repo = new BigdataSailRepository(sail);
      
      final RepositoryConnection cxn = repo.getConnection();
      
      try {
          cxn.setAutoCommit(false);
  
          final ValueFactory vf = sail.getValueFactory();

          /*
           * Create some terms.
           */
          final URI X = vf.createURI(BD.NAMESPACE + "X");
          final Literal label = vf.createLiteral("John");
          
          /*
           * Create some statements.
           */
          cxn.add(X, RDF.TYPE, RDFS.RESOURCE);
          cxn.add(X, RDFS.LABEL, label);
          
          /*
           * Note: The either flush() or commit() is required to flush the
           * statement buffers to the database before executing any operations
           * that go around the sail.
           */
          cxn.commit();
          
          if (log.isInfoEnabled()) {
              log.info(((BigdataSailRepositoryConnection) cxn).getTripleStore().dumpStore());
          }
          
          {
              
              final String query =
                  "select * where { ?s ?p ?o . FILTER (regex(?o,\"John\",\"i\")) }";
  
              final SailTupleQuery tupleQuery = (SailTupleQuery)
                  cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
              tupleQuery.setIncludeInferred(true /* includeInferred */);
             
              if (log.isInfoEnabled()) {
                  
                  log.info(query);
                  
                  final TupleQueryResult result = tupleQuery.evaluate();
                  while (result.hasNext()) {
                      log.info(result.next());
                  }
                  
              }
              
//              final Collection<BindingSet> answer = new LinkedList<BindingSet>();
//              answer.add(createBindingSet(
//                      new BindingImpl("a", paul),
//                      new BindingImpl("b", mary)
//                      ));
//              answer.add(createBindingSet(
//                      new BindingImpl("a", brad),
//                      new BindingImpl("b", john)
//                      ));
//
//              final TupleQueryResult result = tupleQuery.evaluate();
//              compare(result, answer);

            }
          
        } finally {
            cxn.close();
        }
        } finally {
            if (sail instanceof BigdataSail)
                ((BigdataSail)sail).__tearDownUnitTest();//shutDown();
        }

    }
 
Example 17
Source File: TestMaterialization.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testXsdStr() throws Exception {
        
        final BigdataSail sail = getSail();
        try {
        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        
        final RepositoryConnection cxn = repo.getConnection();
        
        try {
            cxn.setAutoCommit(false);
    
            final ValueFactory vf = sail.getValueFactory();

            /*
             * Create some terms.
             */
            final URI X = vf.createURI(BD.NAMESPACE + "X");
            final Literal label = vf.createLiteral("John");
            
            /*
             * Create some statements.
             */
            cxn.add(X, RDF.TYPE, RDFS.RESOURCE);
            cxn.add(X, RDFS.LABEL, label);
            
            /*
             * Note: The either flush() or commit() is required to flush the
             * statement buffers to the database before executing any operations
             * that go around the sail.
             */
            cxn.commit();
            
            if (log.isInfoEnabled()) {
                log.info(((BigdataSailRepositoryConnection) cxn).getTripleStore().dumpStore());
            }
            
            {
                
                String query =
                    "select * where { ?s ?p ?o . FILTER (xsd:string(?o) = \""+RDF.PROPERTY+"\"^^xsd:string) }";
    
                final SailTupleQuery tupleQuery = (SailTupleQuery)
                    cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
                tupleQuery.setIncludeInferred(true /* includeInferred */);
               
                if (log.isInfoEnabled()) {
                    
                    log.info(query);
                    
                    final TupleQueryResult result = tupleQuery.evaluate();
                    if (result.hasNext()) {
                        while (result.hasNext()) 
                        	log.info(result.next());
                    } else {
                    	fail("expecting result from the vocab");
                    }
                    
                }
                
//                final Collection<BindingSet> answer = new LinkedList<BindingSet>();
//                answer.add(createBindingSet(
//                        new BindingImpl("a", paul),
//                        new BindingImpl("b", mary)
//                        ));
//                answer.add(createBindingSet(
//                        new BindingImpl("a", brad),
//                        new BindingImpl("b", john)
//                        ));
  //
//                final TupleQueryResult result = tupleQuery.evaluate();
//                compare(result, answer);

              }
            
          } finally {
              cxn.close();
          }
          } finally {
              if (sail instanceof BigdataSail)
                  ((BigdataSail)sail).__tearDownUnitTest();//shutDown();
          }

      }
 
Example 18
Source File: HelloBlazegraph.java    From blazegraph-samples with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws OpenRDFException {

		final Properties props = new Properties();
		
		/*
		 * For more configuration parameters see
		 * http://www.blazegraph.com/docs/api/index.html?com/bigdata/journal/BufferMode.html
		 */
		props.put(Options.BUFFER_MODE, BufferMode.DiskRW); // persistent file system located journal
		props.put(Options.FILE, "/tmp/blazegraph/test.jnl"); // journal file location

		final BigdataSail sail = new BigdataSail(props); // instantiate a sail
		final Repository repo = new BigdataSailRepository(sail); // create a Sesame repository

		repo.initialize();

		try {
			// prepare a statement
			final URIImpl subject = new URIImpl("http://blazegraph.com/Blazegraph");
			final URIImpl predicate = new URIImpl("http://blazegraph.com/says");
			final Literal object = new LiteralImpl("hello");
			final Statement stmt = new StatementImpl(subject, predicate, object);

			// open repository connection
			RepositoryConnection cxn = repo.getConnection();

			// upload data to repository
			try {
				cxn.begin();
				cxn.add(stmt);
				cxn.commit();
			} catch (OpenRDFException ex) {
				cxn.rollback();
				throw ex;
			} finally {
				// close the repository connection
				cxn.close();
			}

			// open connection
			if (repo instanceof BigdataSailRepository) {
				cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
			} else {
				cxn = repo.getConnection();
			}

			// evaluate sparql query
			try {

				final TupleQuery tupleQuery = cxn
						.prepareTupleQuery(QueryLanguage.SPARQL,
								"select ?p ?o where { <http://blazegraph.com/Blazegraph> ?p ?o . }");
				final TupleQueryResult result = tupleQuery.evaluate();
				try {
					while (result.hasNext()) {
						final BindingSet bindingSet = result.next();
						System.err.println(bindingSet);
					}
				} finally {
					result.close();
				}

			} finally {
				// close the repository connection
				cxn.close();
			}

		} finally {
			repo.shutDown();
		}
	}
 
Example 19
Source File: TestTicket1682.java    From database with GNU General Public License v2.0 4 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			conn.add(getClass().getResourceAsStream("TestTicket1682.nt"), "",
					RDFFormat.TURTLE);
			conn.commit();

			final String query = "select ?s with { " +
			        "   select ?s where {" +
                       "       ?s <http://p> ?o" +
                       "   } VALUES (?o) {" +
                       "       (\"a\") (\"b\")" +
                       "   }" +
                       "} AS %sub1 " +
                       "where {" +
                       "   INCLUDE %sub1" +
                       "}";
			final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					query);
			final TupleQueryResult tqr = q.evaluate();
			int cnt = 0;
			while (tqr.hasNext()) {
			    final Set<String> bindingNames = tqr.next().getBindingNames();
			    cnt++;
			    if(log.isInfoEnabled())
			        log.info("bindingNames="+bindingNames);
			}
			tqr.close();
			assertEquals(2, cnt);
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 20
Source File: TestMaterialization.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testStr() throws Exception {
        
        final BigdataSail sail = getSail();
        try {
        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        
        final RepositoryConnection cxn = repo.getConnection();
        
        try {
            cxn.setAutoCommit(false);
    
            final ValueFactory vf = sail.getValueFactory();

            /*
             * Create some terms.
             */
            final URI X = vf.createURI(BD.NAMESPACE + "X");
            final Literal label = vf.createLiteral("John");
            
            /*
             * Create some statements.
             */
            cxn.add(X, RDF.TYPE, RDFS.RESOURCE);
            cxn.add(X, RDFS.LABEL, label);
            
            /*
             * Note: The either flush() or commit() is required to flush the
             * statement buffers to the database before executing any operations
             * that go around the sail.
             */
            cxn.commit();
            
            if (log.isInfoEnabled()) {
                log.info(((BigdataSailRepositoryConnection) cxn).getTripleStore().dumpStore());
            }
            
            {
                
                String query =
                    "select * where { ?s ?p ?o . FILTER (str(?o) = \""+RDF.PROPERTY+"\") }";
    
                final SailTupleQuery tupleQuery = (SailTupleQuery)
                    cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
                tupleQuery.setIncludeInferred(true /* includeInferred */);
               
                if (log.isInfoEnabled()) {
                    
                    log.info(query);
                    
                    final TupleQueryResult result = tupleQuery.evaluate();
                    if (result.hasNext()) {
                        while (result.hasNext()) 
                        	log.info(result.next());
                    } else {
                    	fail("expecting result from the vocab");
                    }
                    
                }
                
//                final Collection<BindingSet> answer = new LinkedList<BindingSet>();
//                answer.add(createBindingSet(
//                        new BindingImpl("a", paul),
//                        new BindingImpl("b", mary)
//                        ));
//                answer.add(createBindingSet(
//                        new BindingImpl("a", brad),
//                        new BindingImpl("b", john)
//                        ));
  //
//                final TupleQueryResult result = tupleQuery.evaluate();
//                compare(result, answer);

              }
            
          } finally {
              cxn.close();
          }
          } finally {
              if (sail instanceof BigdataSail)
                  ((BigdataSail)sail).__tearDownUnitTest();//shutDown();
          }

      }