Welcome!

Linux Containers Authors: Liz McMillan, Elizabeth White, Zakia Bouachraoui, Pat Romanski, Stefana Muller

Related Topics: Java IoT, Industrial IoT

Java IoT: Article

Java Programming with Berkeley DB XML

Explained through examples

Berkeley DB XML (BDB XML) is a popular native XML database. It can be accessed through the shell or within another program. This month I will show you how to use BDB XML in Java. BDB XML has similar APIs for all supported languages such as Java and C++, therefore the ideas presented in this article apply to all supported languages. I have been closely following BDB XML from the very first release, and there have been tremendous improvements in this product.

Last month in this column I wrote about using BDB XML through the command shell (WSJ Vol. 5, iss. 12). I also mentioned some of the basic BDB XML concepts, which I think may be helpful in constructing Java programs. If you aren't familiar with BDB XML concepts, I recommend reading last month's article or checking the online BDB XML documentation.

Installation
BDB XML is distributed by SleepyCat Software, and has an installer for the Windows operating systems. You may choose to build it from the source files, which exist for almost every popular operating system. For convenient coding I used the Eclipse Integrated Development Environment (IDE) from www.eclipse.org. Eclipse is a very nice IDE that makes programming tasks easy and fun. It's available free of charge. In order to use the Java API provided with the BDB XML, we have to include two .jar files in the Classpath. These files are db.jar and dbxml.jar, and they should be located under the .jar directory of your installation path.

Environment
In order to start making something useful with our Java programs, we have to take a moment to decide the properties of the environment that we will use throughout the lifetime of the code. I will explain some of the widely used environment properties. It's true that an embedded database such as BDB XML puts more pressure on the shoulders of the programmers. You should only enable a feature if there is a need for it. If you don't feel very comfortable with these database environment features, refer to a database book, or check them online.

An important feature of the Environment is that once it has been created, it's not possible to change many of its attributes. The following is a summary of commands:

  • EnvironmentConfig.setAllowCreate(true) - This command enables creation of the environment.
  • EnvironmentConfig.setInitializeLocking(true) - If there are multiple processes or multiple threads, this should be turned on. It locks the database sources for preventing anomalies. Data locking is an important database concept. It's definitely needed in a multiple transaction environment. However, if the transactions are serial, i.e., one starts after the other finishes, you might not need it. In a multiple process or in a multiple thread environment, there are competing transactions. In some situations deadlock may occur because of locking, but this feature comes with a deadlock detector for resolving such resource conflicts.
  • EnvironmentConfig.setInitializeLogging(true) - This command initializes the logging. Logging, which is essential for recovery, is basically keeping track of read and write operations in the database. When there is a power outage you may need to recover using the log files, and in some cases log files are used for replication purposes.
  • EnvironmentConfig.setInitializeCache(true) - Initializes the shared memory. It must be set to true when using multithreaded applications.
  • EnvironmentConfig.setTransactional(true) - Enables transactional support that is essential for most of the applications. A transaction is a set of read and write operations. Conceptually, a transaction looks something like this:
    Start the transaction:
    - Read customer credit card number
    - Contact Visa, verify the number
    - Charge the credit card account
    - Ship the item
    - Commit transaction

    The transaction above is an atomic operation; either all of the operations succeed or none of them does. Imagine that there is a power outage after the third step ("Charge the credit card account"); the credit card will be charged, but the item will not be shipped. This is not good news for the customer. In a transactional database such as Berkeley DB XML, if there is a power outage after the third step, when the system is back on power, it will roll back all of the operations done in the first, second, and third steps. The credit card charge will be refunded because the fourth step ("Ship the item") was not completed, so a customer won't be charged for something he didn't receive.

  • EnvironmentConfig.setRunRecovery(true) - This will turn on the normal recovery feature, which makes sure that the database files are consistent with the log files. For example, after a power failure it's possible that the database files are behind the logs. When the recovery is on, BDB XML will recover the database files from the logs. This feature depends on the setInitializeLogging, which in fact must be turned on in advance. Listing 1 shows a Java snippet for configuring the environment.
XmlManager
This is the high-level class for managing XML collections. Queries are sent to the database using the XmlManager object. XmlManager can also create input streams and collections.

XmlManager has three different constructors. One of them, shown below, takes Environment and XmlManagerConfig objects as its two arguments:

XmlManager(Environment dbenv, XmlManagerConfig config)

XmlManagerConfig, as the name suggests, is the configuration object for the XmlManager. Let's see what kind of configurations can we make using this object:

  • XmlManagerConfig.setAllowAutoOpen(true) - If a query refers to an unopened container, it will be opened automatically.
  • XmlManagerConfig.setAdoptEnvironment(true) - XmlManager will automatically close the Environment when its close() method is called. There will be no need to use the close() method of the Environment object.
  • XmlManagerConfig.setAllowExternalAccess(true) - Allows use of external resources such as DTD entities. It's important to enable this feature, because when using external general entities, the result or part of the result may be outside of the database. In this situation BDB XML will be able to access the external resources.
Adding a Document
After instantiating an XmlManager object, creating a container and then adding an XML document is easy. The Java snippet in Listing 2 shows how to do this. Listing 2 demonstrates creating an XML container called "xbench.dbxml." Following this, an input stream is created from the file "C:/dictionary.xml" and it is added to the container by the container's putDocument() method. The complete Java code is provided in Listing 4.

Querying Data
After setting up the necessary foundations, now we are ready to query the database. As a programmer you can fine-tune the query evaluations using Lazy, and Eager methods. The documentation states that BDB XML supports the July 2004 W3C XQuery specification. XPath is a sub language of XQuery, therefore it's automatically supported too. Results are provided in the XmlResults object, which requires looping over it as Listing 3 shows.

As I mentioned earlier, I have been following BDB XML for a long time. Unfortunately, the API has not been backward compatible with earlier versions. Code that I wrote earlier for version 1.2 doesn't compile on version 2.2 of Berkeley DB XML because of API changes. This is very inconvenient, and I hope in future versions SleepyCat Software publishes backwardly compatible APIs.

More Stories By Selim Mimaroglu

Selim Mimaroglu is a PhD candidate in computer science at the University of Massachusetts in Boston. He holds an MS in computer science from that school and has a BS in electrical engineering.

Comments (2)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.