Enhance Java Applications with FOSS APIs

0
5575
Implementation of Hello World in Java_10180279_l
Java application developers have access to many free and open source APIs that ease their workload. This article, which presumes the reader has some knowledge of Netbeans, Core Java and Java Swing, demonstrates the implementation of user input validation, reporting and SMS integration.

Imagine a world where car manufacturers had to invent the wheel for every car they manufactured, or if Jonas Salk, the inventor of the polio vaccine, had patented his invention or if Dennis Ritchie, the creator of the C programming language, had not created it. What would it be like then? Very different from what it is today, wouldn’t it? Thanks to the open source community, we aren’t living in such a world.
The Free and Open Source Software (FOSS) community plays an important role in the world of software development. Over the past many years, its efforts and expertise have helped software developers to avoid re-inventing the wheel. Most of the software being developed today uses certain functionalities that have been implemented in some other software. In order to save development time, software vendors break such functionalities into modules and offer them as APIs. They may or may not charge other developers for using these APIs. Those who don’t, often make them open source and invite the community to develop them further.
In this article, we explore three such open source APIs for developing Java applications—the SimpleValidation API, SMSLib API and DynamicReports API. These APIs enable developers to implement user input validation controls, reporting and SMS integration without much overhead.
The following sections cover each of the three APIs in detail. First, they give a brief introduction to the API, followed by its download and implementation details. A sample snippet is included wherever feasible. Each section includes a link to the working example referred to.

The SimpleValidation API
When I was in college, our software engineering professor asked us to remember this simple principle while developing software: ‘Always assume that your software will be used by monkeys.’ He didn’t mean it as an offence, but the message he wanted to convey was that user input validation is mission critical in any software.
An application with relaxed user input validation not only scores badly on the quality front, but is also a security hazard. Therefore, developers tend to spend more time on coding controls for erroneous inputs than on coding actual functionality, irrespective of the programming language or platform used.
Thankfully, for Java application developers, there’s good news in the form of the SimpleValidation API, which was developed by Tim Boudreau. It is a Java library developed to ease the coding of user input validation controls. It reduces the time required to code validation controls, thereby allowing developers to enhance the application further, without compromising on project deadlines. Through this library, developers can simply plug the required validation control in most of the swing components. It comes pre-built with some of the common validation controls like the non-empty string, numeric-only, URL, email, length of the input, etc. A more elaborate introduction to and the documentation for the API are both available at http://goo.gl/MqeQii.

Download and build
The most recent source code of the API is available at git://kenai.com/simplevalidation~git. In order to use this API, you’ll need to check out the source files from the Git repository and build them with NetBeans. You can use the following steps to do so:

  • Download and install Git for Windows (http://git-scm.com/download/win)
  • Launch the Git GUI and select Clone existing repository
  • In the source location, enter the above mentioned URL for the Git repository and specify the target directory on your machine and click Clone.
  • Once the repository is cloned, open it in NetBeans and build it. The build process will generate .jar files, which can then be included in any project.

However, if you think that’s too much of work, I have uploaded a compiled version of the API at http://goo.gl/Olc5MN. Download the zip file, extract it and follow the next section.

Implementation
If you’re using the GIT repository, copy the simplevalidation-standalone-<version>.Jar file from standalone\target folder and nbstubs-<version>.jar from \nbstubs\target folder to the project folder. However, if you have downloaded the compiled APIs from the above link, copy the two JAR files into the project folder.
Next, import the API in Netbeans. To do this, right click the project, select Properties > Libraries > Add Jar/Folder, specify the location of JAR files and press OK.
This API allows you to define the severity levels (FATAL, WARNING and INFO) of validation controls. The FATAL severity level is the strictest and requires the user to correct the input before submitting the form. The WARNING and INFO severity levels are a bit relaxed and can be used for validation of optional fields. It also decorates the Swing components (see Figure 1) according to the severity level set. The default is FATAL for all Swing components.

figure1
Figure 1: Login form

Sample code
A sample code snippet to enable validation in a login form with a username field, a password field and a login button is given below:

private ValidationPanel validationPanel;
private ValidationGroup validationGroup;

validationPanel = new ValidationPanel();
validationGroup = validationPanel.getValidationGroup();
validationPanel.validate();

/*Username field validation (Non-Empty String)*/

validationGroup.add(textField1,StringValidators.REQUIRE_NON_EMPTY_STRING);

/*Password field validation (Minimum Length 8, Non-Empty String, Disallowed
Characters)*/

validationGroup.add(passwordField1,StringValidators.REQUIRE_NON_EMPTY_STRING,StringValidators.minLength(8),StringValidators.disallowChars(new char[]{‘\’’,’!’}));
validationGroup.addUI(new ValidationUpdate(button1));

/*Class to change the state of Login button depending on the validity of input values and assigned severity*/

public class ValidationUpdate implements ValidationUI {

JButton button,button2;

public ValidationUpdate(JButton Button)
{
button=Button;
button2=new JButton();
}

public ValidationUpdate(JButton Button, JButton Button2)
{
button=Button;
button2=Button2;
}

public void clearProblem()
{
button.setEnabled(true);
button2.setEnabled(true);
}
public void showProblem(Problem problem)
{
if(problem.isFatal())
{
button.setEnabled(false); button2.setEnabled(false);
}
else
{
button.setEnabled(true); button2.setEnabled(true);
}
}
}

You can download the code for the above example at http://goo.gl/slVtDb. Extract the zip file, open the project in NetBeans, add the API JAR files to the project as mentioned above and run the project.

The SMSLib API
A common requirement from clients is to integrate SMS functionality in their application. They may need it for sending order notifications, automated greetings, marketing messages, etc. Often this can be done using the bulk SMS gateways via the Internet. However, sometimes, using such gateways might not be a desired option. Clients may want to use their mobile or a GSM dongle to send such SMS. This method has two benefits—it is more personalised and it is not affected by ‘Do Not Disturb’ (DND) filters.
The SMSLib API, developed by Thanasis Delenikas, is an open source library, available for Java and Microsoft .NET platforms. Through this API, applications can send and receive messages using almost any GSM modem. It’s simple to implement and can interface with most of the USB GSM dongles available in the market.

Download
You have two options to use SMSLib in your projects. The first one is to download the source code of SMSLib v 3.5.x from https://github.com/smslib/smslib-v3 and build it locally. If you choose this, follow the instructions available at http://smslib.org/doc/installation/. The second option is to download the compiled JAR file from http://goo.gl/wx5oIZ and import it into your NetBeans project using the steps mentioned previously.

Implementation
Since SMSLib uses the Java Communication API, you’ll have to download and install the Java Comm API before using it. The following instructions will help you in downloading and installing the Java Comm API:

  • Download the JavaComm v2 (for Windows 32-bit systems) from http://smslib.org/download/ and extract the zip file.
  • Copy Comm.jar to:
    %JAVA_HOME%\lib (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\lib)
    %JAVA_HOME%\jre\lib\ext (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\jre\lib\ext)
  • Copy win32com.dll to:
    %JAVA_HOME%\bin (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\bin)
    %JAVA_HOME%\jre\bin (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\jre\bin)
    %windir%System32 (e.g., C:\Windows\System32)
  • Copy javax.comm.properties to:
    %JAVA_HOME%/lib (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\lib)
    %JAVA_HOME%/jre/lib (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\jre\lib)

Note: The ‘Program Files’ (x86) folder exists only on 64-bit Windows machines.

Unfortunately, the JavaComm API is not available for 64-bit JDK; so in case you’re using the 64-bit JDK, you’ll have to use the RXTXComm API, which is an alternative to the JavaComm API and has a 64-bit version. The following instructions will help you in downloading and installing the RXTXComm API:

  • Download the RXTXComm 64-bit version from http://goo.gl/wx5oIZ and extract the zip file.
  • Copy RXTXcomm.jar to:
    %JAVA_HOME%\lib (e.g., C:\Program Files\ Java\jdk1.8.0_11\lib)
    %JAVA_HOME%\jre\lib\ext (e.g., C:\Program Files\ Java\jdk1.8.0_11\jre\lib\ext)
  • Copy rxtxSerial.dll and rxtxParallel.dll to:
    %JAVA_HOME%\bin (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\bin)
    %JAVA_HOME%\jre\bin (e.g., C:\Program Files (x86)\ Java\jdk1.8.0_11\jre\bin)
    %windir%System32 (e.g., C:\Windows\System32).

Sample code
In the sample code snippets shown below:

  • Replace the ‘Gateway Name’ with ‘GSM modem gateway’ (usually it’s the manufacturer’s name).
  • Replace the COM port with the COM port on which your device is registered. You can get the list of registered COM ports from Computer > Properties > Device Manager > Ports (COM & LPT). Try each port, if multiple ports are listed there.
  • Change the baud rate according to your device.
    Sample code to send an SMS is:
SerialModemGateway smsGateway = new SerialModemGateway(“Huawei”, “COM8”, 9600, “”, “”);
smsGateway.setInbound(true);
smsGateway.setOutbound(true);

try {
Service.getInstance().addGateway(smsGateway);
Service.getInstance().startService();

/*Insert the recipient phone number here*/

OutboundMessage msg = new OutboundMessage(“+91<Insert Phone Number here>”, “Test Message”);

Service.getInstance().sendMessage(msg);
Service.getInstance().stopService();

} catch (GatewayException ex) {
} catch (SMSLibException ex) {
} catch (IOException ex) {
} catch (InterruptedException ex) {
}

Sample code to receive an SMS is:

SerialModemGateway gateway = new SerialModemGateway(“Huawei”, “COM8”, 115200, “”, “”);
gateway.setProtocol(Protocols.PDU);
gateway.setInbound(true);
gateway.setOutbound(true);
Service.getInstance().setInboundMessageNotification(inboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, MessageClasses.ALL);

for (InboundMessage msg : msgList)
System.out.println(msg);

System.out.println(“Waiting for SMS. Press any key to stop.”);
System.in.read();

/*Class to display the notification and text of incoming message*/

public class InboundNotification implements IInboundMessageNotification
{
public void process(AGateway gateway, MessageTypes msgType, InboundMessage msg)
{
if (msgType == MessageTypes.INBOUND)
{
System.out.println(“Incoming message from: “ + gateway.getGatewayId());
System.out.println(“Sender: “+ msg.getOriginator());
}

System.out.println(msg);
}
}

The entire code for the above mentioned snippets is available at http://goo.gl/uQDsCO as a NetBeans project.

The DynamicReports API
I came across the DynamicReports API when I was developing my first business application. I was stuck for a while on the reporting module, thinking that I’d need to do it from scratch. That wasn’t a motivating thought at all, so I searched the Internet for an alternative. I came across several proprietary reporting APIs before I stumbled upon DynamicReports, and since then I haven’t looked anywhere else to create reports.
The DynamicReports API, developed by Ricardo Mariaca, is based on Jasper Reports. It reduces the effort required to create reports programmatically by abstracting much of the work required when using the Jasper Reports API. It comes pre-built with several designs and templates, thus eliminating the need for a visual designer. It also allows you to include various charts (bar charts, pie charts, metre charts, etc) in reports. It also allows you to export the reports in various formats (.pdf, .xls, .doc, etc). Thus, apart from some basic formatting and source data, it takes care of pretty much everything. You can visit http://www.dynamicreports.org to read more about it. It is well documented and the community provides good support.

Download and implementation
You can download the API from http://goo.gl/9xwY34. At the time of writing, the version is 3.2.1. Once the zip file is downloaded, extract it and copy the contents of the dist folder to your project. Next, import the JAR files in your NetBeans project using the steps mentioned previously.
DynamicReports hosts a variety of examples at http://www.dynamicreports.org/examples to get you started. In case you need help, you can visit the support forum at http://www.dynamicreports.org/forum/ and post your queries there or contact me at the email ID given at the end of the article.
The above mentioned APIs can be used in a variety of applications, either alone or in combination. For example, almost any application that requires users to input some value can benefit from the SimpleValidation API. DynamicReports can enhance any report-intensive business application (MIS, ERP, school results management, etc). SMSLib is very convenient for applications that use SMS as a means to accept user input (like accepting orders via SMS), and applications designed for machine-to-machine communication (for example, applications to monitor radio taxis, meter reading applications, etc).
Open source APIs and their developers are a boon to the developer community. They not only help in reducing development time and efforts but also bring down the overall cost of the project.

LEAVE A REPLY

Please enter your comment!
Please enter your name here