Java developers combine Node.js programming introductory Tutorials _java

Source: Internet
Author: User
Tags mongodb object model install node jboss

First of all, I have to admit that as a Java developer with more than 10 years of development experience, I have formed the inherent way to solve most of the problems, even though they are often cumbersome and cumbersome. For example, if you want to read a file, it should be to initialize a BufferedReader instance and pass in a filereader, which is almost logical, I write code in many projects that I think is "enterprise class" and enjoy the process. I can say that I am a Java brain residue that is dismissive of other languages.

If you are reading this blog, you may have fallen into a myth that I had long ago, as a qualified developer should continue to learn new technologies and choose the right technology based on actual job requirements. Although I have been getting older and may someday be tired of Java. But now I really found a new exciting thing, node.js. For me, like a child getting a novelty toy, in this blog post, I'll show you how to use Java EE to create a simple rest service to read the MongoDB database. Then I will use node.js to achieve the same function, you will be easier to understand this new development language exciting.

Starting from the basics-what is Node.js?

First of all, I would like to make it clear that node.js is not the kind of "trendy fashion", only the "Chao people" to use the language. Although it began with this knowledge, I am pleased to report that Node.js is a mature language-and that in the current internet age it has found its own way into large enterprises, supporting some of the highest flow of Web sites. Node.js is a very useful tool in your skill set, and the ease with which you can build stable, secure, and High-performance code will surprise you.

In a word, node is a language for server-side activity. It uses JavaScript language and has a lot of libraries available, such as the NPM model. You can compare those NPM models to a. jar package in Java. When you need a part of the functionality and don't like to write all of this code yourself, it's very likely that the NPM model already provides the features you're looking for.

Node applications typically execute with the need to maximize efficiency by leveraging non-blocking I/O and asynchronous events. One thing that Java developers need to know is that the node application runs in a single thread. However, the back-end node code uses multiple threads to operate, such as network and file access. In view of this, node is the perfect choice for those applications that require real-time experience.

Continue--ide Support

You might be like me, "living" and "breathing" in the IDE, which may have originated in Java, which requires us to write constant code in the software development process to complete the function. Once we find the benefits of code completion, we slowly learn to use the IDE for file management, debugging, and other very useful features. You can say that I like to use an IDE and continue to use it when I work with NodeB. The following is the first of the most current IDE support node:

1.eclipse--This should be easy to use when you are already using it in Java. You only need to install the Node.js plug-in.
2.JetBrains IntelliJ idea--is a very popular commercial IDE. So far, this is my favorite IDE.
3.Microsoft Visual studio--Yes, you saw it wrong. Node has grown to Microsoft's native support in Visual Studio added to it. This implementation is very stable, and VS is my second favorite IDE. Oddly enough, I use vs only as a base node project.
4.codeenvy--a web-based IDE
5.cloud9--a web-based IDE
6.SublimeText 2--has no extra decorative text editor, because of its lightweight, more and more well-known among developers.

This is the favorite IDE I work on on the Node Foundation project. Just give me an example.

Starting from an example

In the remainder of this blog post, we will combine Java EE and node.js to create a simple rest service. This rest service will simply read the information from the MongoDB database and return the results to the requestor. The installation and configuration of Java application servers and MongoDB databases is not covered in this article.

Create our Java application

The first step: Configure the Pom.xml file

We'll call this paradigm restexample, and I'll use the JBoss EAP application Server. The first thing we need to do is configure our pom.xml files to use the Maven build system's dependency management. Here is the Pom.xml file that contains the dependencies we need in this 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>restexamp le</name> <repositories> <repository> <id>eap</id> <url>http ://maven.repository.redhat.com/techpreview/all</url> <releases> <enabled>true</enab led> </releases> <snapshots> <enabled>true</enabled> </sna pshots> </repository> </repositories> <pluginRepositories> &LT;PLUGINREPOSITORY&G
        T
     <id>eap</id>   <url>http://maven.repository.redhat.com/techpreview/all</url> <releases> <enable d>true</enabled> </releases> <snapshots> <enabled>true</enabled&gt
        ; </snapshots> </pluginRepository> </pluginRepositories> <properties> <projec T.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> <artifacti D>jboss-javaee-6.0</artifactid> <version>3.0.2.Final-redhat-4</version> <type>p om</type> <scope>provided</scope> </dependency> <dependency> ; groupid>org.mongodb&Lt;/groupid> <artifactId>mongo-java-driver</artifactId> <version>2.9.1</version&gt
      ;
 </dependency> </dependencies> </project>

Cool, pretty detailed, but I want you to be able to understand the code, and in this blog post I assume that the reader already knows Java, so I'm not going to explain the details.

Step Two: Create the Beans.xml file and set our servlet map

As part of the example, we will use CDI for our Database access classes (context-dependent injection). According to the official CDI configuration instructions, an application that uses CDI will include a beans.xml file in the application's Web-inf directory. So we're going to create this file and configure it according to 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=
 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 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 three: Create the DbConnection class

By this step, we have built the project and our Pom.xml file already contains the drive dependencies of the MongoDB database, and remember to ensure that the required drivers are packaged in our application. The next thing we're going to do is create a class that manages the connection to the database. Create a new file named Dbconneection.java, place the file in the/src/main/java/com/strongloop/data directory, and add the following code to the file:

Note: Make sure you install the MONGODB database and configure 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 @ApplicationScoped public class DbConnection {private DB MongoDB;
  Public DbConnection () {super (); @PostConstruct public void Aftercreate () {String mongohost = "127.0.0.1" string mongoport = "27001" S
    Tring 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; }
 
}

Fourth step: Import the data into the MongoDB (mmmm beer)

In our project, we want to load a list of all beers named Pabst. If you are not familiar with the beer industry, you can try the Pabst Brewing Company produced the American Light beer. These beers have blue ribbons and colt {sensitive Word} patterns, and they contain all the types of maltose beverages.

First you need to download a JSON file that contains all the data you need to return. You can use the following URL to achieve this:
Https://dl.dropboxusercontent.com/u/72466829/beers.json

When the download is complete, use the Mongoimport command to import it into the database, with the following commands:

$ 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:27017
Tue June 20:09:55.436 Check 9
Tue June 20:09:55.437 imported

Step 5th: Create the Beer model object

We have created a database connection class and have loaded the beer information into the MongoDB database, and it's time to create a model object to control our beer information. Create a new file named Beer.java and put it in the/src/main/java/com/strongloop/data directory. After you create 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 good JSON file contains more information that we will use, so we can look it up and add some extra functionality to broaden your learning experience.

Step 6th: Create a Rest service

Guess what? Yes, we're finally ready to create a rest-based Web service that allows us to get the beer information that was contained in the previous step. To do this, we need to create a new file named Beerws.java and put it under the/src/main/java/com/strongloop/webservice directory. After you have created 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 Beer @GET () @Produces ("Application/json") public list<beer> getallbeers () {ARRAYLIST&LT;BEER&G T
 
    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; }
}

7th step: Browse the beer information silly music

Oh, it's done. We've written a rest service to get all the beer information from the database. Now deploy your code to your application server, open the following address in the browser to see if it works:
Http://yourserverlocation/ws/beers

If everything is OK, you will see a list of all the beer information, as shown in the following figure:

Create a Node application

If you follow the steps above to program in Java, you will realize that using Java EE to create an application is very fast, but creating a simple application like a rest service is cumbersome. Don't get me wrong, I still like Java EE, but I find that node is more useful for many scenarios, such as creating a rest service that returns JSON data. Next, we're going to use the Strongloop loopback API to create a simple Web service. In addition, I'll show you how to install node on the Apple OS X system.

Step 1: Install Node

The simplest way to install node is through a binary package that is compatible with most operating systems. Open the browser to the following Web page, 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 OS X, click on the generic. pkg file. This will save the installer to your native computer. After downloading the file, double-click it to start the installer, and you will see the following Setup dialog box:

All the way to the default installation, after the successful installation, click the Close button to exit the installer.

It's pretty simple, isn't it?

Step 2: Use NPM to install loopback

Now that node is installed on the local system, the next step is to install the loopback package provided by the Strooploop company. Loopback is an open API source package, and when you learn to use node to develop and deploy software, loopback can make programming simpler.

To install loopback, we use the NPM command line, which is part of the node language core. NPM is an official package management tool that installs the class libraries or templates that your application relies on. If you're 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 relies on in Pom.xml. When the project starts to compile, MAVEN downloads all dependent files and introduces the jar package into the project. NPM works the same as Maven, and for some special projects, it uses the Package.json file to configure the files that the project relies on. You can also use command-line methods to download dependent files to the local system. If you don't understand the content, don't worry, in the next steps we'll describe the Package.json file in detail.

To install loopback, we use a simple command line to download and install all dependent files. Open your Windows command Line window and enter the following command:

$ NPM install-g Strongloop

Tip: When installing, you may need to use another user account to perform 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 the package compatible with any system and application. Once you have run the above command, NPM downloads all dependent files. The download time depends on the speed, which may take several minutes.

Step 3: Create the application

Creating an application using the loopback API is simple. Open your Windows command Line window and use the following command to create a new application restexample.

$ SLC Loopback

It then prompts for the name of the project root path. In this example, the restexample is used. It then prompts for the application name. Use default value restexample.

The SLC command has now created a loopback application called Restexample, and this application has been configured. If you execute the above command again and still use the Restexample name, loopback will create a new directory. You can use the CD command to modify the root path of an application.

$ CD Restexample

Now that we have created an application, we will then configure MongoDB as the data source for the program.

Step 4: Define the data source

To connect MongoDB, we need to add a data source to the application and run the following command:

$ SLC Loopback:datasource

In the pop-up prompts, you can enter any custom data source name, here Select Mymongo

[?] Enter the Data-source Name:mymongo

This allows us to attach the backend data source definition to the real connector supported by Strongloop. Here we select the MongoDB connector from the list.

[?] Select the connector for Mymongo:
PostgreSQL (supported through Strongloop)
Oracle (supported by Strongloop)
Microsoft SQL (supported by Strongloop)
MongoDB (supported through Strongloop)
SOAP webservices (supported by Stronglo OP)
REST Services (supported by Strongloop)
neo4j (provided through community) (move up and down to
reveal more Cho Ices

Step 5: Point to the real data source

To connect MongoDB, we need to point to the actual MongoDB instance. Loopback defines all the data source configuration information in the Datasource.json file. This file is located in the application's Root/server directory. Open this file, Add a data source to the MongoDB as follows:

{"
 
 db": {"
  name": "DB",
  "connector": "Memory"
 },
 "Mymongo": {
  "name": "Mymongo",
  "connector": "MongoDB"
  "url": "Mongodb://localhost:27017/restexample"
 }
}

Note: Be sure to provide the correct connection URL for the MongoDB database. For this example, I created a database called Restexample, which is used as a data source.

Step 6: Import data to MongoDB (Mmmmm beer)

As the Java section of this article says, we need to load the dataset into the MongoDB database. If you have done this step in the way described in this article and then intend to use the same database, you can skip step 6 and jump directly to step 7.

First, you need to download a JSON file that contains all the information you want to return, which can be obtained from the following URL:
Https://dl.dropboxusercontent.com/u/72466829/beers.json

Once the dataset file is downloaded, 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 be able to see the following results:

Connected to:127.6.189.2:27017
Tue June 20:09:55.436 Check 9
Tue June 20:09:55.437 imported

Step 7: Create our own beer model

In the Java world, you can think of an object model. It represents this object, just here, this object is beer. Loopback provides an easy way to create model objects from the command line. Open the terminal window and go to the Engineering folder and enter the following command:

$ SLC Loopback:model

This will open an interactive session to define the model. First you need to enter the model name, where you enter "beer". Next, you will be prompted for the data source that the model should be attached to, where the Mymongo data source was previously created.

[?] Enter the Model Name:beer
[?] Select the Data-source to attach beer to:
db (Memory)
Mymongo (MongoDB)

Next, you'll be prompted to expose the API through rest. Of course, this is what we want.

[?] Expose beer via the REST API? Yes

Finally, select the network number name for the model, where the model name is beer, so the plural is beers (default). Tap the ENTER key to accept the default value.

[?] Custom plural form (used to build REST URL):

Next you are prompted to define the model properties. For this sample program, we focus on the name and description of the beer.

Enter Empty property name is done.
[?] Property Name:name

As soon as you hit enter, you are prompted for the data type for each specified property. The first item is name, and the string type is selected here. Select a string type and then tap

Enter.
[?] Property type: (use arrow keys)
string
number
Boolean
object
array
date
buffer
Geopoint
(Other)

Next, create the Description property in the same way, and then ask for the input data type. It is also a string type, select the string option, and then tap

Enter.
Let ' s add another beer.
Enter Empty property name is done.
[?] Property Name:description
Invoke Loopback:property
[?] Property Type:string
[?] Required? Yes

Congratulations! You have completed the creation of the model object using loopback binding node. If you want to see what you really created in 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 the name and description attributes have been given to this model.

In the/server/model-config.js file, you can note that the file contains some extra fields, Includes public and DataSource. Where the public domain specifies that we want to expose this model to the outside through a rest network service. The datasource domain specifies the data source to which the crud operations of this model will be used.

' Beer ': {
  ' dataSource ': ' Mymongo ',
  ' public ': true
 }

Step 8: Immerse yourself in the joy of seeing beers

Congratulations! You have created the first Node.js application, which contains rest network services that can get beer information. Finally, what we need to do is deploy this application.

Fortunately, deployment is already very easy. You can do this by executing the following command in the application root directory:

$ SLC Run

As soon as the application is running, you can go to the following URL to confirm the success of the deployment through the browser:

Http://0.0.0.0:3000/api/beers

Pretty cool, isn't it?

Loopback also includes a page that allows you to view all available services for your application, including the beer model and the rest service that we created, and we can view the browser by pointing to the following URL:

Http://0.0.0.0:3000/explorer

After the page is loaded successfully, you will see the following interface, we have created the Beers node as part of the blog, I highlighted the/beers endpoint:

You can click/beers to expand the API that you can invoke, and you can manipulate and test it as shown in the following illustration:

Conclusion

In this blog post, I showed you how to use Java EE to create a rest service that can return Pabst Beer's beer product inventory data. I then used the Node.js and the Node.js loopback framework to implement the same functional rest services with little code. Most importantly, the loopback API also provides a default implementation of the beer entity's additions and deletions, which allows us to get a rest service with complete additions and deletions without having to write a single line of code.

The following list compares the Java EE and node.js features that are involved in the blog:

Feature

Java EE

Node.js

Perfect IDE Support

Yes, multiple IDE options, including Eclipse, Sublime and Idea

Yes, multiple IDE selections, Visual Studio, Eclipse, Sublime

Dependency Management

Maven

Npm

Enterprise-class projects are used

Yes

Yes

A huge ecosystem of components

Yes

Yes

Requires JVM

Yes

No

Common development Framework

Spring, JEE

Express

Database support

Yes

Yes

ORM Framework

Yes

Yes

Test framework

Yes

Yes

What's next?

The upcoming node v0.12 will bring at least 8 exciting new features, what are they? Visit the "What ' New in node.js v0.12" page for more information.
Interested in node-related training and certification? Strongloop Company offers a variety of services to meet your needs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.