Sunday, April 13, 2014

Different ways to run scripts in node.js

Well now I have some weeks learning node, the easiest way to run a script is through  the node command, lets start with a simple script:



Save it as server.js If you want to run this script all you have to do is go to the directory where the script is and run the following command:

                           node server.js

Another way to run a script is through the npm command, it requires a file named package.json at the root of the project, this way is more sophisticated because in the package.json file you can specify a command to run a script, so you can have several commands each one mapped to a script.
Also it helps to configure dependencies, versions and a lot of other stuff, you can find more about the package.json configuration in the following link:
                   https://www.npmjs.org/doc/json.html

Well for the purpose of the blog the file package.json will be very simple just to show how it works, so it will contain the following:


In the file the start command is mapped to the server.js script, once the file is saved in the directory where sript is located the following command will run the script:

                          npm start

Another way to run a script is with the help of packages one of them is nodemon (http://nodemon.io/), it stands for node monitor.

The description of nodemon says that it is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. Using nodemon instead of node to run your code, and now your process will automatically restart when your code changes.

To install nodemon jus run the following command:

                         npm install -g nodemon

The -g means that it will install nodemon in a global way, you don't have to install it for every project.

Once installed you can see it working, just replace the node command for nodemon and run the script:

                         nodemon server.js

To see it working type the address http://127.0.0.1:1337/ in your browser and see the output, then modify the script to output instead "Hello world" to something else, reload the browser and see that the changes are reflect, so this is the big advantage of using nodemon you don't have to waste any time running the scripts while developing them.

Another package that does the same as nodemon is run (https://www.npmjs.org/package/run), install it just like nodemon:

                         npm install -g run

Then run the script with the run command

                         run server.js

Do the same exercise go the address http://127.0.0.1:1337/  see the output and modify the script, reload the page and see the changes.

So far in my way to node these are the different ways to run scripts, I hope you can learn something new from it.

Friday, March 21, 2014

Creating processes in node.js

In some of my previous posts I started comparing some of the features of node.js with java and since then my interest has started to grow for node.js.

One thing I just learned is that node runs in a single thread mode, it uses an event-driven paradigm to handle concurrency.

Well that's fine but what about parallel processes how can you take advantage of this when you are in a single thread program, well node.js has some mechanisms to create processes and take advantage of parallel computing, and I will tell you how.

First we will need a process to run as a worker, there could be many instances running of this process at the same time.

For the purpose of this blog this process will have just a log to console, also any kind of process can be created not just node process, but also for the blog I will use just this.

For creating a child process the child_process module is required, this module has different ways to create process.

The exec method of the child_process runs a command in a shell and buffers the output. It has the following signature:

               child_process.exec(command, [options], callback)


In the example the command "node worker.js i"  is executed where i is a parameter passed to the process.
Also a callback function is passed and it is called when the process terminates and allows to read and process the output from it.

After running the example the following should be printed in console for each process created.

stdout: Process 0 at work
stderr:

Child process exited with exit code 0

The spawn method of the child_process module launches a new process with a given command, it has the following signature:

               child_process.spawn(command, [args], [options])


After running the example the following should be printed in console for each process created.

stdout: Process 0 at work

child process exited with code 0

Exec() and spawn() both create processes, but they differ in what they return, spawn returns streams (stdout & stderr), while exec returns a buffer with a max size. Spawn() should be used when the process returns large amount of data.

Another difference is that spawn() starts receiving the response as soon as the process starts executing, and exec() otherwise waits for the process to end and tries to return all the buffered data at once

The fork method is a special case of the spawn() functionality, it only creates Node processes. Its signature is the following:


              child_process.fork(modulePath, [args], [options])

After running the example the following should be printed in console for each process created.

Process 0 at work
child process exited with code 0

Node.js also has the cluster module and also allows to create processes, the definition of the cluster module says: "A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load".

From the example you can notice that the cluster module is imported, once imported you can call fork() method to create a new child process, after calling fork() the same process will run but as a child, to distinguish if the process is running as a Master or child the cluster module has the isMaster() and isWorker() methods.

After running the example above, the following should be printed.

Master Forking!!!!
Worker 4984 is online.
....
Child process running!!!
....


You can find more information about these modules in the following links:
http://nodejs.org/api/child_process.html
http://nodejs.org/api/cluster.html

Node.js says that runs in a single thread mode, but as with this brief example, I show that node.js has different mechanisms to create processes and to take advantage of multiple processors.





Friday, February 7, 2014

Restful web services in node.js

In my latest blog restful web services with jetty and jersey I was trying to create rest web services simple as node.js, so I decide to show you how simple is to write this services with node.js.

First you will need node installed, you can install it from here nodejs.org, I'm going to use the express framework (expressjs.com) for node to help me develop the services, so to install express just go to the folder in which your projects will reside and with the help of the npm (node packaged modules) type the following command:

                 [jluna@host projects]$ npm install express

With this the express framework will be installed locally at your projects folder, now you can start creating the restful web services, first create a file in the projects folder for example services.js.

To use express use the following:


Once imported express to create a service just use one of its methods like this:

Finally, just configure the port and listen:

                 app.listen(process.env.PORT || 9999);

So here it is the whole script that contains the services:



As you can see the first service receives a parameter, this is specified in the path '/employee/getEmployee/:name', and to obtain the value of the parameter just get it from the request:

                  var name = req.params.name;

In javascript to create objects you don't have to define a class like in java just specify its properties when the object is created:

                 employee = new Object();
                 employee.name = name;
                 employee.age = 25;
                 employee.deparment = "HR";
                 employee.wage = 15000.00;

This has its benefits and its risks but I won't get into there, also there are other ways in javascript to create objects, you can define a function.

Finally to send the response to the client the json() method is used to parse the objects to json:

                 res.json(employee);

In the post method the interesting thing to see is that it is receiving an object, to access this object just get it from the body

                 var employee = req.body;

And then you can access the object like this:

                 console.log("Got name: " + employee.name);

Well to run the script just use the following  command in the path where the script is:

                 [jluna@host projects]$ node services.js

And the script should be up and running.

To test the script you can use the following commands:

curl -i -X GET -H 'Content-Type: application/json'  http://localhost:9999/employee/getEmployee/James

curl -i -X POST -H 'Content-Type: application/json'  -d '{"address": {"city": "Massachusetts","state": "Springfield","street": "Evergreen","zip": "66450"},"age": "25","deparment": "HR","name": "James","salary": "0.0"}'  http://localhost:9999/employee/postEmployee

In the console you should see the output, also here it is a java client you can use:


As you can see is very simple to create the services in node.js.

Monday, January 20, 2014

RESTful web services with jetty and jersey

Recently I was thinking if there is a way to start a web server in java just as easy as it is in node.js, if you don't know node.js you can check this link nodejs.org, so in node you just write a few lines and you have a server like this:


I thought that with something like this you can easily test your code without the burden of deploy it, and also saving some resources. 

So I start looking if there is something similar in java and I found several projects to start a web server or a minimal server, but I decided to go with jetty www.eclipse.org/jetty, so I'm going to show you how to run some restful web services using jetty. 

Also I'm going to use jersey jersey.java.net which simplifies the development of RESTful Web services and their clients in Java.

So you can download the jars from these projects or configure them through maven to your project to start using them, in these links www.eclipse.org/jetty , jersey.java.net you can check the instructions to do it.

So to create a web server with jetty is as easy as the following code:


If you run the code and check the http://localhost:8080/hello url you can see that your servlet is running, so basically in the code you create a Server object and set the port the Servlets and the servlets to run and that's it.

With jetty you can do much more than this, but for the purpose of this blog I will no go further, you can check the jetty documentation.

The following would be to create and deploy the RESTful web services, now we will use jersey to this.

The first thing to do is to create the services that we will deploy, for the example I will create two services one using JSON and other using XML, I will create two objects used to transfer the data.



In the classes above you can see two classes Employee with a nested class Address and Student, the only thing to notice from these classes are the annotations @XmlRootElement and @XmlAttribute, these annotations are used to do the parsing from object to the protocol used (XML, JSON) and from protocol to object.

The following would be to create the classes for the services.




The classes above use the standard Java EE specification for RESTful web services they use the @Path annotation at the top level to set the service path and each method use the @GET, @POST annotations to describe the type of service and the @Produces annotation to set the type of protocol to use.

The method getStudent of the class XMLStudentSvc has also the @Path("/student/{name}")  this specifies a path for this method, also note that it receives a parameter named "name" through the path and this parameter will be mapped to the parameter of the method.
For more about how define RESTful web services check the specification https://jcp.org/en/jsr/detail?id=311

Another thing to notice is that both classes are in a package called "rest", so the following to do would be to deploy these services in jetty as long as the jersey configuration.

This is the class for the server:



See in the class above all what it needs to configure jersey, a ServletHolder object is created to set the parameters, note that is indicated the package where the services are located and jersey will automatically deploy them. The ServletHolder object is passed to a ServletContextHandler object, and that's it with this the services should be up and running.

The last thing to do is to create a client for our services, for the client I will use jersey to help.

This is the client for the JSON service:


The client will call two methods, the first will be to the GET method and it uses the url with the path specified for this method ("http://localhost:9999/employee/getEmployee"), this method returns a response in JSON, then this response is unmarshal to a object with the call to "response.getEntity(Employee.class)".

If the JSON response is needed instead of the actual object all what is need to do is change the type to String in the unmarshal "response.getEntity(Employee.class)".

The other method specified in this client is the POST method this call doesn't return a thing,  it uses the url with the path specified for this method ("http://localhost:9999/employee/postEmployee") and it sends back the same object the client is receiving, you should see an output in the server since the service method is printing the object it is receiving.

This is the client for the XML service:


It is almost the same as the JSON client, the only difference is that a parameter is include in the url "http://localhost:9999/xmlServices/student/James", because the service is expecting it.

After running these examples I notice how easy and fast is to run the services and the few resources that required, I'm using at most 30Mb of memory.

Monday, January 6, 2014

JDK 7 securtiy issues with web start

With the latest updates java increased its security and new features were added to the web start applications, so basically if you have a web start application and is not properly signed it will not run over the latest version of the JVM (1.7.45), giving  you a warning like the following, and more errors.



This is what happened to me and I will explain what I had to do to get over this new security requirements and kept your application running.

The first step is get a code signing certificate with an certificate authority (CA), there are different CA and here are some of them:
The process to get the certificate is the following:

First you will have to request the CA for a certificate, and for this you will need a Keystore and a Certificate Signing Request (CSR), these are generated with the keytool.

For generate the keystore use the following command:

keytool -genkey -alias Alias -keyalg RSA -keysize 2048 -keystore Keysotre.jks

And for generate the CSR use the following command:

keytool -certreq -alias Alias  -file Cert.csr -keystore Keysotre.jks 

Each command will ask you for a password, after generating these files you will send the CSR file to the CA.

After the CA generates the certificate, it will send you the certificate, it is a file with probably one of the following extensions: PEM, DER, P7B, PFX, depending in the type of certificate, you can find more about the certificate types in this link: www.sslshopper.com/ssl-converter.html

Once you have the certificate with you, you will have to import it using the keytool, with the following command:

keytool -import -trustcacerts -alias Alias -file CAcert.p7b -keystore Keysotre.jks

Make sure you use the same keystore file used in the generation of the CSR file. You can find more information of the keytool command in the following link:

With this the jars files can be signed using the jarsigner command:

jarsigner -keystore Keysotre.jks -storepass password file.jar Alias

With these steps the jar file gets signed, but there is much more about this process of signing a jar.

Before the new features that were added in the latest releases of the JVM (1.7.XX) this was all you have to do to meet the security requirements for a web start application just sign the jars of the application.

These are some of the new features:

The META-INF/MANIFEST.MF file of the jar files must have the following attributes to grant permissions

Manifest-Version: 1.0
Permissions: all-permissions
Codebase: https://example.com

In this link you can find the new attributes of the Manifest file http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/manifest.html


Another feature is to sign the JNLP file, the oracle documents says the following in order to sign a JNLP file: 

"To create a signed JNLP file you don't sign the JNLP file itself, but you include the JNLP file inside the directory structure before the JAR file is created and then signed. The JNLP file must be named APPLICATION.JNLP and is included in the JNLP-INF subdirectory. The JAR file is then created and signed in the usual manner. When a web start application is started, the JNLP file used must be identical to the JNLP file in the signed JAR in order for the application to run".

You can find more information about signing JNLP files in the following link: http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/signedJNLP.html

Well these are some of the new requirements in order to run properly a web start application, I hope with this blog you can now have an idea of what to do if your web start application does not run because of security issues.



Wednesday, October 16, 2013

UDDI: Universal Description, Discovery, and Integration


I recently found out about this protocol I never heard of, so I decided to write a post about it to share it with you.

If you want to implement a Service Oriented Architecture UDDI will help a lot to implement it, most of the Enterprise Service Bus solutions that are in the market implement this protocol.

Introduction

UDDI is a standard for publishing and discovering information about web services, it behaves as a directory service for describing services, discovering businesses, and integrating business services. 
It defines a group of Web services and programmatic interfaces for publishing, retrieving, and managing information about services. (In true SOA fashion, a UDDI registry is itself composed of Web services!) 

It is a protocol developed by OASIS, It  focuses on the process of discovery in the service-oriented architecture, so most of the Enterprise Service Bus implements this standard.

UDDI registry can have three types of information white pages, yellow pages and green pages:

  • White pages: Basic contact information and identifiers, such as business name, address. 

  • Yellow pages: Information that describes a web service using different categorizations, such as business type manufacturing.

  • Green pages: Technical information that describes the behaviors and supported functions of a web service hosted by your business.

Developers use the UDDI to publish services and query the registry to discover services matching various criteria., they can query one or more UDDI registries to view the different businesses that expose web services and the specifications of those services.

Architecture

The UDDI Business Registry (UBR) or the Public Cloud, is built from multiple nodes that has their data synchronized through replication, so each node has the same information.

Content inserted into the UBR is done at a single node, and that operator node becomes the master owner of that content. Any subsequent updates or deletes of the data must occur at the operator node where the data was inserted.





Private nodes can be created too forming a private cloud, these nodes do not have data synchronized with the UBR they just have information replicated between them.

Specifications

UDDI builds upon several other established industry standards, including HTTP, XML, XML Schema (XSD), SOAP, and WSDL.




UDDI defines a set of XML Schema definitions that describe the data formats used by the various specification APIs.
UDDI Version 3.0.2 XML Schema. UDDI uses the XML Schema Language to formally describe its data structures. UDDI Version 3.0.2 XML Schema is provided by these files:

UDDI Version 3.0.2 WSDL Service Interface Descriptions. The complete set of UDDI Version 3.0.2 WSDL definitions is provided by these files:
What you can do with these documents:

UDDI replication

This document describes the data replication processes and interfaces to which a registry operator must conform to achieve data replication between sites. This specification is not a programmer's API; it defines the replication mechanism used among UBR nodes.

UDDI operators

This document outlines the behavior and operational parameters required by UDDI node operators. This specification defines data management requirements to which operators must adhere. For example, node operators are responsible for durable recording and backup of all data, ensuring that each business registration has a valid email address associated with it, and the integrity of the data during deletions (e.g., deleting a business means that all of its service entries must also be deleted). This document is not a programmer's API and private registries are not required to support it.

UDDI Programmer's API

This specification defines a set of functions that all UDDI registries support for inquiring about services hosted in a registry and for publishing information about a business or a service to a registry. This specification defines a series of SOAP messages containing XML documents that a UDDI registry accepts, parses, and responds to. This specification, along with the UDDI XML API schema and the UDDI Data Structure specification, makes up a complete programming interface to a UDDI registry.

UDDI data structures

This specification covers the specifics of the XML structures contained within the SOAP messages defined by the UDDI Programmer's API. This specification defines five core data structures and their relationships to one another.

So this is a brief introduction to UDDI protocol so in case you heard of it you can know what is all about.

Monday, August 19, 2013

JAVA EE SERVERS

JAVA EE SERVERS

I recently notice that Jboss changed the name of its community server version from JBoss AS to Wildfly. It took me some time to understand what was all the fuzz about, first I thought it was a new server but then I finally get it, Red hat was just making a bigger distinction between the JBoss supported (Jboss EAP) and community (now Wildfly) version nothing else, just like red hat and fedora.
You can find more information about it in the following link:

With this I realized that there are plenty versions of JEE servers in the market and is hard to understand for a non expert or a newbie which one does what and what is the difference between all of them, so I decided to write a post about the JEE Servers that are available, just to list some of its features and not a benchmark because that would require expertise in each server and I don't have that.

Before getting into serves here is a list of the specifications that a full Java EE 7 server should have, I will refer to it in a future as figure 1.







































Apache Tomcat 


Apache tomcat is an open source web server, it has many years in the market and is very common to find implementations using it.
Tomcat is a web server because it supports the Java Servlet and JavaServer Pages and others related to them, the table below shows the specification version supported by the tomcat version.

Tomcat home page: http://tomcat.apache.org/



Jetty


Jetty is a open source web container, it an Eclipse project and is hosted entirely at the Eclipse Foundation. It is known for be a lightweight server and be easily embedded in devices, tools, frameworks, application servers, and clusters. It has support for SPDY, WebSocket, OSGi, JMX, JNDI, JAAS and many other integrations.

The specifications that jetty has support are:
















More information about jetty can be found in the following link:


Apache TomEE




Apache TomEE is an open source Java EE 6 Web Profile server, it is based on Tomcat with EE features, that's the reason of its name “TomEE” pronounced as "Tommy”. It is practically new its first release came out in April of 2012, but it is gaining popularity and it has the support of the apache community.

TomEE server supports more JEE specifications than tomcat such as Enterprise JavaBeans, Java Persistence API (JPA), and others. It comes in different packages each with different specifications, the following table shows a comparison of the different packages.



















TomEE uses other project to provide the specifications:
  • CDI - Apache OpenWebBeans
  • EJB - Apache OpenEJB
  • JPA - Apache OpenJPA
  • JSF - Apache MyFaces
  • JSP - Apache Tomcat
  • JSTL - Apache Tomcat
  • JTA - Apache Geronimo Transaction
  • Servlet - Apache Tomcat
  • Javamail - Apache Geronimo JavaMail
  • Bean Validation - Apache BVal
  • JAX-RS - Apache CXF
  • JAX-WS - Apache CXF
  • JMS - Apache ActiveMQ
  • Connector - Apache Geronimo Connector


Use the following link for more information:


Glassfish


Glassfish is an open source Java EE application server sponsored by Oracle, it works as a reference implementation of the latest Java EE specifications. Its latest version Glassfish 4 supports the Java EE 7 specifications, so it should support all the specifications shown in figure 1.

 It makes use of some others opens source projects to implement the specifications:












Also Oracle provides a commercial version of this server which offers support. The following links will provide more information.



Geronimo



Apache Geronimo is an open source server, it is Java EE 6 certified and it is based in OSGI offering a more modular design.

Geronimo also uses other source projects to implement the specifications:
  • OpenEJB
  • OpenJPA
  • ActiveMQ
  • Tomcat
  • Jetty
  • TranQL


In the following link you can find a list of all the components or projects used in geronimo:

Geronimo home page:





JBoss Wildfly and Jboss AS



Wildfly formerly JBoss AS is an open source Java EE server now sponsored by Red Hat. Wildfly is still in alpha version but it would've be the Jboss AS 8 version. It supports the Java EE 7 specifications shown in “figure 1”, and it is based in OSGI offering a more modular design.

It makes use of some others opens source projects to implement the specifications, such as:


Red hat also offers a commercial version of Wildfly named JBoss EAP and it has all the benefits of a commercial product such as support, extra tools and many others. Its fees are not cheap it will probably cost tens of thousand of dollar, so be careful at the time of choosing a commercial server, the following link is a calculator from RED HAT so you can get an idea about the fees http://www.redhat.com/promo/eap_calculator/

Some of the links where you can find more information about Jboss are:



Weblogic



Oracle WebLogic Server is a commercial Java EE application server, its latest version is weblogic 12 is a Java EE 6 Full Profile, so the Java EE 6 specifications are supported. The following image shows the platforms supported by Weblogic.


















As it is commercial counterpart from redhat, oracle provides support and many tools for maintain the server, but is not a cheap server it will probably cost tens of thousand of dollar also. The following link is a pdf about the costs so you can get an idea about the fees:

Some of the links where you can find more information about Weblogic are:


Websphere 


IBM WebSphere Application Server is a commercial Java EE application server, its latest version is WebSphere 8, it is JEE6 certiļ¬ed based in OSGI offering a more modular design, some of the features they include are:

● Enterprise JavaBeans (EJB) 3.1
● Java Servlet 3.0
● Contexts and Dependency Injection for Java (CDI) 1.0
● Bean Validation 1.0
● Java Architecture for XML Binding (JAXB) 2.2
● Enterprise Web Services 1.3
● Java API for XML-Based Web Services (JAX-WS) 2.2

The Operative Systems supported are:




















As it is commercial as Weblogic and JBoss EAP, it comes with all the benefits from a commercial product but also its fees, the following image shows how much could it cost to have Webshpere:








In the following link more information about websphere can be found:

FUJITSU

FUJITSU Software Interstage Application Server is a commercial server and support standards such as Java EE, Web Service, and CORBA. Interstage Application Server component technologies and development frameworks.

It has support for the following features:
























The OS supported are:
  • Microsoft Windows Server 2008 R2
  • Microsoft Windows Server 2008
  • Microsoft Windows Server 2003 R2
  • Microsoft Windows Server 2003
  • Windows Azure Guest OS 1.18~(4)
  • Windows Azure Guest OS 2.6~(4)
  • Red Hat Enterprise Linux 6
  • Red Hat Enterprise Linux 5
  • Solaris 11
  • Solaris 10

For more information about fujitsu server go to the following links:

JEUS

TmaxSoft's JEUS is a commercial Java EE certified application server. It supports the following specifications:



















JEUS offer support for clustering, load balancing and has tools for the development and administration process.

For more information about JEUS go to the following link:




JONAS


OW2 Jonas is an open source Java EE application server, it is Java EE 5 certified and has a Java EE 6 preview version, is based in OSGI offering a more modular design.

Jonas use other opens source projects to implement the specifications, and since it is based on osgi different options and you can choose what project to use:















OW2 do not offer a commercial version of Jonas server but it offers a support subscription for professional support and training, it has tools for managing and clustering but they are for free.

In the following link more information about JONAS can be found:



Resin 


Resin is a commercial Java application server by Caucho, it supports the Java EE 6 Web Profile. It supports Servlet, JSP, JSTL, EJB, Candi (Java CDI), JSF, JPA, and more. It is a lightweight server designed with CDI.It has Java monitoring and OS monitoring facilities available via built-in console or third party applications via JMX and REST



















It has support for clustering and tools for application deployment, distributed caching, load balancing and messaging, and so on.

Resin can be used with Amazon Web Services for cloud deployment. More information about resin and amazon can be found in the following link:

The prices of the licenses of resin can be found in the following link:

Resin has an open source version http://resin.caucho.com/ , the differences between the open source and the commercial version, is the amount of tools offered by the commercial version, in the following link a comparison between the two versions can be found:

For more information about resin go to the following link:

Well these are the most known options that can be found for a JEE server, I try to list some of its features and useful links. As I said before this is not a benchmark, but for choosing one server first you have to check if you want a commercial option or open source option, then check what options are among between your budget and then evaluate these options, its features, the support, if it is open source the community support, the documentation and so on.

And finally here is a link where you can find which servers are compatible with each JEE profile: