Java Code Examples for com.bigdata.rdf.model.BigdataValueFactory#createURI()

The following examples show how to use com.bigdata.rdf.model.BigdataValueFactory#createURI() . 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: AbstractOptimizerTestCaseWithUtilityMethods.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a SPARQL 1.1 {@link ServiceNode} using the specified vars in its
 * body, with a constant endpoint.
 */
ServiceNode serviceSparql11WithConstant(final String... varNames) {
   
   final JoinGroupNode jgn = joinGroupWithVars(varNames);
   
   final BigdataValueFactory f = store.getValueFactory();
   final BigdataURI serviceEndpoint = f.createURI("http://custom.endpoint");
   final IV serviceEndpointIV = makeIV(serviceEndpoint);
   
   final BigdataValue[] values = new BigdataValue[] { serviceEndpoint };       
   store.getLexiconRelation().addTerms(
      values, values.length, false/* readOnly */);
   
    final ServiceNode serviceNode = 
       (ServiceNode) new Helper(){{
          tmp = service(constantNode(serviceEndpointIV),jgn);
       }}.getTmp();  
       
    return serviceNode;
}
 
Example 2
Source File: TestTicket1086.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * When loading quads into a triple store and the BigdataSail option
 * REJECT_QUADS_IN_TRIPLE_MODE is set to true, an exception will be thrown.
 */
public void testQuadStrippingRejected() throws Exception {

   BigdataSailRepositoryConnection cxn = null;

   final BigdataSail sail = getSail(getTriplesNoInferenceNoQuadsStripping());

   boolean exceptionEncountered = false;
   try {

      sail.initialize();
      final BigdataSailRepository repo = new BigdataSailRepository(sail);
      cxn = (BigdataSailRepositoryConnection) repo.getConnection();

      final BigdataValueFactory vf = (BigdataValueFactory) sail
            .getValueFactory();
      final URI s = vf.createURI("http://test/s");
      final URI p = vf.createURI("http://test/p");
      final URI o = vf.createURI("http://test/o");
      final URI c = vf.createURI("http://test/c");

      BigdataStatement stmt = vf.createStatement(s, p, o, c);
      cxn.add(stmt);

   } catch (RepositoryException e) {
      
      exceptionEncountered = true; // expected !
      
   } finally {
      
      if (cxn != null)
         cxn.close();
      sail.__tearDownUnitTest();
   }
   
   assertTrue(exceptionEncountered);
}
 
Example 3
Source File: TestInlineURIs.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public void testInlineUUIDs() throws Exception {
  	
      /*
       * The bigdata store, backed by a temporary journal file.
       */
      final AbstractTripleStore store = getStore(getProperties());
 	
try {

	final BigdataValueFactory vf = store.getValueFactory();

	final BigdataURI uri1 = vf.createURI("urn:uuid:" + UUID.randomUUID().toString());
	final BigdataURI uri2 = vf.createURI("urn:uuid:" + UUID.randomUUID().toString());
	final BigdataURI uri3 = vf.createURI("urn:uuid:foo");

	final StatementBuffer<BigdataStatement> sb = new StatementBuffer<BigdataStatement>(store, 10/* capacity */);

	sb.add(uri1, RDF.TYPE, XSD.UUID);
	sb.add(uri2, RDF.TYPE, XSD.UUID);
	sb.add(uri3, RDF.TYPE, XSD.UUID);
	sb.flush();
	store.commit();

	if (log.isDebugEnabled())
		log.debug(store.dumpStore());

	assertTrue(uri1.getIV().isInline());
	assertTrue(uri2.getIV().isInline());
	assertFalse(uri3.getIV().isInline());

} finally {
	store.__tearDownUnitTest();
      }
  	
  }
 
Example 4
Source File: TestTicket1893.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
   * case 19:
   * {@link Options#INLINE_TEXT_LITERALS} is false 
   * {@link Options#INLINE_XSD_DATATYPE_LITERALS} is false 
   * data loaded from file
   */
  public void test_19() throws Exception {
      
      final String namespace = "test" + UUID.randomUUID();
      
      final BigdataSailRepositoryConnection cxn = prepareTest(namespace, false /*inlineTextLiterals*/ , 
      		false /*inlineXSDDatatypeLiterals*/);
      
      loadData(cxn);
      
      BigdataValueFactory vf = cxn.getValueFactory();
BigdataValue[] values = new BigdataValue[]{
		vf.createURI("http://s"),
		vf.createLiteral("1", XMLSchema.INTEGER),
		vf.createLiteral(2),
		vf.createLiteral("3.0", XMLSchema.DECIMAL),
		vf.createLiteral(4.0),
		vf.createLiteral(true),
		vf.createLiteral(false),
		vf.createLiteral("plain string"),
		vf.createLiteral("datatyped string", XMLSchema.STRING),
		vf.createLiteral("english string", "en"),
};

cxn.getTripleStore().getLexiconRelation().addTerms(values, values.length, true /* readOnly */);
      
      assertFalse(values[0].getIV().isInline()); //    	http://s
      assertFalse(values[1].getIV().isInline()); //    	1
      assertFalse(values[2].getIV().isInline()); //    	"2"^^xsd:int
      assertFalse(values[3].getIV().isInline()); //    	3.0
      assertFalse(values[4].getIV().isInline()); //    	"4.0"^^xsd:double
      assertFalse(values[5].getIV().isInline()); //    	true
      assertFalse(values[6].getIV().isInline()); //    	"false"^^xsd:boolean
      assertFalse(values[7].getIV().isInline()); //    	"plain string"
      assertFalse(values[8].getIV().isInline()); //    	"datatyped string"^^xsd:string
      assertFalse(values[9].getIV().isInline()); //    	"english string"@en
      
      endTest(cxn);
      
  }
 
Example 5
Source File: TestTicket1086.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * When loading quads into a triple store, the context is striped away by
 * default.
 */
public void testQuadStripping() throws Exception {

    BigdataSailRepositoryConnection cxn = null;

    final BigdataSail sail = getSail(getTriplesNoInference());

    try {

        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        cxn = (BigdataSailRepositoryConnection) repo.getConnection();

        final BigdataValueFactory vf = (BigdataValueFactory) sail
              .getValueFactory();
        final URI s = vf.createURI("http://test/s");
        final URI p = vf.createURI("http://test/p");
        final URI o = vf.createURI("http://test/o");
        final URI c = vf.createURI("http://test/c");

        BigdataStatement stmt = vf.createStatement(s, p, o, c);
        cxn.add(stmt); 

        RepositoryResult<Statement> stmts = cxn.getStatements(null, null,
              null, false);
        Statement res = stmts.next();
        assertEquals(s, res.getSubject());
        assertEquals(p, res.getPredicate());
        assertEquals(o, res.getObject());
        assertEquals(null, res.getContext());

    } finally {
        if (cxn != null)
            cxn.close();
        sail.__tearDownUnitTest();
    }
}
 
Example 6
Source File: TestIVariableBindingRequirements.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test interface implementation for internal {@link BDS} service. Note
 * that, at the time being, the BDS service does not allow the injection
 * of variables (in contrast to, e.g., the FTS service). Therefore, this
 * service imposes only a not bound constraint on the outgoing variable.
 */
public void testServiceBDS() {
   
   final BigdataValueFactory f = store.getValueFactory();
   final BigdataURI bdsSearch = f.createURI(BDS.NAMESPACE + "search");
   final BigdataURI predSearch = f.createURI(BDS.SEARCH.toString());
   final BigdataURI predSearchTimeout = f.createURI(BDS.SEARCH_TIMEOUT.toString());
   final BigdataURI predMatchExact = f.createURI(BDS.MATCH_EXACT.toString());
   
   final BigdataValue[] values = 
      new BigdataValue[] { bdsSearch, predSearch, predSearchTimeout, predMatchExact };       
   store.getLexiconRelation().addTerms(values, values.length, false/* readOnly */);

   final ServiceNode serviceNode = 
      (ServiceNode) new Helper(){{
         tmp = 
            service(
               constantNode(makeIV(bdsSearch)), 
               joinGroupNode(
                  statementPatternNode(varNode("res"), constantNode(makeIV(predSearch)), constantNode("search")),
                  statementPatternNode(varNode("res"), constantNode(makeIV(predSearchTimeout)), constantNode("1000")),
                  statementPatternNode(varNode("res"), constantNode(makeIV(predMatchExact)), constantNode("false"))));
         }}.getTmp();
         
   
   final Set<IVariable<?>> requiredBound = new HashSet<IVariable<?>>();
   final Set<IVariable<?>> desiredBound = new HashSet<IVariable<?>>();
         
   // dummy sa object
   final StaticAnalysis sa = 
      new StaticAnalysis(new QueryRoot(QueryType.SELECT), null);

   assertEquals(requiredBound, serviceNode.getRequiredBound(sa));
   assertEquals(desiredBound, serviceNode.getDesiredBound(sa));
      
}
 
Example 7
Source File: TestTripleStore.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Unit test verifies that {@link BigdataValue}s whose term identifiers
 * have already been assigned are unchanged by
 * {@link LexiconRelation#addTerms(BigdataValue[], int, boolean)}.
 * <p>
 * Note: {@link BNode}s are not tested for this property since they will be
 * assigned a new term identifier each time. Blank nodes are ONLY made
 * self-consistent within a canonicalizing mapping imposed for some blank
 * node context, e.g., a source document that is being parsed.
 */
public void test_addTermsFiltersAlreadyAssigned() {

    final AbstractTripleStore store = getStore();

    try {
    
        final BigdataValueFactory valueFactory = store.getValueFactory();
        
        final BigdataURI x = valueFactory.createURI("http://www.foo.org/x");
        final BigdataURI y = valueFactory.createURI("http://www.foo.org/y");
        final BigdataLiteral z = valueFactory.createLiteral("z");
        
        // add terms - lots of duplicates here.
        store.addTerms(new BigdataValue[] { x, y, x, z, y, z});
        
        final IV _x = x.getIV();
        final IV _y = y.getIV();
        final IV _z = z.getIV();
        
        // none are NULL.
        assertNotSame(x.getIV(),NULL);
        assertNotSame(y.getIV(),NULL);
        assertNotSame(z.getIV(),NULL);

        // all distinct.
        assertNotSame(x.getIV(), y.getIV());
        assertNotSame(x.getIV(), z.getIV());
        
        assertNotSame(y.getIV(), z.getIV());
        
        // correct type of term identifier was assigned.
        assertTrue(x.getIV().isURI());
        assertTrue(y.getIV().isURI());
        assertTrue(z.getIV().isLiteral());
        
        // reverse lookup is consistent with the assigned term identifiers.
        assertEquals(x,store.getTerm(x.getIV()));
        assertEquals(y,store.getTerm(y.getIV()));
        assertEquals(z,store.getTerm(z.getIV()));

        /*
         * re-adding the same term instances does not change their term
         * identifer assignments.
         */
        
        // add terms - lots of duplicates here.
        store.addTerms(new BigdataValue[] { x, y, x, z, y, z});

        assertEquals(_x, x.getIV());
        assertEquals(_y, y.getIV());
        assertEquals(_z, z.getIV());
        
        /*
         * verify that re-adding distinct term identifier instances having
         * the same data assigns the same term identifiers.
         */
        {

            final BigdataURI x1 = valueFactory.createURI("http://www.foo.org/x");
            final BigdataURI y1 = valueFactory.createURI("http://www.foo.org/y");
            final BigdataLiteral z1 = valueFactory.createLiteral("z");
            
            // add terms - lots of duplicates here.
            store.addTerms(new BigdataValue[] { x1, y1, x1, z1, y1, z1});

            // same term identifiers were assigned.
            assertEquals(_x, x1.getIV());
            assertEquals(_y, y1.getIV());
            assertEquals(_z, z1.getIV());

        }
        
    } finally {
        
        store.__tearDownUnitTest();
        
    }
    
}
 
Example 8
Source File: TestRDRHistory.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test whether the RDRHistory can handle statements that are added
 * and removed in the same commit.
 */
public void testPartiallyRedundantEvents() throws Exception {

    BigdataSailRepositoryConnection cxn = null;

    final BigdataSail sail = getSail(getProperties());

    try {

        sail.initialize();
        final BigdataSailRepository repo = new BigdataSailRepository(sail);
        cxn = (BigdataSailRepositoryConnection) repo.getConnection();

        final BigdataValueFactory vf = (BigdataValueFactory) sail
                .getValueFactory();
        final URI s = vf.createURI(":s");
        final URI p = vf.createURI(":p");
        final Literal o = vf.createLiteral("foo");
        final Literal bar = vf.createLiteral("bar");
        final BigdataStatement stmt = vf.createStatement(s, p, o);
        final BigdataStatement stmt2 = vf.createStatement(s, p, bar);
        final BigdataBNode sid = vf.createBNode(stmt);
        final BigdataBNode sid2 = vf.createBNode(stmt2);

        cxn.add(stmt);
        cxn.commit();

        assertEquals(1, cxn.getTripleStore().getAccessPath(sid, null, null).rangeCount(false));
        
        cxn.remove(stmt);
        cxn.add(stmt);
        cxn.add(stmt2);
        cxn.commit();

        assertEquals(1, cxn.getTripleStore().getAccessPath(sid, null, null).rangeCount(false));
        assertEquals(1, cxn.getTripleStore().getAccessPath(sid2, null, null).rangeCount(false));
        
        
    } finally {
        if (cxn != null)
            cxn.close();
        
        sail.__tearDownUnitTest();
    }
}
 
Example 9
Source File: TestReificationDoneRightEval.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
	 * Bootstrap test. The data are explicitly entered into the KB by hand. This
	 * makes it possible to test evaluation without having to fix the RDF data
	 * loader. The query is based on <code>rdf-02</code>.
	 */
    public void test_reificationDoneRight_00() throws Exception {

		final BigdataValueFactory vf = store.getValueFactory();

		final BigdataURI SAP = vf.createURI("http://example.com/SAP");
		final BigdataURI bought = vf.createURI("http://example.com/bought");
		final BigdataURI sybase = vf.createURI("http://example.com/sybase");
		final BigdataURI dcSource = vf.createURI(DCTermsVocabularyDecl.NAMESPACE+"source");
		final BigdataURI dcCreated = vf.createURI(DCTermsVocabularyDecl.NAMESPACE+"created");
		final BigdataURI newsSybase = vf.createURI("http://example.com/news/us-sybase");
		final BigdataLiteral createdDate = vf.createLiteral("2011-04-05T12:00:00Z",XSD.DATETIME);
		final BigdataURI g1 = vf.createURI("http://example.com/g1");

		// Add/resolve the terms against the lexicon.
		final BigdataValue[] terms = new BigdataValue[] { SAP, bought, sybase,
				dcSource, dcCreated, newsSybase, createdDate, g1 };

		final BigdataURI context = store.isQuads() ? g1 : null;
		
		store.addTerms(terms);
		
		// ground statement.
		final BigdataStatement s0 = vf.createStatement(SAP, bought, sybase, 
				context, StatementEnum.Explicit);
		
		// Setup blank node with SidIV for that Statement.
		final BigdataBNode s1 = vf.createBNode("s1");
		s1.setStatementIdentifier(true);
		final ISPO spo = new SPO(s0);//SAP.getIV(), bought.getIV(), sybase.getIV(),
//				null/* NO CONTEXT */, StatementEnum.Explicit);
		s1.setIV(new SidIV<BigdataBNode>(spo));

		// metadata statements.

		final BigdataStatement mds1 = vf.createStatement(s1, dcSource,
				newsSybase, context, StatementEnum.Explicit);

		final BigdataStatement mds2 = vf.createStatement(s1, dcCreated,
				createdDate, context, StatementEnum.Explicit);

		final ISPO[] stmts = new ISPO[] { new SPO(s0), new SPO(mds1), new SPO(mds2) };

		store.addStatements(stmts, stmts.length);

		/*
		 * Now that we have populated the database, we can go ahead and compile
		 * the query. (If we compile the query first then it will not find any
		 * matching lexical items.)
		 */

		final TestHelper h = new TestHelper(TEST_RESOURCE_PREFIX + "rdr-00", // testURI,
				TEST_RESOURCE_PREFIX + "rdr-02.rq",// queryFileURL
				TEST_RESOURCE_PREFIX + "empty.ttl",// dataFileURL
				TEST_RESOURCE_PREFIX + "rdr-02.srx"// resultFileURL
		);

		h.runTest();

    }
 
Example 10
Source File: TestLexAccessPatternEnum.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void test_FullyBound_pattern() {

        final MockTermIdFactory f = new MockTermIdFactory();
        
        final IConstant<?> iv = new Constant<IV>(f.newTermId());

        final BigdataValueFactory vf = BigdataValueFactoryImpl
                .getInstance(getName());

        final IConstant<?> value = new Constant<BigdataURI>(vf
                .createURI("http://www.bigdata.com"));

        final IVariableOrConstant<?>[] args = new IVariableOrConstant[] {
                value, // value
                iv, // iv
        };

        final LexPredicate p = new LexPredicate(args);

        assertEquals(LexAccessPatternEnum.FullyBound, LexAccessPatternEnum
                .valueOf(p));

    }
 
Example 11
Source File: FulltextSearchServiceFactory.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Convert an {@link IHit} into an {@link IBindingSet}.
 */
private IBindingSet newBindingSet(final IFulltextSearchHit<?> hit) {

   final BigdataValueFactory vf = BigdataValueFactoryImpl
         .getInstance(store.getLexiconRelation().getNamespace());

   /**
    * The searchResultTyppe determines the type to which we cast results
    */
   final BigdataValue val;
   switch (hit.getSearchResultType()) {
   case LITERAL:
      val = vf.createLiteral(hit.getRes());
      break;
   case URI:
   default:
      try {
         val = vf.createURI(hit.getRes());
      } catch (IllegalArgumentException e) {
         
         throw new FulltextSearchException(
               FulltextSearchException.TYPE_CAST_EXCEPTION 
               + ":" + hit.getRes());
      }
      break;
   }

   IBindingSet bs = new ListBindingSet();

   bs.set(vars[0], new Constant(DummyConstantNode.toDummyIV(val)));
   
   if (hit.getScore()!=null) {
      bs.set(vars[1], new Constant(new XSDNumericIV(hit.getScore())));
   }
   
   if (hit.getSnippet()!=null) {
      
      final BigdataLiteral litSnippet = 
         vf.createLiteral(hit.getSnippet());
      bs.set(vars[2], 
         new Constant(new Constant(
            DummyConstantNode.toDummyIV(
               (BigdataValue) litSnippet))));
   }
   
   final IBindingSet baseBs = hit.getIncomingBindings();
   final Iterator<IVariable> varIt = baseBs.vars();
   while (varIt.hasNext()) {

      final IVariable var = varIt.next();

      if (bs.isBound(var)) {
         throw new FulltextSearchException(
               "Illegal use of search service. Variable ?"
                     + var
                     + " must not be bound from outside. If you need to "
                     + " join on the variable, you may try nesting the"
                     + " SERVICE in a WITH block and join outside.");
      }

      bs.set(var, baseBs.get(var));

   }

   if (log.isTraceEnabled()) {
      log.trace(bs);
      log.trace(query.getClass());
      log.trace(((BigdataLiteral) query).getIV());
      log.trace(((BigdataLiteral) query).getIV().getClass());
   }

   return bs;

}
 
Example 12
Source File: TestLexAccessPatternEnum.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void test_ValueBound_pattern() {

        final BigdataValueFactory vf = BigdataValueFactoryImpl
                .getInstance(getName());

        final IConstant<?> value = new Constant<BigdataURI>(vf
                .createURI("http://www.bigdata.com"));

        final IVariableOrConstant<?>[] args = new IVariableOrConstant[] {
                value, // value
                Var.var(), // iv
        };

        final LexPredicate p = new LexPredicate(args);

        assertEquals(LexAccessPatternEnum.ValueBound, LexAccessPatternEnum
                .valueOf(p));

    }
 
Example 13
Source File: TestNativeDistinctFilter.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public JoinSetup(final String kbNamespace) {

            if (kbNamespace == null)
                throw new IllegalArgumentException();
            
            final Properties properties = new Properties();

            properties.setProperty(Journal.Options.BUFFER_MODE,
                    BufferMode.Transient.toString());
            
            jnl = new Journal(properties);

            // create the kb.
            final AbstractTripleStore kb = new LocalTripleStore(jnl,
                    kbNamespace, ITx.UNISOLATED, properties);

            kb.create();

            this.spoNamespace = kb.getSPORelation().getNamespace();

            // Setup the vocabulary.
            {
                final BigdataValueFactory vf = kb.getValueFactory();
                final String uriString = "http://bigdata.com/";
                final BigdataURI _knows = vf.asValue(FOAFVocabularyDecl.knows);
                final BigdataURI _brad = vf.createURI(uriString+"brad");
                final BigdataURI _john = vf.createURI(uriString+"john");
                final BigdataURI _fred = vf.createURI(uriString+"fred");
                final BigdataURI _mary = vf.createURI(uriString+"mary");
                final BigdataURI _paul = vf.createURI(uriString+"paul");
                final BigdataURI _leon = vf.createURI(uriString+"leon");
                final BigdataURI _luke = vf.createURI(uriString+"luke");

                final BigdataValue[] a = new BigdataValue[] {
                      _knows,//
                      _brad,
                      _john,
                      _fred,
                      _mary,
                      _paul,
                      _leon,
                      _luke
                };

                kb.getLexiconRelation()
                        .addTerms(a, a.length, false/* readOnly */);

                knows = _knows.getIV();
                brad = _brad.getIV();
                john = _john.getIV();
                fred = _fred.getIV();
                mary = _mary.getIV();
                paul = _paul.getIV();
                leon = _leon.getIV();
                luke = _luke.getIV();

            }

//            // data to insert (in key order for convenience).
//            final SPO[] a = {//
//                    new SPO(paul, knows, mary, StatementEnum.Explicit),// [0]
//                    new SPO(paul, knows, brad, StatementEnum.Explicit),// [1]
//                    
//                    new SPO(john, knows, mary, StatementEnum.Explicit),// [2]
//                    new SPO(john, knows, brad, StatementEnum.Explicit),// [3]
//                    
//                    new SPO(mary, knows, brad, StatementEnum.Explicit),// [4]
//                    
//                    new SPO(brad, knows, fred, StatementEnum.Explicit),// [5]
//                    new SPO(brad, knows, leon, StatementEnum.Explicit),// [6]
//            };
//
//            // insert data (the records are not pre-sorted).
//            kb.addStatements(a, a.length);
//
//            // Do commit since not scale-out.
//            jnl.commit();

        }
 
Example 14
Source File: TestEncodeDecodePackedLongIVs.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
public void testRoundTripAndCompareCompressedTimestamp() throws Exception {
    
    // namespaces should never be reused in test suites.
    final BigdataValueFactory vf = BigdataValueFactoryImpl.getInstance(getName() + UUID.randomUUID());

    final CompressedTimestampExtension<BigdataValue> ext = 
        new CompressedTimestampExtension<BigdataValue>(
            new IDatatypeURIResolver() {
                  @Override
                  public BigdataURI resolve(final URI uri) {
                     final BigdataURI buri = vf.createURI(uri.stringValue());
                     buri.setIV(newTermId(VTE.URI));
                     return buri;
                  }
            });

    // we'll create a permutation over all values above
    final BigdataLiteral[] dt = {
         vf.createLiteral("0", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("100", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("101", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("103", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1010", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1011", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1012", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1013", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1014", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1015", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1016", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1017", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1018", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1019", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1020", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1021", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1022", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1023", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1024", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1025", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1026", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("10000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("10010", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("10100", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("11000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("100000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("100001", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1000000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("10000000", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         
         // from here: some realistic timestamp (up to year 9999)
         vf.createLiteral("1446203550", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1446203560", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1446203570", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1446203580", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1446203590", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1446203600", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1448881949", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("1480504349", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("2553419549", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("2869038749", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("3500190749", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("4131256349", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("7286929949", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("16754037149", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("32532491549", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("127203390749", CompressedTimestampExtension.COMPRESSED_TIMESTAMP),
         vf.createLiteral("253399576349", CompressedTimestampExtension.COMPRESSED_TIMESTAMP)
    };

    final IV<?, ?>[] e = new IV[dt.length];
    for (int i = 0; i < dt.length; i++) {
        e[i] = ext.createIV(dt[i]);
     }
    
    for (int i = 0; i < e.length; i++) {
        final BigdataValue val = ext.asValue((LiteralExtensionIV) e[i], vf);
        
        // verify val has been correctly round-tripped
          if (log.isInfoEnabled())
              log.info(val);
      }
    
     doEncodeDecodeTest(e);
     doComparatorTest(e);
     
}
 
Example 15
Source File: TestASTBottomUpOptimizer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test when <code>?v</code> is bound in the input {@link IBindingSet}[]. In
 * this case we can not rewrite the filter.
 * 
 * <pre>
 * PREFIX : <http://example/>
 * SELECT ?v
 * { :x :p ?v . { FILTER(?v = "x") } }
 * </pre>
 * 
 * @throws MalformedQueryException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void test_bottomUpOptimizer_filter_nested_2_withBindings()
        throws MalformedQueryException {

    final String queryStr = "" + //
            "PREFIX : <http://example/>\n" + //
            "SELECT ?v \n" +//
            "{ :x :p ?v . { FILTER(?v = \"x\") } }";
    
    /*
     * Add the Values used in the query to the lexicon. This makes it
     * possible for us to explicitly construct the expected AST and
     * the verify it using equals().
     */
    final BigdataValueFactory f = store.getValueFactory();
    final BigdataURI x = f.createURI("http://example/x");
    final BigdataURI p = f.createURI("http://example/p");
    final BigdataValue[] values = new BigdataValue[] { x, p };
    store.getLexiconRelation()
            .addTerms(values, values.length, false/* readOnly */);

    final ASTContainer astContainer = new Bigdata2ASTSPARQLParser()
            .parseQuery2(queryStr, baseURI);

    final AST2BOpContext context = new AST2BOpContext(astContainer, store);

    QueryRoot queryRoot = astContainer.getOriginalAST();
    
    final QueryRoot expected = BOpUtility.deepCopy(queryRoot);

    /*
     * A single solution with [v] bound. The value of the binding does not
     * matter. The presence of the binding is what is critical.  Since [v]
     * is bound in the source solutions we can not eliminate the filter.
     */
    final IBindingSet[] bindingSets = new IBindingSet[] {
            new ListBindingSet(
            new IVariable[] { Var.var("v") },
            new IConstant[] { new Constant(x.getIV()) })
    };
    
    Set<IVariable<?>> globallyScopedVars = new HashSet<IVariable<?>>();
    globallyScopedVars.add(Var.var("v"));

    context.setSolutionSetStats(SolutionSetStatserator.get(bindingSets));
    context.setGloballyScopedVariables(globallyScopedVars);
    
    queryRoot = 
       (QueryRoot) new ASTBottomUpOptimizer().optimize(
          context, new QueryNodeWithBindingSet(queryRoot, bindingSets))
          .getQueryNode();

    diff(expected, queryRoot);

}
 
Example 16
Source File: TestInlineURIs.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testMultipurposeIDNamespace() throws Exception {
      
      final Properties props = new Properties(getProperties());
      
      props.setProperty(AbstractTripleStore.Options.VOCABULARY_CLASS, 
              CustomVocab.class.getName());
      props.setProperty(AbstractTripleStore.Options.INLINE_URI_FACTORY_CLASS, 
              MultipurposeInlineIDFactory.class.getName());
      
      /*
       * The bigdata store, backed by a temporary journal file.
       */
final AbstractTripleStore store = getStore(props);

try {

	final BigdataValueFactory vf = store.getValueFactory();

	final BigdataURI uri1 = vf.createURI(CUSTOM_NAMESPACE + UUID.randomUUID().toString());
	final BigdataURI uri2 = vf.createURI(CUSTOM_NAMESPACE + "1");
	final BigdataURI uri3 = vf.createURI(CUSTOM_NAMESPACE + Short.MAX_VALUE);
	final BigdataURI uri4 = vf.createURI(CUSTOM_NAMESPACE + Integer.MAX_VALUE);
	final BigdataURI uri5 = vf.createURI(CUSTOM_NAMESPACE + Long.MAX_VALUE);
	final BigdataURI uri6 = vf.createURI(CUSTOM_NAMESPACE + "2.3");
	final BigdataURI uri7 = vf.createURI(CUSTOM_NAMESPACE + "foo");

	{
		final StatementBuffer<BigdataStatement> sb = new StatementBuffer<BigdataStatement>(store,
				10/* capacity */);
		sb.add(uri1, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri2, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri3, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri4, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri5, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri6, RDF.TYPE, RDFS.RESOURCE);
		sb.add(uri7, RDF.TYPE, RDFS.RESOURCE);
		sb.flush();
		store.commit();

		if (log.isDebugEnabled())
			log.debug(store.dumpStore());
	}

	for (BigdataURI uri : new BigdataURI[] { uri1, uri2, uri3, uri4, uri5, uri6, uri7 }) {

		assertTrue(uri.getIV().isInline());
		
	}
	
	assertEquals(DTE.UUID, uri1.getIV().getDTE());
	assertEquals(DTE.XSDByte, uri2.getIV().getDTE());
	assertEquals(DTE.XSDShort, uri3.getIV().getDTE());
	assertEquals(DTE.XSDInt, uri4.getIV().getDTE());
	assertEquals(DTE.XSDLong, uri5.getIV().getDTE());
	assertEquals(DTE.XSDDouble, uri6.getIV().getDTE());
	assertEquals(DTE.XSDString, uri7.getIV().getDTE());

} finally {
	store.__tearDownUnitTest();
}
      
  }
 
Example 17
Source File: TestASTBottomUpOptimizer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Slight variation on the structure of the query in the test above which
 * should not be recognized as a badly designed left join.
 * 
 * @throws MalformedQueryException
 */
public void test_wellDesigned03() throws MalformedQueryException {

    final String queryStr = "" + //
            "PREFIX : <http://example/>\n" + //
            "SELECT * \n" + //
            "{ \n" + //
            "    ?X  :name \"paul\" . \n" + //
            "    OPTIONAL {?X :name \"george\" } OPTIONAL { ?X :email ?Z } \n" + //
            "}"//
            ;

    /*
     * Add the Values used in the query to the lexicon. This makes it
     * possible for us to explicitly construct the expected AST and
     * the verify it using equals().
     */
    final BigdataValueFactory f = store.getValueFactory();
    final BigdataURI name = f.createURI("http://example/name");
    final BigdataURI email = f.createURI("http://example/email");
    final BigdataLiteral paul = f.createLiteral("paul");
    final BigdataLiteral george = f.createLiteral("george");
    final BigdataValue[] values = new BigdataValue[] { name, email, paul,
            george };
    store.getLexiconRelation()
            .addTerms(values, values.length, false/* readOnly */);

    final ASTContainer astContainer = new Bigdata2ASTSPARQLParser()
            .parseQuery2(queryStr, baseURI);

    final AST2BOpContext context = new AST2BOpContext(astContainer, store);

    QueryRoot queryRoot = astContainer.getOriginalAST();
    
    queryRoot = (QueryRoot) new ASTWildcardProjectionOptimizer().optimize(
            context, new QueryNodeWithBindingSet(queryRoot, null)).
            getQueryNode();

    final QueryRoot expected = BOpUtility.deepCopy(queryRoot); 
    
    queryRoot = (QueryRoot) new ASTBottomUpOptimizer().optimize(
            context, new QueryNodeWithBindingSet(queryRoot, null)).
            getQueryNode();

    // Verify NO transform.
    assertEquals(expected, queryRoot);
    
}
 
Example 18
Source File: TestInlineURIs.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testCustomUUIDNamespace() throws Exception {
      
      final Properties props = new Properties(getProperties());
      
      props.setProperty(AbstractTripleStore.Options.VOCABULARY_CLASS, 
              CustomVocab.class.getName());
      props.setProperty(AbstractTripleStore.Options.INLINE_URI_FACTORY_CLASS, 
              CustomInlineURIFactory.class.getName());
      
      /*
       * The bigdata store, backed by a temporary journal file.
       */
      final AbstractTripleStore store = getStore(props);
 	
try {
      
              final BigdataValueFactory vf = store.getValueFactory();

              final BigdataURI uri1 = vf.createURI(CUSTOM_NAMESPACE + UUID.randomUUID().toString());
              final BigdataURI uri2 = vf.createURI(CUSTOM_NAMESPACE + UUID.randomUUID().toString());
              final BigdataURI uri3 = vf.createURI(CUSTOM_NAMESPACE + "foo");
  
  			final StatementBuffer<BigdataStatement> sb = new StatementBuffer<BigdataStatement>(store, 10/* capacity */);

  			sb.add(uri1, RDF.TYPE, XSD.UUID);
              sb.add(uri2, RDF.TYPE, XSD.UUID);
              sb.add(uri3, RDF.TYPE, XSD.UUID);
              sb.flush();
              store.commit();
              
              if (log.isDebugEnabled())
                  log.debug(store.dumpStore());

              assertTrue(uri1.getIV().isInline());
              assertTrue(uri2.getIV().isInline());
              assertFalse(uri3.getIV().isInline());
              
      } finally {
          store.__tearDownUnitTest();
      }
      
  }
 
Example 19
Source File: TestASTBottomUpOptimizer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * A variant of {@link #test_bottomUpOptimizer_nested_optionals_1()} where
 * there is a binding for <code>v</code> in each exogenous solutions. This
 * turns <code>v</code> into a "known" bound variable. At that point we no
 * longer need to rewrite the query in order to have the correct evaluation
 * semantics.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void test_bottomUpOptimizer_nested_optionals_1_correctRejection()
        throws MalformedQueryException {

    final String queryStr = "" + //
            "PREFIX : <http://example/>\n" + //
            "SELECT * \n" + //
            "{ \n" + //
            "    :x1 :p ?v . \n" + //
            "    OPTIONAL {" +
            "      :x3 :q ?w . \n" + //
            "      OPTIONAL { :x2 :p ?v  } \n" + //
            "    } \n" + //
            "}"//
    ;

    /*
     * Add the Values used in the query to the lexicon. This makes it
     * possible for us to explicitly construct the expected AST and
     * the verify it using equals().
     */
    final BigdataValueFactory f = store.getValueFactory();
    final BigdataURI x1 = f.createURI("http://example/x1");
    final BigdataURI x2 = f.createURI("http://example/x2");
    final BigdataURI x3 = f.createURI("http://example/x3");
    final BigdataURI p = f.createURI("http://example/p");
    final BigdataURI q = f.createURI("http://example/q");
    final BigdataURI c1 = f.createURI("http://example/c1");
    final BigdataURI c2 = f.createURI("http://example/c2");
    final BigdataValue[] values = new BigdataValue[] { x1, x2, x3, p, q, c1, c2 };
    store.getLexiconRelation()
            .addTerms(values, values.length, false/* readOnly */);

    final ASTContainer astContainer = new Bigdata2ASTSPARQLParser()
            .parseQuery2(queryStr, baseURI);

    final AST2BOpContext context = new AST2BOpContext(astContainer, store);

    final IVariable<?> v = Var.var("v");
    
    final IBindingSet[] bindingSets = new IBindingSet[] {
            new ListBindingSet(//
                    new IVariable[]{v},//
                    new IConstant[]{new Constant(c1.getIV())}//
                    ),//
            new ListBindingSet(//
                    new IVariable[]{v},//
                    new IConstant[]{new Constant(c1.getIV())}//
                    )
    };
    
    QueryRoot queryRoot = astContainer.getOriginalAST();
    
    context.setSolutionSetStats(SolutionSetStatserator.get(bindingSets));
    
    queryRoot = (QueryRoot) new ASTWildcardProjectionOptimizer().optimize(
            context, new QueryNodeWithBindingSet(queryRoot, bindingSets)).
            getQueryNode();

    queryRoot = (QueryRoot) new ASTBottomUpOptimizer().optimize(
            context, new QueryNodeWithBindingSet(queryRoot, bindingSets)).
            getQueryNode();

    assertNull("should not have rewritten the query",
            queryRoot.getNamedSubqueries());

}
 
Example 20
Source File: TestEncodeDecodeKeys.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Unit test for the {@link ColorsEnumExtension}.
 */
public void test_encodeDecodeColor() {
    
    final BigdataValueFactory vf = BigdataValueFactoryImpl.getInstance("test");
    
    final ColorsEnumExtension<BigdataValue> ext = 
        new ColorsEnumExtension<BigdataValue>(new IDatatypeURIResolver() {
        public BigdataURI resolve(URI uri) {
            final BigdataURI buri = vf.createURI(uri.stringValue());
            buri.setIV(newTermId(VTE.URI));
            return buri;
        }
    });
    
    final List<IV<?, ?>> a = new LinkedList<IV<?, ?>>();

    for (Color c : Color.values()) {
    
        a.add(ext.createIV(new LiteralImpl(c.name(),
                ColorsEnumExtension.COLOR)));
        
    }

    final IV<?, ?>[] e = a.toArray(new IV[0]);

    doEncodeDecodeTest(e);

    doComparatorTest(e);
    
}