public class SampleBlazegraphBlueprintsEmbedded {
	
	protected static final Logger log = Logger.getLogger(SampleBlazegraphBlueprintsEmbedded.class);
	private static final String journalFile = "/tmp/testJournal-" + System.currentTimeMillis()
			+ ".jnl";
	
	public static void main(String[] args) throws Exception {
		
			final File f = new File(journalFile);				
			
			//Make sure were starting with a clean file.
			f.delete();

			final BigdataGraph g = BigdataGraphFactory.create(journalFile);
			
			final InputStream is = SampleBlazegraphBlueprintsEmbedded.class
					.getClassLoader().getResourceAsStream("graph-example-1.xml");
			try {
				
				GraphMLReader.inputGraph(g, is);
				
			} finally {
				is.close();
			}
			
			try {
	
				for (final Vertex v : g.getVertices()) {
					log.info(v);
				}
				for (final Edge e : g.getEdges()) {
					log.info(e);
				}
				
			} finally  {
				
				g.shutdown();	
				
				f.delete();
				
			}
			
	}
	
} public class SampleBlazegraphBlueprintsRemote {
	
	public static final Logger log = Logger.getLogger(SampleBlazegraphBlueprintsRemote.class);

    public static final String serviceURL = "http://localhost:9999/bigdata/sparql";

	public static void main(String[] args) throws Exception {
		
		final BigdataGraph graph = new BigdataGraphClient(SampleBlazegraphBlueprintsRemote.serviceURL);
		
		try{
		
			final InputStream is = SampleBlazegraphBlueprintsRemote.class.getClassLoader().getResourceAsStream("graph-example-1.xml");
			final Path file = Files.createTempFile("graph-example-1.xml", "tmp");
			try{
				Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
				graph.loadGraphML(file.toString());
			} finally {					
				Files.delete(file);	
				is.close();
			}
			
			for (final Vertex v : graph.getVertices()) {
				log.info(v);
			}
			for (final Edge e : graph.getEdges()) {
				log.info(e);
			}
				
		} finally {
			graph.shutdown();
		}
	}
} public class JournalExample {

    public static void main(String[] args) {

        final Properties properties = new Properties();

        properties.setProperty(Journal.Options.FILE, "testJournal.jnl");
        
        Journal store = new Journal(properties);

        try {

            /*
             * Register the index. There are a lot of options for the B+Tree,
             * but you only need to specify the index name and the UUID for the
             * index. Each store can hold multiple named indices.
             */
            {
                
                final IndexMetadata indexMetadata = new IndexMetadata(
                        "testIndex", UUID.randomUUID());

                store.registerIndex(indexMetadata);
                
                // commit the store so the B+Tree can be found on restart.
                store.commit();
                
            }

            /*
             * Lookup the unisolated B+Tree. This is the mutable B+Tree view.
             * 
             * While the temporary store does not differentiate between mutable
             * and read-only views, the Journal and the scale-out architecture
             * do.
             */
            {
            
                final BTree mutableBTree = store.getIndex("testIndex");

                // lookup the tuple (not found).
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

                // add a tuple
                mutableBTree.insert("hello", "world");

                // lookup the tuple
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

                // update the tuple
                mutableBTree.insert("hello", "again");

                // lookup the new value
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

                /*
                 * The tuple is not visible on the read-committed view until the
                 * next commit.
                 */
                {

                    final ILocalBTreeView readOnlyBTree = store.getIndex(
                            "testIndex", store.getLastCommitTime());

                    // lookup the tuple (not found).
                    System.err.println("tuple: "
                            + readOnlyBTree.lookup("hello"));

                }

                // abort (discard writes since the last commit).
                store.abort();
                
            }
            
            // Verify writes are not visible on the mutable B+Tree.
            {
                
                final BTree mutableBTree = store.getIndex("testIndex");

                // lookup the tuple (not found).
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

            }

            // Show writes visible after a commit.
            {
                
                final BTree mutableBTree = store.getIndex("testIndex");

                // lookup the tuple (not found).
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

                // add a tuple
                mutableBTree.insert("hello", "world2");

                // lookup the tuple
                System.err.println("tuple: " + mutableBTree.lookup("hello"));

                // update the tuple
                mutableBTree.insert("hello", "again2");

                // lookup the new value
                System.err.println("tuple: " + mutableBTree.lookup("hello"));
                
                // commit the changes.
                store.commit();
                
            }

            // Show that the changes were restart safe.
            {
                
                // close the journal.
                store.close();
                System.out.println("Store closed.");
                
                // re-open the journal.
                store = new Journal(properties);
                System.out.println("Store re-opened.");

                // lookup the B+Tree.
                final BTree mutableBTree = store.getIndex("testIndex");
                
                // lookup the tuple
                System.err.println("tuple: " + mutableBTree.lookup("hello"));
    
            }
            
        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }

}
 public class JournalReadOnlyTxExample {
	
	private static final Logger log = Logger.getLogger(JournalReadOnlyTxExample.class);

    public static void main(String[] args) throws IOException {

    	// enable logging
    	log.setLevel(Level.INFO);
    	
        final Properties properties = new Properties();

		final File tmpDir = new File(System.getProperty("java.io.tmpdir"));

		if (tmpDir.exists()) {
			tmpDir.mkdirs();
		}

		final File journalFile = new File(tmpDir,
				JournalReadOnlyTxExample.class.getSimpleName() + "jnl");

		if (journalFile.exists()) {
			if (!journalFile.delete()) {
				throw new IOException("Could not delete old file: "
						+ journalFile);
			}
		}

		// this example uses the RWStore, but it also works with the WORM.
		properties.setProperty(Journal.Options.BUFFER_MODE, //
				BufferMode.DiskRW.toString()
//				BufferMode.DiskWORM.toString()
				);

		properties.setProperty(Journal.Options.FILE, journalFile
				.getCanonicalPath());

		/*
		 * Immediate recycling of committed data unless protected by a read-lock
		 * (ZERO milliseconds of retained data associated historical commit
		 * points).
		 * 
		 * Note: this is the default behavior for the RWStore and the bigdata
		 * federation.
		 */
		properties.setProperty(
				AbstractTransactionService.Options.MIN_RELEASE_AGE, "0");

		Journal store = new Journal(properties);

		// The name of the index used in this example.
		final String name = "testIndex";
		
		try {

            /*
             * Register the index. Each store can hold multiple named indices.
             */
        	final long commitTime1;
            {
                
                final IndexMetadata indexMetadata = new IndexMetadata(
                        name, UUID.randomUUID());

                // Note: isolatable indices are NOT required for read-only txs.
                indexMetadata.setIsolatable(false);
                
                // register the index.
                store.registerIndex(indexMetadata);
                
                // commit the store so the B+Tree can be found on restart.
                commitTime1 = store.commit();
                
            }

            /*
             * Write data using the UNISOLATED view of the B+Tree.
             */
            {

                final BTree unisolatedBTree = store.getIndex(name);

                writeSet1(unisolatedBTree);

                verifyWriteSet1(unisolatedBTree);

                /*
                 * Note: The unisolated index has not been committed yet.
                 */
                
            }

			/*
			 * The data are not visible on read-only B+Tree reading from the
			 * most recent commit point.
			 */
			{

				final long tx1 = store.newTx(ITx.READ_COMMITTED);

				try {

					final BTree readOnlyBTree = (BTree) store.getIndex(name,
							tx1);

					verifyWriteSetNotFound(readOnlyBTree);

				} finally {

					store.abort(tx1);

            	}

            }

            // Commit the write set for the UNISOLATED index.
            final long commitTime2 = store.commit();

            // Verify writes are now visible on the UNISOLATED B+Tree.
            {
                
                final BTree unisolatedBTree = store.getIndex(name);

                verifyWriteSet1(unisolatedBTree);

            }
            
			// Show that the changes were restart safe.
			if (true) {

				// close the journal.
				store.close();
				log.info("Store closed.");

				// re-open the journal.
				store = new Journal(properties);
				log.info("Store re-opened.");

				// lookup the B+Tree.
				final BTree unisolatedBTree = store.getIndex(name);

				verifyWriteSet1(unisolatedBTree);

			}

            /*
             * Open a read-only transaction on the last commit time.
             * 
             * Note: If you use store.getLastCommitTime() here instead you will
             * have a read-historical view of the same data, but that view is
             * NOT protected by a read lock. Running the example with this
             * change will cause the RWStore to throw out an exception since the
             * writes will have overwritten the historical data by the time you
             * try to read it.
             */
			// Obtaining a tx here protects against recycling.
            final long tx2 = store.newTx(ITx.READ_COMMITTED);
            // Using a historical read w/o a tx does NOT protect against recycling.
//            final long tx2 = store.getLastCommitTime();
            try {

                // lookup the UNISOLATED B+Tree.
                final BTree unisolatedBTree = store.getIndex(name);

                // First, remove the existing tuples.
                removeWriteSet(unisolatedBTree);

                store.commit();
                
				/*
				 * Write some new records on the unisolated index.
				 */
				writeSet2(unisolatedBTree);

				store.commit();

                /*
                 * Verify that the read-only view has not seen those changes.
                 * 
                 * Note: If you used a historical read rather than a read-only
                 * tx then this is where the RWStore will throw out an exception
                 * because the recycled has reused some of the records
                 * associated with the historical revision of the BTree.
                 */
				{
					final BTree readOnlyBTree = (BTree) store.getIndex(name, tx2);

					verifyWriteSet1(readOnlyBTree);
				}

			} finally {
				// release that read-only transaction.
				store.abort(tx2);
            }
            
			log.info("Done.");
			
        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }

	/**
	 * Write a set of tuples having keys in [0:1000) and values equal to the
	 * keys.
	 */
	private static void writeSet1(final BTree btree) {

		log.info("");
		
		for (int i = 0; i < 1000; i++) {

			btree.insert(i, i);

		}

	}

	/**
	 * Write a set of tuples having keys in [0:1000) and values equal to the
	 * twice the numerical value of the keys.
	 * 
	 * @param btree
	 */
	private static void writeSet2(final BTree btree) {

		log.info("");

		for (int i = 0; i < 1000; i++) {

			btree.insert(i, i * 2);

		}

	}

	/**
	 * Verify the set of tuples written by {@link #writeSet1(BTree)}.
	 */
	private static void verifyWriteSet1(final BTree btree) {

		log.info("");

		for (int i = 0; i < 1000; i++) {

			final Object val = btree.lookup(i);

			if (!Integer.valueOf(i).equals(val)) {

				throw new RuntimeException("Not found: key=" + i+", val="+val);

			}

		}

	}

	/**
	 * Verify that the write set is not found (no keys in [0:1000)).
	 */
	private static void verifyWriteSetNotFound(final BTree btree) {

		log.info("");

		for (int i = 0; i < 1000; i++) {

			if (btree.contains(i)) {

				throw new RuntimeException("Not expecting: key=" + i);

			}

		}

	}
	
	/**
	 * Delete the tuples written by {@link #writeSet(BTree)} or
	 * {@link #writeSet2(BTree).
	 */
	private static void removeWriteSet(final BTree btree) {

		log.info("");

		for (int i = 0; i < 1000; i++) {

			if (btree.remove(i) == null) {

				throw new RuntimeException("Not found: key=" + i);

			}

		}

	}

}
 public class JournalTxExample {

    public static void main(String[] args) {

        final Properties properties = new Properties();

        properties.setProperty(Journal.Options.FILE, "testJournal.jnl");
        
        Journal store = new Journal(properties);

        try {

            /*
             * Register the index. Each store can hold multiple named indices.
             */
            {
                
                final IndexMetadata indexMetadata = new IndexMetadata(
                        "testIndex", UUID.randomUUID());

                /*
                 * Note: You MUST explicitly enable transaction processing for a
                 * B+Tree when you register the index. Transaction processing
                 * requires that the index maintain both per-tuple delete
                 * markers and per-tuple version identifiers. While scale-out
                 * indices always always maintain per-tuple delete markers,
                 * neither local nor scale-out indices maintain the per-tuple
                 * version identifiers by default.
                 */
                indexMetadata.setIsolatable(true);
                
                // register the index.
                store.registerIndex(indexMetadata);
                
                // commit the store so the B+Tree can be found on restart.
                store.commit();
                
            }

            // start a read-write transaction.
            final long txid = store.newTx(ITx.UNISOLATED);

            /*
             * Lookup a view of the B+Tree isolated by that transaction. This
             * will be a mutable view since we requested a read-write
             * transaction.
             */
            {
            
                final IIndex isolatedBTree = store.getIndex("testIndex", txid);

                // lookup the tuple (not found).
                System.err.println("tuple: " + isolatedBTree.lookup("hello"));

                // add a tuple
                isolatedBTree.insert("hello", "world");

                // lookup the tuple
                System.err.println("tuple: " + isolatedBTree.lookup("hello"));

                // update the tuple
                isolatedBTree.insert("hello", "again");

                // lookup the new value
                System.err.println("tuple: " + isolatedBTree.lookup("hello"));

            }

            /*
             * The tuple is not visible on unisolated B+Tree until we commit the
             * transaction.
             */
            {

                final BTree unisolatedBTree = store.getIndex("testIndex");

                final Object val = unisolatedBTree.lookup("hello");
                
                // lookup the tuple (not found).
                System.err.println("tuple: " + val);
                
                assert val == null;

            }

            // Commit the transaction.
            store.commit(txid);

            // Verify writes are now visible on the mutable B+Tree.
            {
                
                final BTree mutableBTree = store.getIndex("testIndex");

                final Object val = mutableBTree.lookup("hello");
                
                // lookup the tuple (found).
                System.err.println("tuple: " + val);
                
                assert "again".equals(val);

            }

            // Show that the changes were restart safe.
            {
                
                // close the journal.
                store.close();
                System.out.println("Store closed.");
                
                // re-open the journal.
                store = new Journal(properties);
                System.out.println("Store re-opened.");

                // lookup the B+Tree.
                final BTree mutableBTree = store.getIndex("testIndex");

                // lookup the tuple.
                final Object val = mutableBTree.lookup("hello");
                
                // lookup the tuple (found).
                System.err.println("tuple: " + val);
                
                assert "again".equals(val);
    
            }
            
        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }

}
 public class ReadWriteIndexExample {

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {

        final Properties properties = new Properties();

        properties.setProperty(Journal.Options.FILE, "testJournal.jnl");
        
        final Journal store = new Journal(properties);

        try {

            /*
             * Register the index. There are a lot of options for the B+Tree,
             * but you only need to specify the index name and the UUID for the
             * index. Each store can hold multiple named indices.
             */
            {
                
                final IndexMetadata indexMetadata = new IndexMetadata(
                        "testIndex", UUID.randomUUID());

                store.registerIndex(indexMetadata);
                
                // commit the store so the index is on record.
                store.commit();
                
            }

            /*
             * Demonstrate that the each view has read/write concurrency against
             * the mutable B+Tree.
             */
            final List<Callable<Void>> tasks = new LinkedList<Callable<Void>>();

            final UnisolatedReadWriteIndex btree = new UnisolatedReadWriteIndex(
                    store.getIndex("testIndex"));

            final int nops = 50000;

            tasks.add(new ReadWriteTask(btree, nops));

            tasks.add(new ReadWriteTask(btree, nops));

            tasks.add(new ReadWriteTask(btree, nops));

            // run tasks on the journal's executor service.
            final List<Future<Void>> futures = store.getExecutorService()
                    .invokeAll(tasks);

            for(final Future<Void> future : futures) {
                
                // check for errors.
                future.get();
                
            }
            
            // commit the store.
            store.commit();
            
            // show #of operations executed and #of tuples in the B+Tree.
            System.out.println("nops=" + (nops * tasks.size())
                    + ", rangeCount=" + btree.rangeCount());

            System.out.println(new Date().toString());

        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }
    
    /**
     * Task performs random CRUD operations, range counts, and range scans.
     * 
     * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan
     *         Thompson</a>
     * @version $Id$
     */
    static class ReadWriteTask implements Callable<Void> {

        final IIndex ndx;
        final int nops;
        final Random r = new Random();
        
        // #of distinct keys for this task.
        final int range = 1000;

        /**
         * 
         * @param ndx
         *            A B+Tree which serializes write operations but permits
         *            concurrent read operations when no write operations are
         *            running.
         * @param nops
         *            The #of operations to execute against that {@link BTree}.
         */
        public ReadWriteTask(final UnisolatedReadWriteIndex ndx, final int nops) {
            
            /*
             * Obtain two views onto the same
             */
            this.ndx = ndx;

            this.nops = nops;

        }
        
        public Void call() throws Exception {
            
            for(int i=0; i<nops; i++) {
             
                switch (r.nextInt(4)) {
                case 0:
                    /*
                     * write on the index, inserting or updating the value for
                     * the key.
                     */
                    ndx.insert("key#" + r.nextInt(range), r.nextLong());
                    break;
                case 1:
                    /* write on the index, removing the key iff found. */
                    ndx.remove("key#" + r.nextInt(range));
                    break;
                case 2:
                    /*
                     * lookup a key in the index.
                     */
                    ndx.lookup("key#"+r.nextInt(range));
                    break;
                case 3:
                    /*
                     * range count the index.
                     */
                    ndx.rangeCount();
                    break;
                case 4: {
                    /*
                     * run a range iterator over the index.
                     */
                    final Iterator<ITuple<?>> itr = ndx.rangeIterator();
                    while(itr.hasNext()) {
                        itr.next();
                    }
                    break;
                    }
                default:
                    throw new AssertionError("case not handled");
                }
                
            }
            
            // done.
            return null;
            
        }
        
    }

}
 public class ReadWriteIndexTxExample {

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {

        final Properties properties = new Properties();

        properties.setProperty(Journal.Options.FILE, "testJournal.jnl");
        
        final Journal store = new Journal(properties);

        try {

            /*
             * Register the index. Each store can hold multiple named indices.
             */
            {
                
                final IndexMetadata indexMetadata = new IndexMetadata(
                        "testIndex", UUID.randomUUID());

                /*
                 * Note: You MUST explicitly enable transaction processing for a
                 * B+Tree when you register the index. Transaction processing
                 * requires that the index maintain both per-tuple delete
                 * markers and per-tuple version identifiers. While scale-out
                 * indices always always maintain per-tuple delete markers,
                 * neither local nor scale-out indices maintain the per-tuple
                 * version identifiers by default.
                 */
                indexMetadata.setIsolatable(true);

                // register the index.
                store.registerIndex(indexMetadata);
                
                // commit the store so the index is on record.
                store.commit();
                
            }

            /*
             * Run a set of concurrent tasks. Each task executes within its own
             * transaction. Conflicts between the transactions are increasingly
             * likely as the #of transactions or the #of operations per
             * transaction increases. When there is a conflict, the transaction
             * for which the conflict was detected will be aborted when it tries
             * to commit.
             */
            final List<Callable<Void>> tasks = new LinkedList<Callable<Void>>();

            final int ntx = 30;
            final int nops = 10;
            
            for(int i=0; i<ntx; i++) {

                tasks.add(new ReadWriteTxTask(store, "testIndex", nops));
                
            }

            // run tasks on the journal's executor service.
            final List<Future<Void>> futures = store.getExecutorService()
                    .invokeAll(tasks);

            int i = 0;
            int nok = 0;
            for (final Future<Void> future : futures) {

                // check for errors.
                try {
                    future.get();
                    nok++;
                } catch (ExecutionException ex) {
                    if (InnerCause.isInnerCause(ex, ValidationError.class)) {
                        /*
                         * Normal exception. There was a conflict and one or the
                         * transactions could not be committed.
                         */
                        System.out
                                .println("Note: task["
                                        + i
                                        + "] could not be committed due to a write-write conflict.");
                    } else {
                        // Unexpected exception.
                        throw ex;
                    }
                }
                i++;
                
            }

            /*
             * Show #of transactions which committed successfully and the #of
             * transactions which were executed.
             */
            System.out.println("" + nok + " out of " + tasks.size()
                    + " transactions were committed successfully.");

            /*
             * Show the operations executed and #of tuples in the B+Tree.
             */
            System.out.println("nops=" + (nops * tasks.size())
                    + ", rangeCount="
                    + store.getIndex("testIndex").rangeCount());

            System.out.println(new Date().toString());

        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }
    
    /**
     * Task performs random CRUD operations, range counts, and range scans.
     * 
     * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan
     *         Thompson</a>
     * @version $Id$
     */
    static class ReadWriteTxTask implements Callable<Void> {

        final Journal jnl;
        final String indexName;
        final int nops;
        final Random r = new Random();
        
        // #of distinct keys for this task.
        final int range = 1000;

        /**
         * 
         * @param jnl
         *            The journal.
         * @param indexName
         *            The name of the index.
         * @param nops
         *            The #of operations to execute against that {@link BTree}.
         */
        public ReadWriteTxTask(final Journal jnl, final String indexName,
                final int nops) {

            this.jnl = jnl;
            this.indexName = indexName;
            this.nops = nops;

        }

        /**
         * Starts a read-write transaction, obtains a view of the B+Tree
         * isolated by the transaction, performs a series of operations on the
         * isolated view, and then commits the transaction.
         * <p>
         * Note: When multiple instances of this task are run concurrently it
         * becomes increasingly likely that a write-write conflict will be
         * detected when you attempt to commit the transaction, in which case
         * the commit(txid) will fail and an appropriate error will be thrown
         * out of the task.
         * 
         * @throws ValidationError
         *             if there is a write-write conflict during commit
         *             processing (the transaction write set conflicts with the
         *             write set of a concurrent transaction which has already
         *             successfully committed).
         * @throws Exception
         */
        public Void call() throws Exception {

            // Start a transaction.
            final long txid = jnl.newTx(ITx.UNISOLATED);

            try {

                /*
                 * Obtain a view of the index isolated by the transaction.
                 */
                final IIndex ndx = jnl.getIndex(indexName, txid);

                for (int i = 0; i < nops; i++) {

                    switch (r.nextInt(4)) {
                    case 0:
                        /*
                         * write on the index, inserting or updating the value
                         * for the key.
                         */
                        ndx.insert("key#" + r.nextInt(range), r.nextLong());
                        break;
                    case 1:
                        /* write on the index, removing the key iff found. */
                        ndx.remove("key#" + r.nextInt(range));
                        break;
                    case 2:
                        /*
                         * lookup a key in the index.
                         */
                        ndx.lookup("key#" + r.nextInt(range));
                        break;
                    case 3:
                        /*
                         * range count the index.
                         */
                        ndx.rangeCount();
                        break;
                    case 4: {
                        /*
                         * run a range iterator over the index.
                         */
                        final Iterator<ITuple<?>> itr = ndx.rangeIterator();
                        while (itr.hasNext()) {
                            itr.next();
                        }
                        break;
                    }
                    default:
                        throw new AssertionError("case not handled");
                    }

                }

            } catch (Throwable t) {

                jnl.abort(txid);

                throw new RuntimeException(t);
                
            }

            /*
             * Commit the transaction. if the commit fails, then the transaction
             * is aborted.
             */
            jnl.commit(txid);

            // done.
            return null;
            
        }
        
    }

}
 public class TempStoreExample {

    public static void main(String[] args) {

        final TemporaryStore store = new TemporaryStore();

        try {

            /*
             * Register the index. There are a lot of options for the B+Tree,
             * but you only need to specify the index name and the UUID for the
             * index. Each store can hold multiple named indices.
             */
            {
                final IndexMetadata indexMetadata = new IndexMetadata(
                        "testIndex", UUID.randomUUID());

                store.registerIndex(indexMetadata);
            }

            /*
             * Lookup the unisolated B+Tree. This is the mutable B+Tree view.
             * 
             * While the temporary store does not differentiate between mutable
             * and read-only views, the Journal and the scale-out architecture
             * do.
             */
            {
            
                final BTree btree = store.getIndex("testIndex", ITx.UNISOLATED);

                // lookup the tuple (not found).
                System.err.println("tuple: " + btree.lookup("hello"));

                // add a tuple
                btree.insert("hello", "world");

                // lookup the tuple
                System.err.println("tuple: " + btree.lookup("hello"));

                // update the tuple
                btree.insert("hello", "again");

                // lookup the new value
                System.err.println("tuple: " + btree.lookup("hello"));

            }

        } finally {

            // destroy the backing store.
            store.destroy();

        }

    }

}
 public class SampleBlazegraphCustomFunctionEmbedded {
	
	protected static final Logger log = Logger.getLogger(SampleBlazegraphCustomFunctionEmbedded.class);
	
	public static final String journalFile = "/tmp/blazegraph/test.jnl";
	
	/*
	 * Select all documents available to <http://www.example.com/John> 
	 */
	public static final String QUERY = "SELECT ?doc " + // 
			"{ ?doc rdf:type <http://www.example.com/Document> . " + //
			" filter(<http://www.example.com/validate>(<http://www.example.com/John>, ?doc)) . }";

	public static void main(String[] args) throws OpenRDFException, IOException {
		
		final Repository repo = createRepository();
		
		registerCustomFunction(repo);
			
		try{
			repo.initialize();
			
			/*
			 * Load data from resources 
			 * src/main/resources/data.n3
			 */
	
			Utils.loadDataFromResources(repo, "data.n3", "");
											
			final TupleQueryResult result = Utils.executeSelectQuery(repo, QUERY, QueryLanguage.SPARQL);
			
			try {
				while(result.hasNext()){
					
					BindingSet bs = result.next();
					log.info(bs);
					
				}
			} finally {
				result.close();
			}
		} finally {
			repo.shutDown();
		}
	}
	
	public static Repository createRepository(){
		
		final Properties props = new Properties();
		props.put(Options.BUFFER_MODE, BufferMode.DiskRW); 
		props.put(Options.FILE, journalFile); 
		final BigdataSail sail = new BigdataSail(props);
		final Repository repo = new BigdataSailRepository(sail);
		return repo;
		
	}
	
	public static void registerCustomFunction(final Repository repo){
		
		final URI myFunctionURI = new URIImpl("http://www.example.com/validate");
		
		final FunctionRegistry.Factory securityFactory = new FunctionRegistry.Factory() {

			public IValueExpression<? extends IV> create(
					BOpContextBase context, GlobalAnnotations globals,
					Map<String, Object> scalarValues,
					ValueExpressionNode... args) {
				
				
			      // Validate your argument(s)
			      FunctionRegistry.checkArgs(args, ValueExpressionNode.class, ValueExpressionNode.class);

			      // Turn them into physical (executable) bops
			      final IValueExpression<? extends IV> user =  AST2BOpUtility.toVE(context, globals, args[0]);
			      final IValueExpression<? extends IV> document = AST2BOpUtility.toVE(context, globals, args[1]);
						      
			     
			      final GlobalSecurityValidator securityValidator = new GlobalSecurityValidator(repo);			      
			     			      
			      // Return your custom function.
			      return new SecurityFilter(user, document, globals, securityValidator);

			}

		};		
		
		FunctionRegistry.add(myFunctionURI, securityFactory);
		
	}
} public class SampleBlazegraphCustomFunctionRemote {
	
	protected static final Logger log = Logger
			.getLogger(SampleBlazegraphCustomFunctionRemote.class);
	public static final String serviceURL = "http://localhost:9999/bigdata";
	
	/*
	 * Select all documents available to <http://www.example.com/John> 
	 */
	public static final String QUERY = "SELECT ?doc " + // 
			"{ ?doc rdf:type <http://www.example.com/Document> . " + //
			" filter(<http://www.example.com/validate>(<http://www.example.com/John>, ?doc)) . }";

	public static void main(String[] args) throws Exception {
		
		final String namespace = "test";
		
		final Properties journalProperties = new Properties();
        {
            journalProperties.setProperty(Journal.Options.BUFFER_MODE,
                    BufferMode.MemStore.name());
            
        }
			
		final RemoteRepositoryManager repo = new RemoteRepositoryManager(
				serviceURL , false /* useLBS */);
		
		repo.createRepository(namespace, journalProperties);
		
		try {

			/*
			 * Load data from file located in the resource folder
			 * src/main/resources/data.n3
			 */
			final String resource = "/data.n3";
			loadDataFromResource(repo, namespace, resource);

			// execute query
			final TupleQueryResult result = repo.getRepositoryForNamespace(namespace)
					.prepareTupleQuery(QUERY)
					.evaluate();
			
			//result processing
			try {
				while (result.hasNext()) {
					final BindingSet bs = result.next();
					log.info(bs);
				}
			} finally {
				result.close();
			}

		} finally {
			repo.close();
		}
		

	}
	

	/*
	 * Load data into a namespace.
	 */
	public static void loadDataFromResource(final RemoteRepositoryManager repo,
			final String namespace, final String resource) throws Exception {
		final InputStream is = SampleBlazegraphCustomFunctionRemote.class
				.getResourceAsStream(resource);
		if (is == null) {
			throw new IOException("Could not locate resource: " + resource);
		}
		try {
			repo.getRepositoryForNamespace(namespace).add(
					new RemoteRepository.AddOp(is, RDFFormat.N3));
		} finally {
			is.close();
		}
	}
	
	
	
} public class TestSample {

	public static void main(String[] args) throws OpenRDFException {
		
		final Logger log = Logger.getLogger(TestSample.class);
		
		final Properties props = new Properties();
	
		props.put(BigdataSail.Options.BUFFER_MODE, BufferMode.MemStore.toString());
		props.put(BigdataSail.Options.FILE, "/tmp/blazegraph/test.jnl");
		
		props.put(BigdataSail.Options.AXIOMS_CLASS, SampleAxioms.class.getName());
		props.put(BigdataSail.Options.VOCABULARY_CLASS, SampleVocab.class.getName());
		props.put(BigdataSail.Options.CLOSURE_CLASS, SampleClosure.class.getName());
		
		props.put(BigdataSail.Options.TRUTH_MAINTENANCE, "true");
		props.put(BigdataSail.Options.JUSTIFY, "true");

//		props.setProperty(BigdataSail.Options.FORWARD_CHAIN_RDF_TYPE_RDFS_RESOURCE, "true");
		
		// instantiate a sail
		final BigdataSail sail = new BigdataSail(props);
		final Repository repo = new BigdataSailRepository(sail);
		
		try{
			repo.initialize();
			
			final RepositoryConnection cxn = repo.getConnection();
			
			try {
				cxn.begin();
				try {
					
					final ValueFactory vf = sail.getValueFactory();
					
					final URI a = vf.createURI(SAMPLE.NAMESPACE+"a");
					final URI b = vf.createURI(SAMPLE.NAMESPACE+"b");
					final URI c = vf.createURI(SAMPLE.NAMESPACE+"c");
					final URI thing = vf.createURI(SAMPLE.NAMESPACE+"thing");
					final URI attribute = vf.createURI(SAMPLE.NAMESPACE+"attribute");
					final URI link = vf.createURI(SAMPLE.NAMESPACE+"link");
					final URI x = vf.createURI(SAMPLE.NAMESPACE+"x");
					final URI y = vf.createURI(SAMPLE.NAMESPACE+"y");
					
					final Literal foo = vf.createLiteral("foo");
					final Literal bar = vf.createLiteral("bar");
					
					cxn.add(a, RDF.TYPE, thing);
					cxn.add(a, SAMPLE.SIMILAR_TO, b);
					cxn.add(a, SAMPLE.SIMILAR_TO, c);
					
					// a and b are both rdf:type #thing
					cxn.add(b, RDF.TYPE, thing);
					// so a should pick up the literal attribute "foo"
					cxn.add(b, attribute, foo);
					// but not the link to x, since x is not a literal
					cxn.add(b, link, x);
					
					// c is not the same type as a, so a should not pick up any attributes,
					// even though they are marked as similar
					cxn.add(c, attribute, bar);
					cxn.add(c, link, y);
				
					cxn.commit();
					
					log.info("\n"+sail.getDatabase().dumpStore(true, true, false));
										
					log.info("'a' should pick up 'foo' " + cxn.hasStatement(a, attribute, foo, true));
					log.info("'a' should not pick up link to 'x' " + cxn.hasStatement(a, link, x, true));
					log.info("'a' should not pick up 'bar' " + cxn.hasStatement(a, attribute, bar, true));
					log.info("'a' should not pick up link to 'y' " + cxn.hasStatement(a, link, y, true));
					
					// now test truth maintenance
					
					// removing the similarity to b will cause a to lose "foo"
					cxn.remove(a, SAMPLE.SIMILAR_TO, b);
					// adding a common type between a and c will cause a to pick up "bar"
					cxn.add(c, RDF.TYPE, thing);
					
					cxn.commit();
					
					if (log.isInfoEnabled()) {
						log.info("\n"+sail.getDatabase().dumpStore(true, true, false));
					}
					
					log.info("'a' should have lost 'foo' " + cxn.hasStatement(a, attribute, foo, true));
					log.info("'a' should not pick up link to 'x' " + cxn.hasStatement(a, link, x, true));
					log.info("'a' should have picked up 'bar' " + cxn.hasStatement(a, attribute, bar, true));
					log.info("'a' should not pick up link to 'y' " + cxn.hasStatement(a, link, y, true));
					
				} catch (OpenRDFException ex) {
					cxn.rollback();
					throw ex;
				}
			} finally {
				// close the repository connection
				cxn.close();
			}
			
		} finally {
			repo.shutDown();
		}

	}

} public class SampleBlazegraphRDR {
	
	protected static final Logger log = Logger.getLogger(SampleBlazegraphRDR.class);
	private static final String serviceURL = "http://localhost:9999/bigdata";
	
	public static void main(String[] args) throws Exception  {
	
		final RemoteRepositoryManager repositoryManager = new RemoteRepositoryManager(serviceURL, false /*useLBS*/);
	
		try{	
		
			final String namespace = "namespaceRDR";
			final Properties properties = new Properties();
			properties.setProperty(Options.NAMESPACE, namespace);
			properties.setProperty(Options.STATEMENT_IDENTIFIERS, "true");
			
			if(!namespaceExists(namespace, repositoryManager)){
				log.info(String.format("Create namespace %s...", namespace));
				repositoryManager.createRepository(namespace, properties);
				log.info(String.format("Create namespace %s done", namespace));
			}
			
			final InputStream is = SampleBlazegraphRDR.class.getResourceAsStream("/rdr_test.ttl");
			try{
				repositoryManager.getRepositoryForNamespace(namespace).add(new AddOp(is, RDFFormat.forMIMEType("application/x-turtle-RDR")));
			} finally {
				is.close();
			}
			
			//execute query
			final RemoteRepository r = repositoryManager.getRepositoryForNamespace(namespace);
			final IPreparedTupleQuery query = r.prepareTupleQuery("SELECT ?age ?src WHERE {?bob foaf:name \"Bob\" . <<?bob foaf:age ?age>> dc:source ?src .}");
			final TupleQueryResult result = query.evaluate();
			try {
				while (result.hasNext()) {
					final BindingSet bs = result.next();
					log.info(bs);
				}
			} finally {
				result.close();
			}
		} finally {
			repositoryManager.close();
		}
	}
	
	private static boolean namespaceExists(final String namespace, final RemoteRepositoryManager repo) throws Exception{
		final GraphQueryResult res = repo.getRepositoryDescriptions();
		try{
			while(res.hasNext()){
				final Statement stmt = res.next();
				if (stmt.getPredicate().toString().equals(SD.KB_NAMESPACE.stringValue())) {
					if(namespace.equals(stmt.getObject().stringValue())){
						log.info(String.format("Namespace %s already exists", namespace));
						return true;
					}
				}
			}
		} finally {
			res.close();
		}
		return false;
	}

} public class SampleBlazegraphSesameEmbedded {
	
	protected static final Logger log = Logger.getLogger(SampleBlazegraphSesameEmbedded.class);

	public static void main(String[] args) throws IOException, OpenRDFException {

		// load journal properties from resources
		final Properties props = loadProperties("/blazegraph.properties");

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

		try{
			repo.initialize();
			
			/*
			 * Load data from resources 
			 * src/main/resources/data.n3
			 */
	
			loadDataFromResources(repo, "/data.n3", "");
			
			final String query = "select * {<http://blazegraph.com/blazegraph> ?p ?o}";
			final TupleQueryResult result = executeSelectQuery(repo, query, QueryLanguage.SPARQL);
			
			try {
				while(result.hasNext()){
					
					final BindingSet bs = result.next();
					log.info(bs);
					
				}
			} finally {
				result.close();
			}
		} finally {
			repo.shutDown();
		}
	}

	/*
	 * Load a Properties object from a file.
	 */
	public static Properties loadProperties(final String resource) throws IOException {
		final Properties p = new Properties();
		final InputStream is = SampleBlazegraphSesameEmbedded.class
				.getResourceAsStream(resource);
		final Reader reader  = new InputStreamReader(new BufferedInputStream(is));
		try{
			p.load(reader);
		}finally{
			reader.close();
			is.close();
		}
		return p;
	}

	/*
	 * Load data from resources into a repository.
	 */
	public static void loadDataFromResources(final Repository repo, final String resource, final String baseURL)
			throws OpenRDFException, IOException {

		final RepositoryConnection cxn = repo.getConnection();
		
		try {
			cxn.begin();
			try {
				final InputStream is = SampleBlazegraphSesameEmbedded.class.getResourceAsStream(resource);
				if (is == null) {
					throw new IOException("Could not locate resource: " + resource);
				}
				final Reader reader = new InputStreamReader(new BufferedInputStream(is));
				try {
					cxn.add(reader, baseURL, RDFFormat.N3);
				} finally {
					reader.close();
				}
				cxn.commit();
			} catch (OpenRDFException ex) {
				cxn.rollback();
				throw ex;
			}
		} finally {
			// close the repository connection
			cxn.close();
		}
	}

	/*
	 * Execute sparql select query.
	 */
	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();
		}
	}
} public class HelloBlazegraph {
	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();
		}
	}
} public class SampleBlazegraphSesameRemote {

	protected static final Logger log = Logger
			.getLogger(SampleBlazegraphSesameRemote.class);
	private static final String serviceURL = "http://localhost:9999/bigdata";

	public static void main(String[] args) throws Exception {

		final RemoteRepositoryManager repo = new RemoteRepositoryManager(
				serviceURL, false /* useLBS */);

		try {

			JettyResponseListener response = getStatus(repo);
			log.info(response.getResponseBody());

			// create a new namespace if not exists
			final String namespace = "newNamespace";
			final Properties properties = new Properties();
			properties.setProperty("com.bigdata.rdf.sail.namespace", namespace);
			if (!namespaceExists(repo, namespace)) {
				log.info(String.format("Create namespace %s...", namespace));
				repo.createRepository(namespace, properties);
				log.info(String.format("Create namespace %s done", namespace));
			} else {
				log.info(String.format("Namespace %s already exists", namespace));
			}
			
			
			//get properties for namespace
			log.info(String.format("Property list for namespace %s", namespace));
			response = getNamespaceProperties(repo, namespace);
			log.info(response.getResponseBody());

			/*
			 * Load data from file located in the resource folder
			 * src/main/resources/data.n3
			 */
			final String resource = "/data.n3";
			loadDataFromResource(repo, namespace, resource);

			// execute query
			final TupleQueryResult result = repo.getRepositoryForNamespace(namespace)
					.prepareTupleQuery("SELECT * {?s ?p ?o} LIMIT 100")
					.evaluate();
			
			//result processing
			try {
				while (result.hasNext()) {
					final BindingSet bs = result.next();
					log.info(bs);
				}
			} finally {
				result.close();
			}

		} finally {
			repo.close();
		}

	}

	/*
	 * Status request.
	 */
	private static JettyResponseListener getStatus(final RemoteRepositoryManager repo)
			throws Exception {

		final ConnectOptions opts = new ConnectOptions(serviceURL + "/status");
		opts.method = "GET";
		return repo.doConnect(opts);

	}

	/*
	 * Check namespace already exists.
	 */
	private static boolean namespaceExists(final RemoteRepositoryManager repo,
			final String namespace) throws Exception {
		
		final GraphQueryResult res = repo.getRepositoryDescriptions();
		try {
			while (res.hasNext()) {
				final Statement stmt = res.next();
				if (stmt.getPredicate()
						.toString()
						.equals(SD.KB_NAMESPACE.stringValue())) {
					if (namespace.equals(stmt.getObject().stringValue())) {
						return true;
					}
				}
			}
		} finally {
			res.close();
		}
		return false;
	}

	/*
	 * Get namespace properties.
	 */
	private static JettyResponseListener getNamespaceProperties(
			final RemoteRepositoryManager repo, final String namespace) throws Exception {

		final ConnectOptions opts = new ConnectOptions(serviceURL + "/namespace/"
				+ namespace + "/properties");
		opts.method = "GET";
		return repo.doConnect(opts);

	}

	/*
	 * Load data into a namespace.
	 */
	private static void loadDataFromResource(final RemoteRepositoryManager repo,
			final String namespace, final String resource) throws Exception {
		final InputStream is = SampleBlazegraphSesameRemote.class
				.getResourceAsStream(resource);
		if (is == null) {
			throw new IOException("Could not locate resource: " + resource);
		}
		try {
			repo.getRepositoryForNamespace(namespace).add(
					new RemoteRepository.AddOp(is, RDFFormat.N3));
		} finally {
			is.close();
		}
	}

}
import java.util.Properties;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.bigdata.journal.BufferMode;
import com.bigdata.journal.Journal;
import com.bigdata.rdf.sail.webapp.NanoSparqlServer;
import sample.blueprints.embedded.SampleBlazegraphBlueprintsEmbedded;
import sample.blueprints.remote.SampleBlazegraphBlueprintsRemote;
import sample.btree.JournalExample;
import sample.btree.JournalReadOnlyTxExample;
import sample.btree.JournalTxExample;
import sample.btree.ReadWriteIndexExample;
import sample.btree.ReadWriteIndexTxExample;
import sample.btree.TempStoreExample;
import sample.customFunction.embedded.SampleBlazegraphCustomFunctionEmbedded;
import sample.customFunction.remote.SampleBlazegraphCustomFunctionRemote;
import sample.rdf.rules.TestSample;
import sample.rdr.SampleBlazegraphRDR;
import sample.sesame.embedded.SampleBlazegraphSesameEmbedded;
import sample.sesame.first.HelloBlazegraph;
import sample.sesame.remote.SampleBlazegraphSesameRemote;
package samples.tests;





/**
 * 
 * This test suite verifies consistency of Blazegraph Samples, ensuring:
 * - syntax compatibility with core blazegraph;
 * - successful dependency resolution;
 * - no runtime errors generated on execution of all 'main' methods. 
 *
 */
public class BlazegraphSamplesTest {

    private Server nss;
    private Journal m_indexManager;
    private static final Logger log = Logger.getLogger(BlazegraphSamplesTest.class);
    
	
	
	@Before
	public void startNss() throws Exception{
		
		final Properties journalProperties = new Properties();
        {
            journalProperties.setProperty(Journal.Options.BUFFER_MODE,
                    BufferMode.MemStore.name());
        }
        
        m_indexManager = new Journal(journalProperties);
 		
		nss = NanoSparqlServer.newInstance(9999, "jettyMavenTest.xml", m_indexManager, null);
		
		nss.start();
		
	}
	
	@Test
	public void testSampleBlazegraphSesameRemote() throws Exception{
		
		log.info("SampleBlazegraphSesameRemote test:");
		SampleBlazegraphSesameRemote.main(null);
		log.info("ok");
	
	}
	
	@Test
	public void testSampleBlazegraphBlueprintsRemote() throws Exception{
		
		SampleBlazegraphBlueprintsRemote.main(null);
	
	}
	
	@Test
	public void testSampleBlazegraphRDR() throws Exception{
		
		SampleBlazegraphRDR.main(null);
	
	}
	
	@Test
	public void testSampleBlazegraphSesameEmbedded() throws Exception{
		
		SampleBlazegraphSesameEmbedded.main(null);
	
	}
	
	@Test
	public void testHelloBlazegraph() throws Exception{
		
		HelloBlazegraph.main(null);
	
	}
	
// Disabled failing test
	@Test
	public void testSampleBlazegraphBlueprintsEmbedded() throws Exception{
		
		SampleBlazegraphBlueprintsEmbedded.main(null);