示例#1
0
void NormalRepNode::masterOperations()
{
	XmlManager& mgr = getManager();
	XmlContainer& cont = getContainer();
	XmlUpdateContext uc = mgr.createUpdateContext();
	int num = documentNum;

	XmlTransaction txn = mgr.createTransaction();
	try {
		ostringstream o;
		printMsg("is putting document.");
		for (int i = 0; i < num && (docNum_+i) < maxDocumentNum; i++) {
			ostringstream o;
			o << "<node>"
			  << "<name>" << getEnvHome() << "</name>"
			  << "<doc_id>" << i << "</doc_id>"
			  << "</node>";

			// Put documents
			cont.putDocument(txn, "",  o.str(), uc, DBXML_GEN_NAME);
		}
		docNum_ = cont.getNumDocuments(txn);
		txn.commit();
		printMsg("put document done.");
	} catch (XmlException &xe) {
		txn.abort();
		// Deal with permission denied exception
		if (xe.getExceptionCode() == XmlException::DATABASE_ERROR &&
		    xe.getDbErrno() == EACCES) {
			yield();
		} else
			throwIfUnExpected(xe);
	}
}
示例#2
0
void doQuery( XmlTransaction &txn, XmlManager &db, const XmlContainer &container, const std::string &query )
{
	////////////////////////////////////////////////////////////////////////
	//////  Performs a simple query (no context) against the   ///////
	//////  provided container.                                      ///////
	////////////////////////////////////////////////////////////////////////

	///// some defensive code eliminated for clarity //

	// Perform the query. Result type is by default Result Document
	std::string fullQuery = "collection('" + container.getName() + "')" + query;
	try {
		std::cout << "Exercising query '" << fullQuery << "' " << std::endl;
		std::cout << "Return to continue: ";
		getc(stdin);

		XmlQueryContext context = db.createQueryContext();

		XmlResults results( db.query( txn, fullQuery, context) );
		XmlValue value;
		while( results.next(value) ) {
			// Obtain the value as a string and print it to stdout
			std::cout << value.asString() << std::endl;
		}

		std::cout << (unsigned int) results.size()
			<< " objects returned for expression '"
			<< fullQuery << "'\n" << std::endl;

	}
	catch(XmlException &e) {
		std::cerr << "Query " << fullQuery << " failed\n";
		std::cerr << e.what() << "\n";
		txn.abort();
		exit( -1 );
	}
	catch(std::exception &e) {
		std::cerr << "Query " << fullQuery << " failed\n";
		std::cerr << e.what() << "\n";
		txn.abort();
		exit( -1 );
	}
}
示例#3
0
void replaceIndex( XmlContainer &container, const std::string &URI,
				  const std::string &nodeName, const std::string &indexType,
				  XmlTransaction &txn, XmlUpdateContext &uc)
{
	std::cout << "Replacing index on node: " << nodeName << std::endl;
	try
	{
		//Retrieve the XmlIndexSpecification from the container
		XmlIndexSpecification idxSpec = container.getIndexSpecification( txn );

		//Lets see what indexes exist on this container
		std::string uri, name, index;
		int count = 0;
		std::cout << "Before index add." << std::endl;
		while( idxSpec.next(uri, name, index) )
		{
			// Obtain the value as a string and print it to the console
			std::cout << "\tFor node '" << name << "', found index: '" << index << "'." << std::endl;
			count ++;
		}

		std::cout << count << " indexes found." << std::endl;

		//Replace the indexes for the specified node
		idxSpec.replaceIndex( URI, nodeName, indexType );

		//Set the specification back to the container
		container.setIndexSpecification( txn, idxSpec, uc );

		//Look at the indexes again to make sure our replacement took.
		count = 0;
		idxSpec.reset();
		std::cout << "After index add." << std::endl;
		while( idxSpec.next(uri, name, index) )
		{
			// Obtain the value as a string and print it to the console
			std::cout << "\tFor node '" << name << "', found index: '" << index << "'." << std::endl;
			count ++;
		}

		std::cout << count << " indexes found." << std::endl;

	}
	//Catches XmlException
	catch(std::exception &e)
	{
		std::cerr << "Index replace failed: \n";
		std::cerr << e.what() << "\n";
		txn.abort();

		exit( -1 );
	}
	std::cout << "Index replaced successfully." << std::endl;

}
示例#4
0
void NormalRepNode::clientOperations()
{
	XmlTransaction txn = getManager().createTransaction();
	try {
		// Save the new node state.
		docNum_ = getContainer().getNumDocuments(txn);
		txn.commit();
	} catch (XmlException &xe) {
		txn.abort();
		throwIfUnExpected(xe);
	}
}
示例#5
0
void deleteIndex( XmlContainer &container, const std::string &URI,
				 const std::string &nodeName, const std::string &indexType,
				 XmlTransaction &txn, XmlUpdateContext &uc )
{
	std::cout << "Deleting index type: '" << indexType << ""
		<< " from node: '" << nodeName << "'." << std::endl;
	try
	{
		//Retrieve the XmlIndexSpecification from the container
		XmlIndexSpecification idxSpec = container.getIndexSpecification( txn );

		std::cout << "Before the delete, the following indexes are maintained for the container:" << std::endl;
		std::string uri, name, index;
		while( idxSpec.next(uri, name, index) )
		{
			// Obtain the value as a string and print it to the console
			std::cout << "\tFor node '" << name << "', found index: '" << index << "'." << std::endl;
		}
		std::cout << "\n" << std::endl;

		//Delete the indexes from the specification.
		idxSpec.deleteIndex( URI, nodeName, indexType );

		//Set the specification back to the container
		container.setIndexSpecification( txn, idxSpec, uc );

		//Show the remaining indexes in the container, if any.
		std::cout << "After the delete, the following indexes exist for the container:" << std::endl;
		idxSpec.reset();
		while( idxSpec.next(uri, name, index) )
		{
			// Obtain the value as a string and print it to the console
			std::cout << "\tFor node '" << name << "', found index: '" << index << "'." << std::endl;
		}
		std::cout << "\n" << std::endl;
	}
	//Catches XmlException.
	catch(std::exception &e)
	{
		std::cerr << "Index delete failed: \n";
		std::cerr << e.what() << "\n";
		txn.abort();

		exit( -1 );
	}
	std::cout << "Index deleted successfully.\n" << std::endl;

}
示例#6
0
void getDetails( XmlTransaction &txn, XmlManager &mgr, const XmlContainer &container, const std::string &query, XmlQueryContext &context )
{
	////////////////////////////////////////////////////////////////////////
	//////  Performs an query (in context) against the         ///////
	//////  provided container.                                      ///////
	////////////////////////////////////////////////////////////////////////

	///// some defensive code eliminated for clarity //

	// Perform the query. Result type is by default Result Document
	std::string fullQuery = "collection('" + container.getName() + "')" + query;
	try {
		std::cout << "Exercising query '" << fullQuery << "' " << std::endl;
		std::cout << "Return to continue: ";
		getc(stdin);

		XmlResults results( mgr.query( txn, fullQuery, context ) );
		XmlValue value;
		std::cout << "\n\tProduct : Price : Inventory Level\n";
		while( results.next(value) ) {
			/// Retrieve the value as a document
			XmlDocument theDocument = value.asDocument();

			/// Obtain information of interest from the document. Note that the
			//  wildcard in the query expression allows us to not worry about what
			//  namespace this document uses.
			std::string item = getValue( txn, mgr, theDocument, "fn:string(/*/product)", context);
			std::string price = getValue( txn, mgr, theDocument, "fn:string(/*/inventory/price)", context);
			std::string inventory = getValue( txn, mgr, theDocument, "fn:string(/*/inventory/inventory)", context);

			std::cout << "\t" << item << " : " << price << " : " << inventory << std::endl;

		}
		std::cout << "\n";
		std::cout << (unsigned int) results.size()
			<< " objects returned for expression '"
			<< fullQuery << "'\n" << std::endl;
	}
	//Catches XmlException
	catch(std::exception &e) {
		std::cerr << "Query " << fullQuery << " failed\n";
		std::cerr << e.what() << "\n";
		txn.abort();
		exit(-1);
	}
}
void doContextQuery( XmlTransaction &txn, XmlManager &mgr, const std::string cname,
					const std::string &query, XmlQueryContext &context )
{
	////////////////////////////////////////////////////////////////////////
	//////  Performs a simple query (with context) against the ///////
	//////  provided container.                                      ///////
	////////////////////////////////////////////////////////////////////////

	///// some defensive code eliminated for clarity //

	// Perform the query. Result type is by default Result Document
	std::string fullQuery = "collection('" + cname + "')" + query;
	try {
		std::cout << "Exercising query '" << fullQuery << "' " << std::endl;
		std::cout << "Return to continue: ";
		getc(stdin);
		std::cout << "\n";

		XmlResults results( mgr.query(txn, fullQuery, context ) );
		XmlValue value;
		while(results.next(value)) {
			// Get the document's name and print it to the console
			XmlDocument theDocument = value.asDocument();
			std::cout << "Document name: " << theDocument.getName() << std::endl;
			std::cout << value.asString() << std::endl;
		}

		std::cout << (unsigned int)results.size()
			<< " objects returned for expression '" << fullQuery
			<< "'\n" << std::endl;

	}
	//Catches XmlException
	catch(std::exception &e) {
		std::cerr << "Query " << fullQuery << " failed\n";
		std::cerr << e.what() << "\n";
		txn.abort();
		exit( -1 );
	}
}
//Get a document from the container using the document name
void doGetDocument( XmlTransaction &txn, XmlContainer &container, const std::string docname)
{

	try {
		std::cout << "Getting document '" << docname << "' from the container." << std::endl;
		std::cout << "Return to continue: ";
		getc(stdin);
		std::cout << "\n";

		//Get the document from the container using the document name
		XmlDocument theDocument = container.getDocument(txn, docname);
		std::string content;
		std::cout << "Document name: " << theDocument.getName() << std::endl;
		std::cout << theDocument.getContent(content) << std::endl;

	}
	//Catches XmlException
	catch(std::exception &e) {
		std::cerr << "Get document from container failed.\n";
		std::cerr << e.what() << "\n";
		txn.abort();
		exit( -1 );
	}
}
示例#9
0
int
main(int argc, char **argv)
{
	// This program uses a named container, which will apear
	// on disk
	std::string containerName = "people.dbxml";
	std::string content = "<people><person><name>joe</name></person><person><name>mary</name></person></people>";
	std::string docName = "people";
	// Note that the query uses a variable, which must be set
	// in the query context
	std::string queryString =
		"collection('people.dbxml')/people/person[name=$name]";
	std::string environmentDir = ".";

	// Berkeley DB environment flags
	u_int32_t envFlags = DB_RECOVER|DB_CREATE|DB_INIT_MPOOL|
		DB_INIT_LOCK|DB_INIT_TXN|DB_INIT_LOG;
	// Berkeley DB cache size (25 MB).  The default is quite small
	u_int32_t envCacheSize = 25*1024*1024;

	// argument parsing should really use getopt(), but
	// avoid it for platform-independence
	if (argc == 3) {
		if (std::string(argv[1]) != std::string("-h"))
			usage(argv[0]);
		environmentDir = argv[2];
	} else if (argc != 1)
		usage(argv[0]);

	// Create and open a Berkeley DB Transactional Environment.
	int dberr;
	DB_ENV *dbEnv = 0;
	dberr = db_env_create(&dbEnv, 0);
	if (dberr == 0) {
		dbEnv->set_cachesize(dbEnv, 0, envCacheSize, 1);
		dbEnv->set_errcall(dbEnv, errcall); // set error callback
		dbEnv->set_lk_detect(dbEnv, DB_LOCK_DEFAULT); // handle deadlocks
		dberr = dbEnv->open(dbEnv, environmentDir.c_str(), envFlags, 0);
	}
	if (dberr) {
		std::cout << "Unable to create environment handle due to the following error: " <<
			db_strerror(dberr) << std::endl;
		if (dbEnv) dbEnv->close(dbEnv, 0);
		return -1;
	}

	try {
		// All BDB XML programs require an XmlManager instance.
		// Create it from the DbEnv
		XmlManager mgr(dbEnv, DBXML_ADOPT_DBENV);

		// Because the container will exist on disk, remove it
		// first if it exists
		if (mgr.existsContainer(containerName))
			mgr.removeContainer(containerName);

		/* Create a container that is transactional.  The container
		* type is NodeContainer, which is the default container type,
		* and the index is on nodes, which is the default for a
		* NodeContainer container.  XmlContainerConfig can be used
		* to set the container type and index type.
		*/
		XmlContainerConfig config;
		config.setTransactional(true);
		XmlContainer cont = mgr.createContainer(
			containerName,
			config);

		// All Container modification operations need XmlUpdateContext
		XmlUpdateContext uc = mgr.createUpdateContext();

		// The following putDocument call will auto-transact
		// and will abort/cleanup if the operation deadlocks or
		// otherwise fails
		cont.putDocument(docName, content, uc);

		// Querying requires an XmlQueryContext
		XmlQueryContext qc = mgr.createQueryContext();

		// Add a variable to the query context, used by the query
		qc.setVariableValue("name", "mary");

		// Use try/catch and while to handle deadlock/retry
		int retry = 0;
		while (retry < 5) { // hard-code 5 retries
			// Create a new transaction for the query
			XmlTransaction txn = mgr.createTransaction();

			try {
				// o Note the passing of txn to both methods
				// o Often the XmlQueryExpression object will be created and
				// saved for reuse in order to amortize the cost of parsing a query
				XmlQueryExpression expr = mgr.prepare(txn, queryString, qc);
				XmlResults res = expr.execute(txn, qc);

				// Note use of XmlQueryExpression::getQuery() and
				// XmlResults::size()
				std::cout << "The query, '" << expr.getQuery() << "' returned " <<
					(unsigned int)res.size() << " result(s)" << std::endl;

				// Process results -- just print them
				XmlValue value;
				std::cout << "Result: " << std::endl;
				while (res.next(value)) {
					std::cout << "\t" << value.asString() << std::endl;
				}

				// done with the transaction
				txn.commit();
				break;
			} catch (XmlException &x) {
				txn.abort(); // unconditional
				if ((x.getExceptionCode() == XmlException::DATABASE_ERROR) &&
					(x.getDbErrno() == DB_LOCK_DEADLOCK)) {
						++retry;
						continue; // try again
				}
				throw; // re-throw -- not deadlock
			}
		}
		// In C++, resources are released as objects go out
		// of scope.
	} catch (XmlException &xe) {
		std::cout << "XmlException: " << xe.what() << std::endl;
	}

	return 0;
}