Friday, October 17, 2014

JavaFX workaround for rotate text on tabpane tab

I have not much of experience with JavaFX, but I've been using it since almost over a year by now. I found that the tabs from the tabpane control have a restriction, when they are placed by a side either right or left the text can not be placed horizontal, the following image shows the behavior.


The issue is that the text is not displayed horizontally and it is hard to read, and javaFX does not provide a solution to it, actually there is feature request to it https://javafx-jira.kenai.com/browse/RT-19547 but it seems that it will not happen soon.

I found some workarounds to it, but they have many issues such as the text doesn't properly resize the tab width, so I'm going to describe the workaround that I did, hoping that it could be helpful to you.

A solution that I found from this post http://stackoverflow.com/questions/16708578/javafx-2-0-tabpane-tabs-at-left-and-keep-tab-header-horizontal , mentions to add the following style:

Which works fine:

But what if you have multiple tabs in your application and this tabs do not have the tabs by a side, it will also rotate the text of this tabs and will complicate everything.


Another issue is, if the characters of the text increases the size also increases but not only its width but also its height:


Due to all this issues this workaround and others seem to work fine only in certain scenarios.
My workaround is not better than them, but it tries to avoid these issues.
First, only rotate the tabs you want to rotate, to do this create a CSS class:



Then add it to the tabs objects you want to rotate:



Then create a CSS class to handle the size for the TabPane in which you are rotating the tabs:

Add this class to the TabPane object:

With this you will restrict the size of your tabs and they will not get bigger if the text increases. The limitation it has is that the amount of characters depends on the size you set to the TabPane object.




As I said I'm not an expert on javaFX and I found this solution to this issue that seems to be different to others and might help you.
If you have a different solution before this issue is fixed tell me about it.



Monday, June 9, 2014

Debug in node.js

A few days ago someone asked me if I knew how to debug in node.js and to be honest I was debugging with the console object, although it is effective I thought there should be better ways to debug a script, so I'm going to explain you my findings and hope to help someone that was in the same position as me.

So let's start with the simplest way to debug with the console object.


Save the script and run it, the console will output in each iteration the value of the variables used in this case "i" and "sum", like the following:

Iteration:0, sum:0
Iteration:1, sum:1
Iteration:2, sum:3
Iteration:3, sum:6
Iteration:4, sum:10
Iteration:5, sum:15
Iteration:6, sum:21
Iteration:7, sum:28
Iteration:8, sum:36
Iteration:9, sum:45

The console object has other methods besides log(), you can find more about it in the following link:

http://nodejs.org/api/stdio.html

Since V8 node comes with a debugger, it has a built in client for this debugger to use it just add the debug argument when start running the script. Save the previous script as scriptDebug.js then type the following command to start the debugger:

               node debug scriptDebug.js

After that you will see a prompt to the debugger client as the following:

< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug>

Now the debug client support some basic commands to debug the script, here are some of them:
  • cont, c - Continue execution
  • next, n - Step next
  • step, s - Step in
  • out, o - Step out
  • pause - Pause running code (like pause button in Developer Tools)
  • setBreakpoint(), sb() - Set breakpoint on current line
  • clearBreakpoint, cb(...) - Clear breakpoint
  • .....
In the debugg mode if you type the command cont as this:

< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug> cont
< Iteration:0, sum:0
< Iteration:1, sum:1
< Iteration:2, sum:3
< Iteration:3, sum:6
< Iteration:4, sum:10
< Iteration:5, sum:15
< Iteration:6, sum:21
< Iteration:7, sum:28
< Iteration:8, sum:36
< Iteration:9, sum:45
program terminated

You will see will be the output of the program, this is because the is no breakpoint in the code.

To set a break point you could use the command sb(), for example to set a break point in the line 5, it would be like this:

connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
debug> sb(5);
  1 var sum = 0;
  2
  3 for(i=0;i<10;i++) {
  4 sum = sum + i;
* 5  console.log('Iteration:' + i +', sum:' + sum);
  6 }

Now every time a continue command is given it will stop in the breakpoint, as the following examples shows:

debug> cont
< Iteration:0, sum:0
break in scriptDebug.js:5
  3 for(i=0;i<10;i++) {
  4 sum = sum + i;
* 5  console.log('Iteration:' + i +', sum:' + sum);
  6 }
  
Another way to place a breakpoint is to set the debugger instruction in your code as the following example:



Once you can go through your code, what is missing is to inspect the values of the variables in your program, to do this let's use the watch command in the script we have used so far, the following example show how to use it:

$ node debug scriptDebug.js
< debugger listening on port 5858
connecting... ok
break in scriptDebug.js:1
  1 var sum = 0;
  2 
  3 for(i=0;i<10;i++) {
debug> watch('sum')
debug> cont
< Iteration:0, sum:0
break in scriptDebug.js:6
Watchers:
  0: sum = 0

  4 sum = sum + i;
  5  console.log('Iteration:' + i +', sum:' + sum);
  6  debugger;
  7 }
  8 
debug> cont
break in scriptDebug.js:6
< Iteration:1, sum:1
Watchers:
  0: sum = 1

  4 sum = sum + i;
  5  console.log('Iteration:' + i +', sum:' + sum);
  6  debugger;
  7 }
  8 

As you can see now every time a breakpoint is found the variable sum is printed with its value.

With this tool you can easily go through your code, stop wherever you want and do many more things, you can find all the instructions in the following link:

http://nodejs.org/api/debugger.html

The debbuger that comes with node.js is very powerful but still is a command based utility, there are debbugers with more visual help, lets use node inspector to have a visual aid to debug our script.

First lets install globally node inspector, with the help of npm use the following command:

        $ npm install -g node-inspector

With node inspector installed let's start it with the following command:

$ node-inspector
Node Inspector v0.7.3
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.

With node inspector running in other terminal you have to start in debug mode your application with the following command:

$ node --debug-brk scriptDebug.js
debugger listening on port 5858

The --debug-brk option is a node inspector option which starts to debug the script and stops it in the first line.

Now let's open a browser with url indicated "http://127.0.0.1:8080/debug?port=5858" by node inspector, you will see the following console:


As you can see the script is displayed and in the right side there is a window that displays all the information about the runtime values of the script, as in the upper right side there are some navigation buttons to go through the script.

With node inspector the debugging of a script is made so much easier because it is a visual tool and all the commands are a click away.

You can find more about node inspector in the following link:
https://github.com/node-inspector/node-inspector

This is a brief example of how to start using the debug tools of node.js and I hope it is useful to you.





Wednesday, May 28, 2014

Websockets in Java EE 7 with wildfly

In the past few weeks I've trying the websockets technology introduced in JEE 7 and I would like to share you how to develop a simple example of it, for those who don't know what is about websockets, here is a brief introduction.

Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.

It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification, and in the Java servers since the JEE 7 version and the specification  JSR 356.

If you want to know more about websockets refer to the following links:

I'm going to use the wildfy 8 as server the open source version of jboss, you can download it from here http://wildfly.org/downloads/, and as for the IDE I'm going to use JBoss tools, you can download it from here http://tools.jboss.org/downloads/ .

To set up wildfly with eclipse you can use the following link for instructions:  http://planet.jboss.org/post/getting_started_with_jboss_tools_and_wildfly_tech_tip_5

Once you have everything installed and integrated lets start creating a websocket application.
lets create a new project, select new project and from the options presented choose dynamic web project, set the name of the project as websockets and the target runtime to wildfy 8.

The Java API for WebSocket consists of the following packages.

  • The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints.
  • The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.

Now lets create a new server endpoint class, this class will receive the messages from the client and also it could send messages to the client.


From the class above notice the @ServerEndpoint annotation, it indicates the class will be a socket endpoint, it takes a string ("example") as parameter this will be the URI of the endpoint.

The methods of the class are annotated with @OnOpen, @OnMessage, @OnClose annotations, these indicate the lifecycle of endpoint here is a brief description of them:

AnnotationEventExample
OnOpenConnection opened
@OnOpen
public void open(Session session, 
                 EndpointConfig conf) { }
OnMessageMessage received
@OnMessage
public void message(Session session, 
                    String msg) { }
OnErrorConnection error
@OnError
public void error(Session session, 
                  Throwable error) { }
OnCloseConnection closed
@OnClose
public void close(Session session, 
                  CloseReason reason) { }




The endpoint now is ready to start a conversation so deploy it in wildfy and lets create a html client to communicate with this endpoint.


In the previous html file the only thing to notice is the simple script that creates a connection to the endpoint, from the url "ws://localhost:8080/websockets/example" used check the name of the application and the URI of the endpoint.

If you open the html file on browser that supports web sockets you should see the message "Web Socket is connected!!" and in the server you should see in console the message "Open session:...". This indicates that the communication has been established between the client and the server.

To now more about the WebSocket javascript interface the following link will help:
http://www.w3.org/TR/2011/WD-websockets-20110419/

Let's create a message and send it from the client to the server. To do this let's just add the following function in the javascript section of the html file.


With this function the ws variable calls the sends() method and sends the message to the server.
To call this function just add a html link and call it.


Let's test it click on the link and you should see the following message on server's console: "Received : Message to server from client, session:..."

Now to simulate a request-response communication lets return a message from the @OnMessage method in the websocket endpoint in the server.


Deploy it and test it, you should get the following sequence of messages:

  1. Browser displays "Web sockect is connected".
  2. After calling send(), server console diplays: Received : Message to server from client, session:
  3. Browser displays "Received, Response from the server"
To demonstrate full duplex communication lets send messages from the server without any request from the client. To do this, lets add and asynchronous task to send messages.



Notice that the @Stateless annotation has been added to the endpoint, it is required to send messages asynchronously, with this now the endpoint is also an EJB, also the endpoint makes use of the ManagedExecutorService resource, it takes runnables and executes them, this is done on the @OnOpen method so when the conversation starts the runnables are set.
In the runnable we wait for 10 seconds and then sends a message to the client this is done without receiving any previous message and this is repeated 3 times so during 30 seconds, your browser should be receiving the message "Received, Message from server".

With this is demonstrated the full-duplex communication this is a message can be sent without any prior message or request.

Well this is basically a simple example that demonstrates how web sockets work, in further post I will keep showing more of their functionality.  





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.