DataTables is a JQuery plugin, facilitating building Ajax table editors. In this example, I show how to connect it to JEE backend, which is a simple Servlet. Backend exposes a table, stored as a Java List within Servlet instance. Data is served back in JSON format using Jackson library.
Example is deployed on Google App Engine, datatablesjee.appspot.com.
Code is available on GitHub github.com/rafalrusin/datatablesjee.
First, we need to instantiate DataTables plugin within a html page.
This is extremely easy, by using code below:
AjaxSource parameter refers to Servlet URI, which handles requests for data.
ServerSide argument is set to true, which means that backend will do sorting, filtering
and pagination. This allows us to use large tables (>1000 rows) without performance problems
on client side.
Now, we need to implement backend.
Servlet requires a doGet method, which needs to retrieve parameters sent from client
as an Ajax request. Those parameters describe search keyword, starting row and page size
of a table.
Then, we need to do filtering and sorting. I used a simple toString + contains methods
on a single row in order to do filtering. Sorting is done via custom comparator, which
sorts by given column number. Following code does the job:
Last, we need to send JSON response back to client. Here, we use Jackson,
which is a very convenient library for manipulating JSON in Java.
iTotalRecords is total number of records, without filtering.
iTotalDisplayRecords is number of records after applying filter.
aaData is two dimensional array of strings, representing visible table data.
Summing up, I like the idea of Ajax in this form, because client side is
not rendered directly by backend (no jsp, etc.).
This makes it a detached view, which could be served as static content, from Apache Web Server for example, which is very performant.
This blog covers topics around programming in various languages, for the industry. It includes my insights based on commercial experience from various projects I worked on. I hope it will provide a simple way of doing complex tasks related to programming, as well as an overview of what's going on in software nowadays.
Saturday, December 17, 2011
Sunday, November 13, 2011
Running Qt4 Examples on Embedded Linux using ARM emulator
In this article I will show how to run Qt4-Embedded Examples on Angstrom Linux using QEMU. The procedure doesn't require any compilation or cross compilation. It uses Angstrom Linux precompiled packages, online image builder, and works both on Windows and Linux.
Qt4 Embedded allows to run Qt applications directly in Linux Framebuffer, bypassing X Windows completely. This is especially important during embedded development, because it allows to save a lot of memory and start up time.
Qt4 has a rich set of examples directly embedded into Qt sources. Below is a few samples of how it looks like:
I will show how to run them.
First, you need to install QEMU. For Windows, the easiest way is to download zipped executables, which I shared here: Qemu-windows-0151. For Linux it's usually apt-get install qemu-system.
Then, we need to build Angstrom image. For those unpatient, I shared a prebuilt image here: angstrom-qt4-embedded. Angstrom has online image builder available here: Angstrom Image Builder. You need to pick console image and download it. The small trick is that you need to download kernel image yourself (from here: kernel-image-2.6.37.2_2.6.37-r4.6_qemuarm.ipk) and unpack it using ar -x kernel-image.ipk command. This is because online image builder doesn't include kernel image for some reason. However this step is not required if you download the image I shared.
Next, you need to start QEMU using kernel image and prebuilt angstrom image. The command looks like this:
qemu-system-arm -M versatilepb -usb -usbdevice wacom-tablet -show-cursor -m 64 -kernel zImage-2.6.37.2 -hda disk.img -append "root=/dev/sda2 rw"
For convenience, I prepared run script, which does that.
Next, you need to login as root and install qt4-embedded using command: opkg install qt4-embedded. This can be again skipped if you use the image I prepared.
In order to run demos, you need to use this command:
qtdemoE -qws
It looks like this: You can run the other examples from Qt, in standalone mode from /usr/bin/qtopia directory. You need to use similar command app -qws. The command is required to initialize Qt framebuffer. It is possible to run a few executables on the same display. In order to do this, you need to run the first one only with qws parameter. The other apps will connect to it.
Have fun!
Qt4 Embedded allows to run Qt applications directly in Linux Framebuffer, bypassing X Windows completely. This is especially important during embedded development, because it allows to save a lot of memory and start up time.
Qt4 has a rich set of examples directly embedded into Qt sources. Below is a few samples of how it looks like:
I will show how to run them.
First, you need to install QEMU. For Windows, the easiest way is to download zipped executables, which I shared here: Qemu-windows-0151. For Linux it's usually apt-get install qemu-system.
Then, we need to build Angstrom image. For those unpatient, I shared a prebuilt image here: angstrom-qt4-embedded. Angstrom has online image builder available here: Angstrom Image Builder. You need to pick console image and download it. The small trick is that you need to download kernel image yourself (from here: kernel-image-2.6.37.2_2.6.37-r4.6_qemuarm.ipk) and unpack it using ar -x kernel-image.ipk command. This is because online image builder doesn't include kernel image for some reason. However this step is not required if you download the image I shared.
Next, you need to start QEMU using kernel image and prebuilt angstrom image. The command looks like this:
qemu-system-arm -M versatilepb -usb -usbdevice wacom-tablet -show-cursor -m 64 -kernel zImage-2.6.37.2 -hda disk.img -append "root=/dev/sda2 rw"
For convenience, I prepared run script, which does that.
Next, you need to login as root and install qt4-embedded using command: opkg install qt4-embedded. This can be again skipped if you use the image I prepared.
In order to run demos, you need to use this command:
qtdemoE -qws
It looks like this: You can run the other examples from Qt, in standalone mode from /usr/bin/qtopia directory. You need to use similar command app -qws. The command is required to initialize Qt framebuffer. It is possible to run a few executables on the same display. In order to do this, you need to run the first one only with qws parameter. The other apps will connect to it.
Have fun!
Sunday, October 16, 2011
Red Black Tree Visualization using HTML5 Canvas and GWT
I created a sample app, which demonstrates HTML5 Canvas usage from Java through GWT.
I think GWT is a great tool for migrating desktop apps into Web nowadays, especially
for Java developers. So it's worth to give it a try.
Google has made great progress on migrating desktop apps into Web during last year. They propagated trend for HTML5 support and Javascript JIT compilers among modern browsers. So it's possible to run Quake 2 or CAD software directly in browser at decent speed.
Red Black Tree is a balanced BST tree. Details are described on Wikipedia.
You can run this sample app directly on appspot (it works on iPhone too :-) )
Sample code can be found here: Browse on GitHub.
Let's start from initialization.
First, we need to create Canvas element and add it to HTML. getContext2D is called to obtain drawing context.
We register a timer to redraw frames frequently:
So doUpdate is called every 50 ms and whenever redrawFrame is set to true, it redraws Canvas contents.
In autoplay mode, we call processFrame in while loop. So whenever redraw procedure takes too long, we will process frames without redrawing them. This won't slow down animation on low resources.
Then, we need to draw a tree. We use drawTree procedure, which is recursive and draws nodes along with contents and connections between them:
The best part is that we can do regular Java unit tests on Red Black tree to verify correctness of implementation:
Google has made great progress on migrating desktop apps into Web during last year. They propagated trend for HTML5 support and Javascript JIT compilers among modern browsers. So it's possible to run Quake 2 or CAD software directly in browser at decent speed.
Red Black Tree is a balanced BST tree. Details are described on Wikipedia.
You can run this sample app directly on appspot (it works on iPhone too :-) )
Sample code can be found here: Browse on GitHub.
Let's start from initialization.
First, we need to create Canvas element and add it to HTML. getContext2D is called to obtain drawing context.
We register a timer to redraw frames frequently:
So doUpdate is called every 50 ms and whenever redrawFrame is set to true, it redraws Canvas contents.
In autoplay mode, we call processFrame in while loop. So whenever redraw procedure takes too long, we will process frames without redrawing them. This won't slow down animation on low resources.
Then, we need to draw a tree. We use drawTree procedure, which is recursive and draws nodes along with contents and connections between them:
The best part is that we can do regular Java unit tests on Red Black tree to verify correctness of implementation:
Monday, October 3, 2011
Grammar parser in C++
Recently I stumbled upon implementing a simple parser in C++. The task is very classic, however I couldn't find any good resources on the web to help me out.
I tried different tools (including ANTLR), but finally the easiest way I found was bison + flex. It's unbelievable that this technology from 1989 is still actively developed. Latest stable release is from May 14, 2011. Moreover, many important projects make use of it. Among them are Ruby, PHP, Google Go, Bash shell.
So I decided to create a minimalistic example, which works from scratch.
I published the code on github Calculator, so you can check it out.
The whole example is 88 lines long and evaluates common expressions, like 2+2*2-13*(7+19/2).
Let's start with lexer. In flex, you need to define regular expressions, which produce tokens. Such tokens are later processed by a scanner. So we have to define calculator.lex, like this:
Flex will generate yylex() function, which we can call later to produce tokens.
Next, we need to create a scanner (calculator.y), which specifies a grammar. It's simple like that:
Here, we specify types for all tokens using C/C++ union like structure. Variable $$ is used to store result of particular reductions.
Additionally, we need to specify %left precedence for +, -, *, / operators to resolve shift / reduce conflicts between them.
And that's basically it. We have a working expression parser.
I implemented it in a way, that executable takes a file name containing expressions as an argument.
So you can try ./calculator input.txt to see the result.
I tried different tools (including ANTLR), but finally the easiest way I found was bison + flex. It's unbelievable that this technology from 1989 is still actively developed. Latest stable release is from May 14, 2011. Moreover, many important projects make use of it. Among them are Ruby, PHP, Google Go, Bash shell.
So I decided to create a minimalistic example, which works from scratch.
I published the code on github Calculator, so you can check it out.
The whole example is 88 lines long and evaluates common expressions, like 2+2*2-13*(7+19/2).
Let's start with lexer. In flex, you need to define regular expressions, which produce tokens. Such tokens are later processed by a scanner. So we have to define calculator.lex, like this:
Flex will generate yylex() function, which we can call later to produce tokens.
Next, we need to create a scanner (calculator.y), which specifies a grammar. It's simple like that:
Here, we specify types for all tokens using C/C++ union like structure. Variable $$ is used to store result of particular reductions.
Additionally, we need to specify %left precedence for +, -, *, / operators to resolve shift / reduce conflicts between them.
And that's basically it. We have a working expression parser.
I implemented it in a way, that executable takes a file name containing expressions as an argument.
So you can try ./calculator input.txt to see the result.
Sunday, June 12, 2011
Visualizing GIS data in JavaFX 2.0 beta using GeoTools
Geographic data mostly comprises of polygon coordinates sets along with attributes, like country or city name, etc. This is quite easy to visualize in JavaFX, which supports rendering for SVG paths.
In the article, I show how to read such GIS data from ESRI type database files using open source library GeoTools.
The data itself comes for free from www.naturalearthdata.com.
Sample code can be found here: Browse on GitHub.
GIS data usually comes in form of SHP and DBF files. In order to read it, we use GeoTools parser. Following code iterates over so called "features" from within data files and retrieves name attribute and shape geometry.
Next, we need to create JavaFX polygons for each feature from iteration. Small note here. Each feature may comprise of multiple polygons. For example "United States" shape may contain separate polygon for Alaska. So we need additional loop to generate such polygons.
In order to create a polygon in JavaFX, we use Path class along with MoveTo and LineTo path elements. Following snippet does the job.
The remaining part is to implement zoom and panning functionality. This is fairly easy in JavaFX. We can use translate and scale properties from main Group shape. Panning functionality is handled using following snippet:
Zoom is coded this way:
That's it. Now we have basic GIS data viewer in JavaFX 2.
In the article, I show how to read such GIS data from ESRI type database files using open source library GeoTools.
The data itself comes for free from www.naturalearthdata.com.
Sample code can be found here: Browse on GitHub.
GIS data usually comes in form of SHP and DBF files. In order to read it, we use GeoTools parser. Following code iterates over so called "features" from within data files and retrieves name attribute and shape geometry.
Next, we need to create JavaFX polygons for each feature from iteration. Small note here. Each feature may comprise of multiple polygons. For example "United States" shape may contain separate polygon for Alaska. So we need additional loop to generate such polygons.
In order to create a polygon in JavaFX, we use Path class along with MoveTo and LineTo path elements. Following snippet does the job.
The remaining part is to implement zoom and panning functionality. This is fairly easy in JavaFX. We can use translate and scale properties from main Group shape. Panning functionality is handled using following snippet:
Zoom is coded this way:
That's it. Now we have basic GIS data viewer in JavaFX 2.
Tuesday, March 22, 2011
Implementing graph editor in JavaFX using MVC like approach
JavaFX has very good SVG support, embedded into language runtime. This makes it interesting choice for implementing custom UI components, which includes graph editors.
In this article, I show how to create a simple graph editor, using MVC like approach and XML serialization via XStream.
Example can be found here: Launch JNLP, Browse on GitHub.
Application brings graph editing functionality and maximum network flow computation using Ford Fulkerson algorithm
Architecture is divided into Model, View and Controller. I made a slight upgrade to classic understanding of MVC. Classic View was responsible for displaying data only. Here, View consists also of UI parts, which include editable labels or combo boxes. Also, in Classic MVC, Model was responsible for refreshing View after Model changes by sending events to registered views. Here, Controller is responsible for refreshing View after Model changes and Model is just a plain POJO structure. I found such approach easier to implement.
Model consists of Three Java classes (non JavaFX), which represent structure of a graph: MNode, MShape, MConnection. Separating those classes from UI gives benefit of easier serialization. In this case using XStream::toXML(model) does the job. Sample output is like this:
View consists of corresponding UI implementations for Model elements, which are UINode, UILine, UIShape. Here, UINode is connected to MNode through model property. This is Bridge Pattern like approach for splitting class hierarchy of nodes into two.
UINode classes refer to controller to perform user input actions, like delete node.
Controller implements user action logic. This includes add, delete, and drag node. It is also responsible for refreshing UI after model changes. In order to do that easily, it uses Weak Hash Map, which keys are Model nodes and values are UI Nodes. Update function is like this:
Because of Weak Hash Map, removing nodes from Model leads to removing corresponding UI elements from map automaticly.
JavaFX SVG support and Layouts make it easy to render quite good looking nodes and connections.
In this article, I show how to create a simple graph editor, using MVC like approach and XML serialization via XStream.
Example can be found here: Launch JNLP, Browse on GitHub.
Application brings graph editing functionality and maximum network flow computation using Ford Fulkerson algorithm
Architecture is divided into Model, View and Controller. I made a slight upgrade to classic understanding of MVC. Classic View was responsible for displaying data only. Here, View consists also of UI parts, which include editable labels or combo boxes. Also, in Classic MVC, Model was responsible for refreshing View after Model changes by sending events to registered views. Here, Controller is responsible for refreshing View after Model changes and Model is just a plain POJO structure. I found such approach easier to implement.
Model consists of Three Java classes (non JavaFX), which represent structure of a graph: MNode, MShape, MConnection. Separating those classes from UI gives benefit of easier serialization. In this case using XStream::toXML(model) does the job. Sample output is like this:
View consists of corresponding UI implementations for Model elements, which are UINode, UILine, UIShape. Here, UINode is connected to MNode through model property. This is Bridge Pattern like approach for splitting class hierarchy of nodes into two.
UINode classes refer to controller to perform user input actions, like delete node.
Controller implements user action logic. This includes add, delete, and drag node. It is also responsible for refreshing UI after model changes. In order to do that easily, it uses Weak Hash Map, which keys are Model nodes and values are UI Nodes. Update function is like this:
Because of Weak Hash Map, removing nodes from Model leads to removing corresponding UI elements from map automaticly.
JavaFX SVG support and Layouts make it easy to render quite good looking nodes and connections.
Monday, March 7, 2011
Drawing arrows in JavaFX
Some time in the past, I was wondering what's the easiest solution for drawing arrow
connections between shapes. The problem boils down to computing boundary point for given shape,
which intersects with connecting line.
The solution is not so difficult when we consider polygon shapes. But it becomes more difficult considering curves and far more difficult for generic SVG shapes.
In this article, I show a simple way to find such boundary points for generic SVG shapes, utilizing JavaFX "contains" method and simple bisection algorithm.
Following application does the job: Launch JNLP, Browse on GitHub.
Application allows to drag shapes to track shape boundaries.
So, "contains" method in JavaFX allows us to poll any 2D point for intersection with SVG shape. Next, we need to assume, that we know a point inside a shape, from which every ray has exactly one intersection. This includes star-like shapes and ellipses. Next, we can use simple bisection algorithm to find such boundary point. We cut off once length between two points is too small. Following snippet does the job: Next, we need to draw arrows on the ends. In order to do that, we can use JavaFX Affine Transform, which is matrix transformation for SVG path. We need to compute transformation vectors for the matrix. This sounds scarry, but in fact is relatively easy. First vector in matrix is (targetPoint - sourcePoint) / length. Second one is perpendicular to it. Following code applies transformation:
The solution is not so difficult when we consider polygon shapes. But it becomes more difficult considering curves and far more difficult for generic SVG shapes.
In this article, I show a simple way to find such boundary points for generic SVG shapes, utilizing JavaFX "contains" method and simple bisection algorithm.
Following application does the job: Launch JNLP, Browse on GitHub.
Application allows to drag shapes to track shape boundaries.
So, "contains" method in JavaFX allows us to poll any 2D point for intersection with SVG shape. Next, we need to assume, that we know a point inside a shape, from which every ray has exactly one intersection. This includes star-like shapes and ellipses. Next, we can use simple bisection algorithm to find such boundary point. We cut off once length between two points is too small. Following snippet does the job: Next, we need to draw arrows on the ends. In order to do that, we can use JavaFX Affine Transform, which is matrix transformation for SVG path. We need to compute transformation vectors for the matrix. This sounds scarry, but in fact is relatively easy. First vector in matrix is (targetPoint - sourcePoint) / length. Second one is perpendicular to it. Following code applies transformation:
Subscribe to:
Posts (Atom)