Random Password Generator in Java

I needed a random password generator done in Java and while reading a few articles here and there I did not find the solution I was looking for. Piecing a few of them I came up with some code.

One of the requirement that made this a bit more complicated is that I needed to have a special character in the password but from a limited list of possible special characters.
I also needed to make sure that it respected some basic complexity rules.

It has a dependency on the commons-lang 3 library from Apache but since I already had it in my project it was easy to accommodate.

Maven dependency:


Java code:

package com.halogensoftware.hosting.example;

import org.apache.commons.lang3.RandomStringUtils;

public class Random {

	public static void main(String args[]){
		String pwd = "";
		for ( int i = 0; i < 1000; i++ ) {
			do {
				pwd = RandomStringUtils.random(12, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890%#^*:");
			} while (!valid(pwd));
			System.out.println(i + ".valid pwd: " + pwd);

	private static boolean valid(String pwd){
		return (pwd.matches(".*([0-9]).*") && pwd.matches(".*([a-z]).*") && pwd.matches(".*([A-Z]).*") && pwd.matches(".*([%#^*:]).*"));

A Not acceptable Rest with Spring

Trying to come up with a clever title for a blog post is not easy.

This problem caused me headaches for 2 days and as much as I have resolved it I have no idea why and how it happened.

I have done REST application with Spring many times in the past and it easy. At one point in the process for this one I was creating REST application with STS just to confirm that it was a no brainer, which helped and puzzled me.

The simplest class that worked for me was something like this:

public class Rest {
    @RequestMapping(value="/{something}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
    public String[] firstTry(@PathVariable String something){
        return new String[]{something, "testValue"};

I could quickly package it with Maven and run it on Wildfly and it would work as expected.

When I tried to do the same in IntelliJ I was getting a non working application that returned a 406, Not Acceptable, return code to all REST calls.

I compared the web.xml, the application context xml files, the pom files, everything I could thing of and the STS app would work with nothing special but the IntelliJ app would not.

Most articles I was finding were talking about bugs in some version of Spring and to make sure you had the element in your application context xml. I tried many version and adding the annotation driven did not fix the issue.

I finally found this article that explained that you needed to make sure you specified the jackson-databind library in your pom.xml otherwise you would get 406 answers. Once I added the jackson libraries to my project from IntelliJ I was able to get things to work as expected.

No Jackson libraries are specified in my STS generated project and they work so I am still puzzled as to why this was needed in the IntelliJ project.

Upgrading Groovy and Grails

I have started to learn what Groovy and Grails can do for web application development and I already faced a fun problem.

After I installed GGTS (from Spring.io), I started a simple application and then wanted to upgrade the Groovy and Grails version to the latest.

Not as straight forward as I would have taught but I got everything working again.

First thing learned is that GVM is a useful tool to use to install Groovy and Grails and manage multiple versions. Doing it manually does not make sense.

I also learned from a stackoverflow article that you need to erase the .metadata directory in the GGTS workspace after upgrading. This will force you to re-import your projects but that is the only way I have found to recover the projects so it is a small inconvenience.

Back to learning!

Learning Groovy and GRails – 1 of X

I want to learn Groovy and Grails because I want to deliver applications faster and with better quality.

I am unsure if this is the right strategy but it is going to be a fun experiment. Learning is always fun.

I will start with a few videos and go from there:

I will also have to look at the documentation on the spring site to figure out all the static variables and built-in methods that can be used.

JSON API with Spring 3.1.2 and Jackson 2.2.0

It took me a few hours to get everything working but I am quite happy at how simple it really is.

I read this blog post that had most of the instructions on how to do it: Spring MVC with JSON via Jackson 2.0

Norris mentions that you need to make sure that you have the jackson-databind dependency otherwise you will get a 406 error. I was getting a 406 error even with the jackson databind because I did not have the mvc:annotation-driven specified. I assumed I had it and was surprised that it was not there (lost an hour to something so trivial).

I was also not sure how to submit a JSON post to the API that I was creating to validate that it worked. I found a few example but the one that worked for me was this answer on stackoverflow: Parsing JSON into Java objects in spring-mvc.

The other testing I needed to do was what the JSON message format was to send to Spring. I tried something like:

{ objectName: [ {“field1”: “value”, “field2”: “value”} ] }

But that was giving me 400 errors.

The JSON message format that works is:

{ “field1”: “value1”, “field2”: “value2” }

Note that I am submitting only 1 object at a time to the API.

The last error that I encountered is that I had an internal class for the status (return object on submission) that was private. I got a 500 error when the spring bean was trying to access it so I switched to a protected class and everything is working.

I like the short code that Spring allows me to write to get this to work. Should make it quite easy to maintain.

Gradle Test Failure Telling You More

I read this article:


and tried the code to see how it worked for me.


The only real gotcha was that FC17 installed Gradle 1.0 while 1.6 is available and the example only works with 1.6. I downloaded and installed the latest version to get the same results as outlined in the article.

I know that Spring has switched over to Gradle as the build system so I should probably get more familiar with it.

They have a free online ebook that I will read:


Spring Data JPA and the id field

When you make mistakes you learn more. Since this is true I can tell you that I am learning a lot every day.

Today I learned that your id field type in the entity need to be the same as the generics in the interface that implements the Spring Repository (CrudRepository in my case).

My entity has some code similar to this:

public class Table {

    private Long id;
    // more fields

And the code for the Repository is something similar to this:

public interface TableRepository extends CrudRepository<Table, Long> {

My mistake today was that my id field in the Table class was a int. My Spring application was returning this generic error message:

Could not execute JDBC batch update; SQL [insert into Table (name, id) values (?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Bonus: I also learned that it will throw the same error if you try to insert twice the same name value.

First try of Node.js

Spring Source has been advertising the scripted editor for a little while and I decided that I was going to give it a try.

First thing was to download an install Node.js itself.
Went to http://nodejs.org/ and downloaded the 64 bit linux tar ball.
Untarred in my /opt/ directory: tar zxvf node-v0.10.0-linux-x64.tar.gz

Once installed I could easily start node.js: /opt/node-v0.10.0-linux-x64/bin/node

Not much can be done with that but at least I know that it is running.

I copied the sample code from their documentation to an example.js

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello Worldn');

console.log('Server running at');

And I can easily run this sample code: /opt/node-v0.10.0-linux-x64/bin/node example.js

Which gives you this output (at the command line): Server running at

Which gives you the “Hello World” web page when you open the link in your browser.

The real step is then to install scripted. It seems too easy from the Spring Source page since all you have to do is: npm install -g scripted

Did a lot of work but it currently ends with errors:

> scripted@0.4.0 postinstall /opt/node-v0.10.0-linux-x64/lib/node_modules/scripted
> cd client && bower install
throw new TypeError(‘Arguments to path.join must be strings’);
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at Object.exports.join (path.js:358:36)
at Object.<anonymous> (/opt/node-v0.10.0-linux-x64/lib/node_modules/scripted/node_modules/bower/lib/core/config.js:35:22)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
npm ERR! scripted@0.4.0 postinstall: `cd client && bower install`
npm ERR! `sh “-c” “cd client && bower install”` failed with 8
npm ERR!
npm ERR! Failed at the scripted@0.4.0 postinstall script.
npm ERR! This is most likely a problem with the scripted package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! cd client && bower install
npm ERR! You can get their info via:
npm ERR! npm owner ls scripted
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.7.3-101.fc17.x86_64
npm ERR! command “/opt/node-v0.10.0-linux-x64/bin/node” “/opt/node-v0.10.0-linux-x64/bin/npm” “install” “-g” “scripted”
npm ERR! cwd /home/mc
npm ERR! node -v v0.10.0
npm ERR! npm -v 1.2.14
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/mc/npm-debug.log
npm ERR! not ok code 0

I also tried downloading the scripted 0.4.0 zip file and the install gives the same errors. As the scripted site is recommending to use Node.js 0.8.6 it is obviously not working with the latest (0.10) yet.

Spring Data JPA

I have an existing project where I wanted to start using the Spring Data JPA library to stop having to do all the code involved in a DAO. It sounded like a smart idea (without any prior knowledge) but when I tried to implement I realized that every time you try something new there are a few hurdles and unexpected surprises.

Searching for solution and tutorial with Google might be a good fallback plan but I found so many references to different ways that I got confused before sorting it out a bit. What you don’t easily see in all the solutions is which version of which library they are using until you have read most of the solution. I wish we could more easily search for examples and tutorial based on library versions.


Here is what I used for my project:

Spring Core 3.1.2.RELEASE
Spring Data 1.1.0.RELEASE
Apache Derby (old version)
Hibernate 3.6.9 (old version)


Since I was working within an existing project I needed to work with certain things in place that I could not remove to use the Spring Data JPA library.

I needed to work with some XML files for the application context.

I needed to work with Apache Derby (old version).

I needed to work with Hibernate (old version).

Code changes

First thing that I needed to do was to add some dependencies in my pom.xml to be able to use Spring Data JPA.


It took me some trial and error to also realize that I needed an entity manager and since I was using Hibernate the logical choice was:


I already had the Hibernate dependency in my pom.xml before starting:


In my Java code I already had an entity that I wanted to use but because of the other entities that were managed under hibernate without Spring Data JPA I had to move this one to its own package so I could use some package scanning. Here is the entity code:

package com.cinq.test.domain;

import java.util.GregorianCalendar;

import javax.persistence.Column;
import javax.persistence.Entity;

public class Event {

private Long id;
private String title;
private String Description;
private GregorianCalendar date;

public Long getId() {
return id;
public void setId(Long id) {
this.id = id;
public String getTitle() {
return title;
public void setTitle(String title) {
this.title = title;
public String getDescription() {
return description;
public void setDescription(String description) {
this.description = description;
public GregorianCalendar getDate() {
return date;
public void setDate(GregorianCalendar date) {
this.date = date;


I needed to create a public interface to bind this entity to the Spring Data JPA “magic”. It simply needs to extend the CrudRepository and all the CRUD code is created for you.

package com.cinq.test.repository;

import org.springframework.data.repository.CrudRepository;

import com.cinq.test.domain.Event;

public interface EventRepository extends CrudRepository{


I also needed to add some quick configuration to my app-servlet.xml to get Spring to scan for repositories at startup:

All the code is available at:

Issues that needs to be worked out

The application runs on Tomcat but is giving an exception for a class not found on JBoss 7.1.1. I will have to look at the vfs settings for a default install.

I still need to fix the form submission.



Spring Data – JPA (Starting point at SpringSource)
The Persistence Layer with Spring 3.1 and JPA (Starting point – tutorial)
Difference between configuring data source in persistence.xml and in spring configuration files (highlighted that with Spring 3.1 you don’t need the persistence.xml)
5 minutes with – Jpa transaction (highlighted the databasePlatform property in the xml configuration)
Problems with Spring maven hibernate org/hibernate/ejb/HibernatePersistence (need for hibernate-entity-manager)
13. Data access with JDBC (reference material for many items)

Eclipse completion template

Someone gave me some  code for a logger auto-completion template that I should use in Eclipse.

After searching on Google and discovering where it is in STS 3.1.0 I added this simple template to auto-complete my logger to use slf4j:

${:import(org.slf4j.Logger, org.slf4j.LoggerFactory)}private static final Logger ${logger} = LoggerFactory.getLogger(${enclosing_type}.class);

This is configurable under the Window -> Preferences -> Java -> Editor -> Templates




I created a new template that I named logger, context is Java, a description (slf4j logging) and the pattern mentioned earlier.

Quite simple and so convenient that it will remove this bad habit of copying and pasting code with the wrong class name.