First of all, I must admit that as a Java developer with more than ten years of development experience, I have formed inherent routines to solve most problems, although they often appear cumbersome and cumbersome. For example, if you want to read a file, you should initialize a BufferedReader instance and pass in a FileReader. This is almost logical. I have written such code in many projects that I consider to be "enterprise-level" and enjoy it very much. Process, it can be said that I am just a Java fanatic who disdains other languages.
If you are reading this blog post, you may have fallen into a misunderstanding that I fell into many years ago. As a qualified developer, you should constantly learn new technologies and choose appropriate technologies based on actual work needs. Although I'm getting older and may one day get tired of java. But I have really discovered an exciting new thing now, node.js is like a child getting a novel toy to me, in this blog post I will first show you how to create a simple Rest using Java EE Service to read the MongoDB database. Then I will use node.js to achieve the same functionality, and you will more easily understand the excitement of this new development language.
Start with the basics – what is Node.js?
First of all, I want to make it clear that Node.js is not a "fashionable" language that only "fashionable people" use. Although it started with this understanding, I'm happy to report that Node.js is a mature language - and in the current Internet age, it has found its way into large enterprises. Powers some of the highest traffic websites. Node.js is a very useful tool in your skill set and will surprise you with how easy it is to build stable, secure, and performant code.
In short, Node is a language for server-side activities. It uses Javascript language, and there are many libraries available, such as npm models. You can compare those npm models to .jar packages in Java. When you need a piece of functionality and don't feel like writing all the code yourself, chances are the feature you're looking for is already provided in the npm model.
Node applications typically execute to maximize efficiency by taking advantage of non-blocking I/O and asynchronous events. One thing that Java developers need to know is that Node applications run in a single thread. However, the backend node code uses multiple threads for operations such as network and file access. For this reason, Node is perfect for applications that require real-time experience.
Continue - IDE support
You may be like me and "live" and "breathe" in the IDE. This may be due to the fact that Java is too wordy and requires us to write constant code to complete functions during the software development process. Once we discovered the benefits of code completion, we slowly learned to use the IDE for file management, debugging, and other very useful features. Suffice it to say, I love using an IDE and continue to use it when working with Nodeb. The following are the first batch of IDEs that currently support Node:
1. Eclipse - This should be easy to get started with if you are already using it in Java. Just install the Node.js plugin.
2.JetBrains IntelliJ IDEA - a very popular commercial IDE. This is my favorite IDE so far.
3.Microsoft Visual Studio – Yes, you read that right. Node has grown to the point where Microsoft added native support for it in Visual Studio. This implementation is very stable and VS is my second favorite IDE. Oddly enough, I only use VS for some basic Node projects.
4.CodeEnvy - a web-based IDE
5.Cloud9 - a web-based IDE
6.SublimeText 2 - A no-frills text editor that is becoming more and more popular among developers due to its lightweight nature.
These are some of my favorite IDEs for working on Node-based projects. Just an example.
Start with an example
In the remainder of this blog post, we will create a simple REST service using Java EE and Node.js. This REST service will simply read information from the MongoDB database and return the results to the requester. The installation and configuration of the Java application server and MongoDB database are beyond the scope of this article.
Create our Java application
Step 1: Configure the pom.xml file
Let's call this example restexample, and I will use the JBoss EAP application server. The first thing we need to do is configure our pom.xml file for dependency management using the Maven build system. The following is the pom.xml file that contains the dependencies needed in our restexample application:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/ /maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>restexample</groupId> <artifactId>restexample</artifactId> <packaging>war</packaging> <version>1.0</version> <name>restexample</name> <repositories> <repository> <id>eap</id> <url>http://maven.repository.redhat.com/techpreview/all</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>eap</ id> <url>http://maven.repository.redhat.com/techpreview/all</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven .compiler.source>1.6</maven.compiler.source> <maven.compiler.target>1.6</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.jboss.spec</groupId> <artifactId>jboss-javaee-6.0</artifactId> <version>3.0.2.Final-redhat-4</version> <type>pom</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.9.1</version> </dependency> </dependencies> </project>
Cool, quite detailed, but I hope you can understand the code. In this blog post I assume that readers already know Java, so I won’t explain the details.
Step 2: Create beans.xml file and set up our servlet mapping
As part of the example, we will use CDI (Context Dependency Injection) on our database access class. According to the official CDI configuration instructions, if an application wants to use CDI, it must include a beans.xml file in the WEB-INF directory of the application. So let's create this file and configure it with the information we need. Go to your /src/main/webapp/WEB-INF directory and create a beans.xml file and add the following code:
<?xml version="1.0"?><beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd"/>
We also need to set up the servlet mapping for our RESI API in the web.xml file. Add the following servlet mapping element to the file in the /src/main/webapp/WEB-INF directory:
<servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/ws/*</url-pattern></servlet-mapping>
Step 3: Create the DBConnection class
At this point, we have set up the project and our pom.xml file already contains the driver dependencies of the MongoDB database. Remember to make sure that the required drivers have been packaged in our application. The next thing we need to do is create a class to manage the database connection. Create a new file named DBConnection.java, place this file in the /src/main/java/com/strongloop/data directory, and then add the following code to this file:
NOTE: Make sure your MongoDB database installation is configured with the appropriate connection authorization details!
package com.strongloop.data; import java.net.UnknownHostException; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import com.mongodb.DB; import com.mongodb.Mongo ; @Named@ApplicationScopedpublic class DBConnection { private DB mongoDB; public DBConnection() { super(); } @PostConstruct public void afterCreate() { String mongoHost = "127.0.0.1" String mongoPort = "27001" String mongoUser = "strongloop; String mongoPassword = "rocks"; String mongoDBName = "restexample" ; int port = Integer.decode(mongoPort); Mongo mongo = null; try { mongo = new Mongo(mongoHost, port); } catch (UnknownHostException e) { System.out.println("Couldn't connect to MongoDB: " + e.getMessage() + " :: " + e. getClass()); } mongoDB = mongo.getDB(mongoDBName); if (mongoDB.authenticate(mongoUser, mongoPassword.toCharArray()) == false) { System.out.println("Failed to authenticate DB "); } } public DB getDB() { return mongoDB; } }Step 4: Import data into MongoDB (mmmm beer)
In our project we want to load a list of all beers with the name Pabst. If you're new to the beer industry, you might want to try Pabst Brewing's American Light Ale. These beers feature blue ribbons and Colt designs, and they include all types of malt beverages.
First you need to download a json file that contains all the data that needs to be returned. You can use the following URL to achieve this:
https://dl.dropboxusercontent.com/u/72466829/beers.json
After downloading, use the mongoimport command to import it into the database. The command is as follows:
$ mongoimport --jsonArray -d yourDBName -c beers --type json --file /tmp/beers.json -h yourMongoHost --port yourMongoPort -u yourMongoUsername -p yourMongoPassword
You can see the following results:
connected to: 127.0.0.1:27017Tue Jun 10 20:09:55.436 check 9 24Tue Jun 10 20:09:55.437 imported 24 objects
Step 5: Create Beer model object
We have created a database connection class and loaded the beer information into the MongoDB database. It is time to create a model object to control our beer information. Create a new file named Beer.java and place it in the /src/main/java/com/strongloop/data directory. After creating the file, add the following code to it:
package com.strongloop.data; public class Beer { private String id; private String name; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }}Note: The provided JSON file contains more information that we will use, so check it out and add some extra functionality to it to broaden your learning experience.
Step 6: Create REST service
Guess what to do? Ok, we are finally ready to create a REST-based web service that will allow us to get the beer information loaded in the previous step. To do this, we need to create a new file called BeerWS.java and place it in the /src/main/java/com/strongloop/webservice directory. After creating it, add the following code:
package com.strongloop.webservice; import java.util.ArrayList;import java.util.List;import javax.enterprise.context.RequestScoped;import javax.inject.Inject;import javax.ws.rs.GET;import javax.ws .rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import com.strongloop.data.DBConnection;import com.strongloop.data.Beer;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb. DBObject; @RequestScoped@Path("/beers")public class BeerWS { @Inject private DBConnection dbConnection; private DBCollection getBeerCollection() { DB db = dbConnection.getDB(); DBCollection beerCollection = db.getCollection("beers"); return beerCollection; } private Beer populateBeerInformation(DBObject dataValue) { Beer theBeer = new Beer (); theBeer.setName(dataValue.get("name")); theBeer.setDescription(dataValue.get("name")); theBeer.setId(dataValue.get("_id").toString()); return theBeer; } // Get all beers @GET() @Produces("application/json") public List<Beer> getAllBeers() { ArrayList<Beer> allBeersList = new ArrayList<Beer>(); DBCollection beers = this.getBeerCollection(); DBCursor cursor = beers.find(); try { while (cursor.hasNext()) { allBeersList.add(this.populateBeerInformation(cursor.next ())); } } finally { cursor.close(); } return allBeersList; }}Step 7: Browse Beer Information Silly
Oh, done. We have written a REST service that can retrieve all beer information from the database. Now to deploy your code to your application server, open the following address in your browser to see if it works fine:
http://yourserverlocation/ws/beers
If everything is fine, you will see a list of all beer information, as shown below:
Create Node application
If you follow the above steps to program in java, you will realize that although creating applications using javaEE is progressing very quickly, it is still very troublesome to create a simple application like a REST service. Don't get me wrong, I still like using javaEE, but find that for many scenarios, such as creating REST services that return json data, Node is more suitable. Next, we are going to create a simple web service using StrongLoop's LoopBack API. Plus, I'll show you how to install Node on Apple OSX.
Step 1: Install Node
The easiest way to install Node is through a binary package that is compatible with most operating systems. Open your browser and visit the webpage below to download the applicable version according to your operating system:
http://nodejs.org/download/
After the download is complete, you will see the following:
If you are using Mac OSX, click on the generic .pkg file. This will save the installer to your computer. After downloading the file, double-click it to start the installation program. You will see the following installation dialog box:
Continue the installation by default. After successful installation, click the close button to exit the installation program.
Pretty simple, right?
Step 2: Install LoopBack using NPM
Now that Node has been installed in the local system, the next step is to install the LoopBack package provided by StroopLoop. LoopBack is an open API source code package. When you learn to use Node to develop and deploy software, LoopBack can make programming easier.
In order to install LoopBack, we will use the npm command line, which is part of the core Node language. NPM is an official package management tool used to install class libraries or templates that applications depend on. If you are a java programmer, you can compare NPM to Maven. Using Maven to build a project, developers can configure the jar packages or templates that the project depends on in pom.xml. When the project starts compiling, Maven will download all dependent files and introduce the jar package into the project. NPM works the same as Maven. For some special projects, it uses the package.json file to configure the files that the project depends on. You can also use the command line to download dependent files to the local system. If you don't understand this, don't worry, we will describe the package.json file in detail in the next steps.
To install LoopBack, we use a simple command line to download and install all dependent files. Open your window command line window and enter the following command:
$ npm install -g strongloop
Tip: During installation, you may need to use another user account to execute this command.
What does this command line mean? The -g parameter tells npm that we want to install the strong-cli package. The -g parameter makes this package compatible with any system and application. Once you run the above command, NPM will download all dependent files. The download time depends on your internet speed and may take several minutes.
Step 3: Create the application
Creating an application using the LoopBack API is simple. Open your window command line window and use the following command to create a new application restexample.
$ slc loopback
Next it will prompt for the name of the project root path. In this example, restexample is used. Next it will prompt for an application name. Use the default restexample.
The slc command has now created a LoopBack application named restexample and configured the application. If you execute the above command again and still use restexample to name it, LoopBack will create a new directory. You can use the cd command to modify the root path of the application.
$ cd restexample
Now that we have created an application, we configure MongoDB as the data source for the application.
Step 4: Define data source
In order to connect to MongoDB, we need to add a data source to the application and run the following command:
$ slc loopback:datasource
At the pop-up prompt, you can enter any customized data source name. Here, choose myMongo
[?] Enter the data-source name: myMongo
This way we attach the backend's data source definition to a real connector powered by StrongLoop. Here we select the MongoDB connector from the list.
[?] Select the connector for myMongo:PostgreSQL (supported by StrongLoop)Oracle (supported by StrongLoop)Microsoft SQL (supported by StrongLoop)MongoDB (supported by StrongLoop)SOAP webservices (supported by StrongLoop)REST services (supported by StrongLoop)Neo4j ( provided by community)(Move up and down to reveal more choices)
Step 5: Point to the real data source
In order to connect to MongoDB, we need to point to the actual MongoDB instance. LoopBack defines all data source configuration information in the datasource.json file. This file is located in the root/server directory of the application. Open this file and proceed as follows. MongoDB adds a data source:
{ "db": { "name": "db", "connector": "memory" }, "myMongo": { "name": "myMongo", "connector": "mongodb" "url": "mongodb: //localhost:27017/restexample" }}Note: Make sure to provide the correct connection URL to the MongoDB database. For this example, I created a database named restexample, which is used as the data source.
Step 6: Import data into MongoDB (mmmmm beer)
As mentioned in the Java part of this article, we need to load the data set into the MongoDB database. If you have completed this step according to the method mentioned in this article, and then plan to use the same database, you can ignore step 6 and jump directly to Step 7.
First, you need to download a JSON file containing all the information to be returned, which can be obtained from the following URL:
https://dl.dropboxusercontent.com/u/72466829/beers.json
After the data set file is downloaded, directly use the following mongoimport command to load it into the database:
$ mongoimport --jsonArray -d yourDBName -c beers --type json --file /tmp/beers.json -h yourMongoHost --port
You should see the following results:
connected to: 127.6.189.2:27017Tue Jun 10 20:09:55.436 check 9 24Tue Jun 10 20:09:55.437 imported 24 objects
Step 7: Create our own beer model
In the Java world, we can think of the object model. It represents this object, but here, this object is beer. LoopBack provides a simple way to create model objects through the command line. Open a terminal window and enter the project folder, enter the following command:
$ slc loopback:model
This will open an interactive session to define the model. The first thing you need to enter is the model name, enter "beer" here. Next, you will be prompted for the data source to which this model should be attached. Here, select the myMongo data source created previously.
[?] Enter the model name: beer[?] Select the data-source to attach beer to:db (memory)myMongo (mongodb)
Next, it prompts whether to expose this API through REST. Of course, we hope so here.
[?] Expose beer via the REST API? Yes
Finally, select the network plural name for the model. Here the model is named beer, so the plural is beans (default). Press Enter to accept the default.
[?] Custom plural form (used to build REST URL):
Next you will be prompted to define model properties. For this example program, we focus on the name and description of the beer.
Enter an empty property name when done.[?] Property name: name
As long as you hit Enter, you will be prompted to enter the data type of each specified attribute. The first item is name, here select the string type. Select the string type, and then press
Enter.[?] Property type: (Use arrow keys)stringnumberbooleanobjectarraydatebuffergeopoint(other)
Next, create the description attribute in the same way, and then you will be asked to enter the data type. It is also a string type, select the string option, and then click
Enter.Let's add another beer property.Enter an empty property name when done.[?] Property name: descriptioninvoke loopback:property[?] Property type: string[?] Required? Yes
Congratulations! You have completed the creation of model objects using LoopBack combined with Node. If you want to see what was actually created during this process, you can open the beer.json file located in the application root/common/models directory and scroll to the end of the file. , you will see the following model:
{ "name": "beer", "base": "PersistedModel", "properties": { "name": { "type": "string", "required": true }, "description": { "type" : "string", "required": true } }, "validations": [], "relations": {}, "acls": [], "methods": []}As you can see here, we have created a model, and at the same time, the name and description attributes have been assigned to this model.
In the /server/model-config.js file, you can notice that the file contains some additional fields, including public and datasource. The public field specifies that we want to expose this model to the outside through a REST network service. The datasource field is Specify the data source that will be used for CRUD operations on this model.
"beer": { "dataSource": "myMongo", "public": true }Step 8: Bask in the joy of seeing beers
Congratulations! You have created your first Node.js application that contains a REST web service that can get beer information. Finally, all we need to do is deploy the application.
Fortunately, deployment is already easy. It can be done by executing the following command in the application root directory:
$ slc run
As soon as the application is running, you can confirm whether the deployment was successful by going to the following URL with your browser:
http://0.0.0.0:3000/api/beers
Pretty cool, isn't it?
LoopBack also contains a page that allows you to view all available services of the application, including the Beer model and the REST service we created. Point your browser to the following URL to view:
http://0.0.0.0:3000/explorer
After the page loads successfully, you will see the following interface. We have created the beans node as part of the blog. I have highlighted the /beers endpoint:
You can click /beers to expand the available APIs. You can operate and test them, as shown in the figure below:
in conclusion
In this blog post, I show how to use Java EE to create a REST service that returns beer product listing data from Pabst Beer Company. Later, I used node.js and the loopback framework based on node.js to implement the rest service with the same function using very little code. The most important thing is that the LoopBack API also provides a default implementation for the addition, deletion, checking and modification of beer entities, so that we can get a rest service with complete addition, deletion, checking and modification functions without writing a single line of code.
The following list compares the respective features of javaEE and node.js mentioned in the blog post:
Feature | Java EE | Node.js |
Complete IDE support | Yes, multiple IDEs are available, including Eclipse, Sublime and Idea | Yes, multiple IDEs to choose from, Visual Studio, Eclipse, Sublime |
Dependency management | Maven | NPM |
Used by enterprise-level projects | Yes | Yes |
Vast component ecosystem | Yes | Yes |
Requires JVM | Yes | No |
Common development framework | Spring, JEE | Express |
Database support | Yes | Yes |
ORM framework | Yes | Yes |
testing framework | Yes | Yes |
What’s next?
The upcoming Node v0.12 will bring at least 8 exciting new features, what will they be? Visit the "What's New in Node.js v0.12" page to learn more.
Interested in Node-related training and certification? StrongLoop offers a variety of services to meet your needs.