Wednesday, September 17, 2014

Scala issue... with Java 8 - class file is broken

Trying to run an sbt command in a freshly installed Scala environment I've got the following error:


Turns out it was an incompatibility error due to my Java 8 environment:
http://stackoverflow.com/questions/24197836/compilation-failed-error-while-loading-annotatedelement-concurrentmap-charseq

These instructions promptly pointed me how to select the active java jdk for a bash session:
http://superuser.com/questions/490425/how-do-i-switch-between-java-7-and-java-6-on-os-x-10-8-2

Changed it to 1.7 and it all runs well now.

Friday, May 9, 2014

Ivy: Invalid content was found starting with element 'dependency'. One of '{exclude, override, conflict}' is expected.

Just in case you try to use an exclude with Ivy and get the following message without having any problems with your ivy.xml:

Invalid content was found starting with element 'dependency'. One of '{exclude, override, conflict}' is expected.

Try to move it to the bottom of the file and build again. It's a bug in the spec and should go away just like that.


Sunday, April 6, 2014

Eclipse - "path/to/project" overlaps the location of another project: "your project"

Sometimes in eclipse we want to open a project that can't be imported because it still doesn't have Eclipse's configuration files (.project file)
The thing is we want to put it in ou workspace and then click on File >> New >> Java Project 
Then we uncheck the "Use default location" box and select our project folder in the workspace and there comes the surprise:


This beautiful small error message. I've recently found out how to deal with it and it's definitely not intuitive.
To avoid it, create the project as you would before (using  File >> New >> Java Project ) but leave "Use default location" checked and in the Project Name field use the name of the folder you put in your workspace. It's going to create the project without complaints and use your existing code.


Creating paginated table with PDFBox

I've recently needed to modify a file generation that was offered in CSV files to PDF format. I'll enumerate some of challenges on doing that:

Finding the right API to do the heavy work
PDF is a complex format created to display documents. It supports texts, graphics and a whole set of features, and has an 747 pages specification that can be bought here: ISO 32000-1 specification. One does not simply start writing to a PDF file, as unlike a text file, they usually contain non-ASCII binary characters and should always be considered as binary files.

Using an off the shelf API can greatly reduce the burden of trying to do that kind of file creation or modification manually. After some quick research I've realized that most o the available libs on the web were paid. The most used standard is iText, which needs a commercial license if being used for commercial purposes (http://itextpdf.com/salesfaq) The best free solution I found was PDFBox, which immediately drew my attention for being an Apache project. It is currently on the 1.8.4 release, is stable and has a fairly extensive amount of documentation on it's website and forums.

Now the thing is, I went through mailing lists and documentation and it doesn't come with any ready-made feature for tables generation. That requires for the developer to handle the drawing of the table's columns and rows. The following code performs that task and also handles paginating the table to multiple pages in case it doesn't fit.

Output sample:


I've meant to do just an essay here, so there are many optimizations to be done, but you can get some ideas from it to adapt to your needs. (full working code: https://github.com/eduardohl/Paginated-PDFBox-Table-Sample)


Tuesday, March 18, 2014

Environment variables and property placeholders using Spring and Tomcat

I've recently been playing on my server and then decided to remove my properties from the code. Even though I still have my properties file managed by Spring's property placeholder, I'm now using the system-properties-mode="OVERRIDE" which allows me to override the values using environment variables. It's very useful in case there are properties you want to remove from your .war (like passwords)

As I'm using Tomcat, the easiest way I found to set it was to use the setenv.sh configuration file. Just create it in Tomcat's bin file and it will be automatically read and used.

Here's an example:

spring.xml
<context:property-placeholder location="classpath:/database.properties" ignore-unresolvable="true" system-properties-mode="OVERRIDE"/>
setenv.sh
JAVA_OPTS="$JAVA_OPTS -Dmongo.db.host=<host> -Dmongo.db.port=<port> -Dmongo.db.name=<db_value> -Dmongo.db.username=<user> -Dmongo.db.password=<pwd>"
Obs: the file should be named setenv.bat on Windows

To test if it worked, after starting your Tomcat, use:
 ps aux | grep -i tomcat
You should be able to see your environments variable set!

Wednesday, March 5, 2014

Design Patterns - Singleton

I'm going to start writing a short series of overviews about the most common Design Patterns from the GoF and the first one I chose to talk about is the Singleton.

Singleton is a creational design pattern that should be used when only one instance of a given object should exist and that instance should be accessible from a global scope.  
The classic implementation for a Singleton uses a static member of the Singleton class which is its own instance, a private constructor to ensure that there will be no other way to instantiate other objects and a static public method that returns our instance. This will look a bit like this:

As you can see, the static method that retrieves our Singleton instance will create it if it doesn't exist, and after that return always the same instance. Also, to avoid more than one singleton being created at the same time due to concurrency, we make this method synchronized.
It's important to notice that there should be a single point of access to that object, and that point would be the place where the object creation is managed. Usually it is a getInstance Method, but we could use a Factory to handle that. Below we can see an example of usage for our singleton.


Other Implementations

My favorite implementation for Singletons is the one provided by Joshua Bloch in the book Effective Java. It uses an ENUM, as the way to request an automatically thread safe and simple Singleton. It's a smart way to use this Java native mechanism to produce an object that respects all of a Singleton's needs:

Usage sample:
 
I find it to be clean and it is also the most recommended way to it.

There's also the eager initialization, that relies on the static initialization of the class to create the class when it's loaded by the class loader, instead of doing it when the getInstance() method is called. 

One other famous implementation is the double-lock mechanism for lazy instantiation. It basically replicates the object managed instantiation, but now adding a double synchronization lock to ensure that only one Singleton will be created in a multi-threaded environment.
 

When to use

Common usages for Singletons are:
  • loggers - whenever you want to create a logger object that must be accessible from all components in the system, but should not be re-created every time it's used.
  • shared resources - hardware components like printers, input devices, output serial devices, etc can be treated as a singleton in order to manage concurrent access
  • configuration classes - configuration and properties are usually unique within a system and referenced by many components. Changes to these properties should also be immediatelly visible to all objects that use it, so this is another use case for our Singletons. In this case, it also serves as a cache, avoiding properties to be reloaded everytime it is accessed.

Issues

Singletons have been widely criticized by the software development industry and a quick search for Singletons are evil will return a good amount on information about why NOT to use singletons. I will enumerated them below, but I particularly believe that the answer to all questions is: "it depends". Even though I agree that singletons are often evil, there are some situations where they might come in handy. The main cons are:
  • They're are globally accessible. It means they add state to your entire application and hide dependencies (it's like having a global variable) and at some point that might become hard to manage, debug and maintain.
  • If you're using your own class to manage the creation of the Singleton, you'll be breaking the single responsibility principle in your class. Using the Enum technique or a factory to manage your instance could be a solution, but you're still working to do something that feels "unnatural"
  • The fact you're hiding dependencies makes things harder to test, and inherently coupled with your singleton. You global state(your singleton) could vary during tests execution for example, producing unpredictable and unreliable results.

Sunday, February 16, 2014

Cloud at fixed price

I've recently started looking for a cloud server provider because I wanted to have my own VPS. After digging through many nice options as Amazon EC2, Rackspace and Digital Ocean I stumbled upon this strange website: Cloud At Cost.

They offer "Pay once" plans that were a little too good to be true, but for anyone that's not looking for a commercial production server, the offer is pretty good. After some research through the web I learned that they're a new company from Canada and backed by a large telecommunications provider.

The features they include in the package are a Server Panel, a support service(ticket system) and DDoS protection.

From the server panel the options available are:
  • Start/Stop/Restart server
  • Reverse DNS
  • Upgrade to a higher configuration
  • Web console (alwful)
  • Re-Image the machine with: Ubuntu 12.04.3 LTS, CentOS 6.4 or Debian 7.1
I've got myself a Quad Core Xeon with 2GB memory and 40GB SSD space. It has a limited 3TB network transfer limit(monthly), but for incredibly $140 dollars I think it was a nice deal. No options to backup an image are being offered at the moment, and that was somewhat frustrating to me.

Well, I'm still hoping that was not a scam, but so far everything is working fine and I don't have anything to complain.

For anyone that would also like to experiment on it but don't want to spend much money, they have a monthly $1 plan for a fairly simple machine(1 core, 512MB memory and 10GB SSD), it might be worth a try! Oh, these prices are also supposed to be a limited time offer, just so you know.

Resolving UnknownHostException right after installing Jenkins

I've just installed Jenkins on my CentOS 6.4 using the very instructions provided on Jenkins website:
Installing Jenkins on RedHat distributions

After the installation, even though Jenkins was up, I was getting the following exception on logs:

WARNING: Could not intialize the host network interface on nullbecause of an error: centos64: centos64: Name or service not known
java.net.UnknownHostException: centos64: centos64: Name or service not known
    at java.net.InetAddress.getLocalHost(InetAddress.java:1473)
    at javax.jmdns.impl.HostInfo.newHostInfo(HostInfo.java:75)
    at javax.jmdns.impl.JmDNSImpl.<init>(JmDNSImpl.java:407)
    at javax.jmdns.JmDNS.create(JmDNS.java:60)
    at hudson.DNSMultiCast$1.call(DNSMultiCast.java:32)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.net.UnknownHostException: centos64: Name or service not known
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293)
    at java.net.InetAddress.getLocalHost(InetAddress.java:1469)
    ... 8 more

Now I don't have the slightest clue about why was jenkins trying to resolve to a server called centos64, but adding that entry to my /etc/hosts file resolved the problem:

127.0.0.1   localhost centos64

It guess it must have used some default configuration and got that network hostname that didn't exist.

Saturday, February 15, 2014

Running all jUnit tests in package with IntelliJ

To run all jUnit tests in a package using IntelliJ click on Run > Edit configurations:


On the left bar, click on the + sign and select JUnit (you must have JUnit plugin and JUnit dependencies on your project).


This will open a Dialog Window to edit the run configuration for a new test.

Name the new configuration, I've used the label <Run all tests>
The fork mode for JUnit allows you to run each test method or class in a separate process, if you're not sure what to use just leave it at <None>
On the <Test Kind> field, select the <All in package> option.
On the <Package> field, select the package from where tests should be executed, then click <Ok>.



It is also a good idea to click on the Code Coverage tab and add your test package to run coverage:


Now run your tests by clicking on the shortcut located on the top bar:


Results should be displayed at the bottom of the screen:


In case you want to see coverage, use the shortcut:

 

Results displayed on the dialog:


Steps to use Gradle with IntelliJ 12 to build a Spark web app

First, install Groovy and Gradle. This can be done by downloading and installing the binaries offered in their respective websites or using your favorite package manager. 
I've used brew for Mac: 
brew install groovy 
brew install gradle 
Make sure you add Gradle bin dir to your PATH and test installation using the following commands on your shell: 
gradle -v 
groovy -v 
On IntelliJ, Groovy's plugin is usually installed by default and Gradle's not. On the plugin list screen click on Install JetBrains plugin... and make sure both plugins are installed. 

Both IntelliJ 12 and 13 have the plugin for Gradle, but 12 doesn't have a full support so that it doesn't offer a Gradle project creation wizard for example. That's not a big deal, IntelliJ 12 is perfectly capable of applying the Gradle facet or import existing Gradle projects through build.gradle files. Most important, the JetGradle panel is available on both versions. That is the interface that will abstract Gradle's console commands and behaves very similarly to Maven or ant IDE tools.

Now let's start building our web app: create a build.gradle file on the root of the project, click on the JetGradle tab and then click on the Add link. Search your recently generated build.gradle file and click Ok. This will integrate JetGradle to your project.

If it is your first time using the Gradle IntelliJ plugin, the IDE might ask you to point your Gradle installation. Go to Preferences and on the Project Settings menu select the Gradle tab on the left column. The <Gradle project> field should contain your build.gradle file path. The <Gradle home> field should contain your Gradle installation path (in my case /usr/local/Cellar/gradle/1.8/libexec because I used brew to install it)

You can use the  command below in the shell in case you need help finding your gradle installation path.
which gradle
Gradle is highly configurable, but relies strongly on default tasks. For them to work, your web project should follow this structure: 
├── build.gradle
└── src
    └── main
        ├── java
           └── com
               └── moody
                   └── model
                       ├── JavaClass.java
                       └── GoesHere.java
        └── webapp                                                  
            ├── WEB-INF
               └── web.xml                                         
            └── index.jsp

Tip: If you create these folders mannually, in order to get IntelliJ to recognize these folders as src folders:
Right click on src/main/java and Mark directory as a Source folder (in blue)
Right click on src/test/java and Mark directory as a Test Source folder (in green)

If you have trouble creating the directory structure, try disabling the <Compact empty middle packages> on the Project panel configuration.
Now let's create a very simple web application using Gradle's convention over configuration features to use an embedded Jetty server. Add this to your build.gradle file:

The first block will require jetty plugin, which will require war and java plugins as well. That will provide all default tasks for build a java, web and jetty application(and handle embedding the server in the application.
The second block will add mavenCentral to the list of repositories where Gradle will look for dependencies.
The third block will add Spark web framework as a dependency of the project.

We're going to use Spark, a lightweight web framework for Java that will allow us to use Routes to respond to http requests. As we will be using the embedded Jetty server, a little configuration on the web.xml file will be necessary in order for Spark to use the Jetty server.
WebServer.java

web.xml


Now go to JetGradle view and click on Refresh Gradle Project. It might take a little while because dependencies might be downloaded. This will analyze all changes in the project and in the build file, import dependencies and etc. This will also refresh the list of available tasks in the tab Tasks. Clicking on it, you will see many defaults tasks.  Gradle allows you to create your own tasks and establish dependencies between them. In our case, we'll use Gradle's java and jetty plugins default tasks to build our web server with almost no configuration at all.

To start the application execute the jettyRun task(available on the JetGradle tab) that will compile, package and deploy the application.

Test it by browsing the URL: localhost:8080/testing-gradle3/hello

Now that's a very simple example of the simplicity of Gradle's automation tool. In very few lines of code we managed to handle a web application build and deploy. We also handled the management of other transitive dependencies.

The verbosity is amazingly little and Gradle also offer many other features. What I really like about it is the Task-like approach that reminds me of Ant, and avoids the overly complex configuration that Maven needs. The build.gradle file would be a mix of an ant build file and Maven's pom.xml, leveraging best features of both worlds.
And even though in this walkthrough I emphasized the nice IntelliJ interface for using it, Gradle can be used entirely through the console, just like Maven and ant.

The relationship between java plugin default tasks(from Gradle User Guide):


Awesome documentation can be found at: