At Couchbase Connect 2015 we demonstrated an example application that uses N1QL to query data from a sample Couchbase bucket.

If you missed the conference, not a problem. We're going to go through how to reproduce this application and check out some of the highlights of Couchbase 4.0.

Prerequisites

  • Apache Maven 3
  • Java Development Kit (JDK) 1.7
  • Couchbase Server 4.0
  • IntelliJ IDEA 14.1+, Eclipse, or NetBeans. IntelliJ IDEA will be used in this example.

Creating a New Project

Open IntelliJ IDEA and choose to create a new Java project, making sure to use JDK 1.7 if asked. For purposes of this guide, let's call the project try-cb-java.

Now right-click try-cb-java in your project tree, then choose Add Frameworks Support and select Maven. This will add a pom.xml file to your project.

Setting up Maven

Inside the pom.xml file, start by giving the project a more appealing group name:

Then proceed to adding the rest of our dependencies to the file, that include Spring Boot, the Couchbase client, and the Spring security framework.

Creating a Run Profile

As of right now, if you try to run the application, it will error or nothing will happen because there is no profile currently configured.

From the toolbar, choose Run -> Edit Configurations and choose to add a new Maven configuration. You can name it whatever you want, but it is important have the following in the command line field:

For this article we're going to name the configuration Spring Boot.

IntelliJ IDEA should now be ready for development.

Creating a Indices on the Couchbase Bucket

Because this tutorial uses N1QL queries, we must first add indices to our Couchbase Server bucket. Now this can easily be done through code, but for this example we're going to shortcut it and add them via the Couchbase Query (CBQ) client that gets automatically installed with a Mac OS and Windows installation of Couchbase 4+.

On Mac OS, launch CBQ found at /Applications/Couchbase Server.app/Contents/Resources/couchbase-core/bin/cbq and run the following:

On Windows, launch CBQ found at C:/Program Files/Couchbase/Server/bin/cbq.exe and execute the same N1QL command as done on Mac OS.

Creating a Main Application Class

The main class for this project will be Application.java and can be created by right-clicking the trycb package from the project tree and choosing New -> Java Class.

Add the following to get the class in its most basic runnable state:

Make sure the project runs without errors by choosing Run -> Run 'Spring Boot' from the IntelliJ IDEA toolbar.

Handling Cross Origin Resource Sharing (CORS)

Since most of our testing will be done locally, we need to make sure CORS is enabled, otherwise the web browser is going to complain when trying to hit our API endpoints with JavaScript.

Make sure the Application class implements the Filter class and add the following code:

Configure Couchbase Cluster and Bucket Options

As of right now we essentially have a Spring Boot application with no Couchbase interation. We've included the Java client via Maven, so it is time to start using it.

Add the following to the Application class:

We've not set up the hostname, bucket, and password variables, but they will be used to connect to a Couchbase cluster and a particular bucket.

Add Resource Variables

You saw that we were using hostname, bucket, and password, so now it is time to set them.

In the IntelliJ IDEA project tree, right-click src/main/resources and choose New -> File. Name the new file application.properties and add the following lines:

Spring Boot will pick up this application.properties file for you. Further information on application related properties can be seen in the official Spring documentation.

Creating RESTful Endpoints

This application is going to be API based so certain endpoints need to be created:

Essentially we'll have endpoints for user registration and sign-ins, booking and finding flights, as well as searching flight information.

The logic behind these endpoints will appear in another class for cleanliness.

Creating a Database Class

We just set up the driving endpoints of our Spring Boot application, but it is now time to take a look at the logic behind interacting with the database.

The database class for this project will be Database.java and can be created by right-clicking the trycb package from the project tree of IntelliJ IDEA and choosing New -> Java Class.

Add the following to get the class for a nice skeleton of where we're going:

From here, we're going to complete each of these methods in the order they are likely to be interacted with by the user.

Creating a New User

When the user issues a POST to the /api/user/login, the following database function must be called:

The username and password included with the request will be added to a JSON object and then the password will be encrypted with the Spring BCrypt library. To keep track of the user data, new users will end up in documents titled user::{USERNAME_HERE}. Using bucket.insert(doc), an attempt to insert the data into the bucket is made. If there are no exceptions thrown, then it succeeded and a response is returned. If there is an exception, then inserting failed and the error will be returned.

Signing in as an Existing User

When the user issues a GET to the same /api/user/login endpoint, the following database function must be called:

Using bucket.get(“user::” + username) with the provided username, the Java application gets the document from the bucket if it exists. The Spring BCrypt library has a great function to check whethor or not the provided password matches the encrypted password that is stored. If it does, then return a success object, otherwise return a login failed object.

Extracting the N1QL Result and Making it Java Readable

N1QL returns a QueryResult object that may be less desirable if returning data to a requesting front-end. What we really want to do is convert it into a List object.

This function will be called every time N1QL data is returned.

Finding All Airports

Now we're going to see some of the magic behind N1QL when it comes to searching for airports.

You can see in the above code we are using the Fluent API with IntelliJ IDEA to create our N1QL query. Essentially, if you were to look at raw SQL, it would look like this:

In the above, {{PARAMS}} represents an airport like LAX or similar. Of course that is provided the params length is three.

Finding All Flight Routes

Finally, we're left with the method responsible for finding flight routes:

We're doing two N1QL queries in this method. The first can easily be translated to the following:

Of course {{PARAMS}} is whatever was passed to your endpoint. In the statement, we're combining the result sets of all the from airports and all the to airports.

After getting both the result sets, we are looping through them to make sure the to and from airports exist, otherwise we're defaulting them to NULL which will prevent the next query from being successful.

The second query can be translated into the following raw query:

We're getting schedule information about the flights by unnesting it from the JSON document and then joining on the now flattened key.

Wrapping Up The Application and Database Classes

We now have our endpoints and database methods, but they are not connected to each other. It is time to revisit the Application.java class and add some code to the functions we created previously:

You can see that the two static Database methods are called from each of the endpoints relating to user accounts. The same process can be done for the other endpoints that we've previously created:

Testing The Sample Endpoints

There are a few ways to test the endpoints of the application. In this example we're going to use cURL, but you can certainly use Postman for Google Chrome or something similar.

With cURL installed, open a Terminal or Command Prompt and enter the following:

The above cURL command will hit the api/airport/findAll endpoint and pass a parameter of search=LAX. If successful, you should get a response of:

The same kind of testing can done for every other endpoint.

Conclusion

We just saw how to get a sample travel application setup that uses Couchbase Server and Spring Boot for Java. Although we didn't set up a front-end, it is very possible to add one using languages such as AngularJS, jQuery, or ReactJS.

This full project along with an AngularJS front-end can be obtained from the Couchbase Labs GitHub channel.

Posted by Nic Raboy, Developer Advocate, Couchbase

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Leave a reply