Linux Containers Authors: Elizabeth White, Zakia Bouachraoui, Liz McMillan, Yeshim Deniz, Pat Romanski

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.

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.

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.
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
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture was Octoblu, a cross-protocol Internet of Things (IoT) mesh network platform, acquired by Citrix. Prior to co-founding Octoblu, Chris was founder of Nodester, an open-source Node.JS PaaS which was acquired by AppFog and ...
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...