Java

This what I have spent most of my time working in over the years and these are the little bits of logic or snippets I have come across. Some of these are things I have needed to search for or I have found I needed to feedback on code reviews.

Tomcat Deploy Same War With Different Ports

When the port is the decider as to which application instance you reach, the request is directed to the instance started from the appropriate application Context File context.xml contained within the Context Directory.

Tomcat Deploy Same War With Different Domain

When domain is the decider as to which application instance you reach, the request is directed to the instance started from the appropriate application Context File context.xml contained within the Context Directory.

Tomcat Deploy Same War With Different Path

When the path is the decider as to which application instance you reach, if the path begins with /red then the application will go to the application referenced in the Context File red.xml contained within the Context Directory, /green will go to green.xml and so forth.

Tomcat Deploy Same War Multiple Times

If you have a tomcat service and you would like to deploy the same or different version of a war multiple times there are 3 ways to accomplish this. The first is same host, same port and differing paths, the second is different hosts, same port and same path and the final is same host, different port and same path. Which is the right one for you depends on your infrastructure components such as proxies and domain configurations for example. This guide will help you understand what is required and how it would be presented.

sun.reflect.annotation.TypeNotPresentExceptionProxy

If you have seen either TypeNotPresentExceptionProxy or (the often wrapped by) ArrayStoreException you might have been surprised. In my case these have shown up most often when using generated code or using Spring auto configuration. It is not easy to tell at the time what this means or how to fix it.

java.sql.sqlexception ora-00911 invalid character

If you stumble across this issue it is likely because your query string contains a ';' character. 9 times out of 10 that is what it is for me. This usually occurs after I have written and verified my query in SQL Developer or SQLPlus and then copy and paste it into a Java string.

Maven jarsigner unable to sign jar duplicate entry in META-INF

jarsigner: unable to sign jar: java.util.zip.ZipException: duplicate entry: META-INF

Jar META-INF Manifest

In Java when you create an artifact such as jar you can and should include a manifest file in the META-INF directory. What is a manifest file and how do I use it?

Set, Get and Remove Session Attributes

When mentoring I have often found that sessions offer one of the least understood areas for some Java developers. This may be because sessions are not covered well in colleges but either way, I have found the following three nuggets to be useful. I will cover getting, setting and removing attributes from sessions. Each session has a HttpSession object which provides means of storing values in name-value pairs. You don't have a HttpSession object by default, but they are easy to create and access.

Servlet Returning a File for Download in the Response

You want to create a file and send it to the browser for the user to open and save. In the simplest example you pass a file to an OutputStream.

Servlet how to get JSP referrer file name within a servlet or JSP

There is often reason to find out which JSP called the servlet or JSP that is running. The file that directed the browser or client to the running servlet or JSP is called to as the referrer.

Logging in JSPs

Before I go any further, I will say that if you require logging in a JSP you have probably gone wrong somewhere in your design. That said I understand that for the most part these sometimes 'epic' JSPs are inherited and that leads to a need for some extra debugging.

JSP JSPX variable declaration and access

There are a number of ways to declare and access variables in JSPs and JSPX files. The diffences are mostly syntactical. In this tutorial I will cover ways of declaring and accessing using JSP/JSPX declarations and scriptlets and also JSTL and EL methods of achieving the same results.

JSP Implicit Objects

In a JSP the web container provides 9 objects (for free) implicitly. These objects are directly available to the developer for use without instantiation etc. JSP provides certain Implicit Objects listed below. These implicit objects are generated by PageContext.

JSP Get the URL of the present page

When in a JSP or Servlet it is often useful to retrieve the URL of the current JSP, to offer as a link or possibly bookmarking. This can be achieved in two steps. You must first get the hostname and directory structure. Using a google URL as an example this is all the text up to but not including the ? character: http://www.google.ie/search?q=www.tomred.net. This can be achieved using a method available in the JSP request JSP Implicit Objects request.getRequestURL().

JSP EL is ignored

If you have noticed that your EL ${} values are being output as plain text and not being interpreted there are two ways of sorting this out. There is a JSP page directive which enables EL for individual page or there is an entry for the web.xml which is applied to the entire application.

JSF i13n using Resource Bundles

If you want to provide your web content in multiple languages in a JSF project you need to you need to use resource (message) bundles. To use Resource bundles in JSF you have to create your .properties file and update the JSF config file. Finally you add the calling tag to the JSF to make the content available. I have outline the information in detail below.

How to add Spring functionality to an existing WebApp

It has been occurring more often these days that a request will be made to migrate an existing java application to the spring framework, the reasons don't really matter but usually there is a legacy system and the skills need to maintain it are less available or more expensive

Accessing a Spring bean from a servlet

I have most recently started work on a series of projects migrating some webapps away from a legacy EJB core to use a Spring core. The why is not important but the what is; when we wanted to access the Spring beans we had to do a bit of searching to find out how.

Hibernate HQL Case Insensitive Query

Recently we have been converting a legacy persistence framework to hibernate. One of the scenarios we have stumbled upon is the case insensitive like or ilike. While this is available as part of criteria queries there is no equivalent HQL function. We looked at this from a number perspectives in the end settled on the following.

Hibernate Repeated column in mapping for entity

If you are experiencing this there is one cause and two likely reasons. The first reason is that you have accidently repeated the mapping of one of your fields by annotating two fields with the same column or duplicating the entry in your hibernate mapping file hbm.xml. The seacond reason is that you intentionally have repeated your mapping. This is sometimes done to have read-only fields. In the first case you are looking for something like the snippet below this is outlining that there are two @Column annotations with the same name. This is usually easy to find and quick to fix.

Hibernate Exception unknown ordinal value for enum class

This exception one took me a while to track down. This is an enum equivalent to Index Out Of Bounds of arrays. This is usually seen when you have an enum that represents some semi-static database data. An example would be state, status or a type field. The enum value maps to the primary key of the table it represents; this field is used as a foreign key on other tables.

Hibernate Override JoinColumn

I had a huge pain chasing this down recently. It is often useful when subclassing in hibernate to be able to override a JoinColumn. This allows you to change the column associated with the field. For example in an embeddable audit class you may have a field called createBy which maps to a column called created_person. You may wish to reuse this in another case to map update info. In this second case for example you create another hibernate object or for use in this individual case you could override the association with an annotation but keep all the functionality the same.

java.lang.IllegalArgumentException: Illegal group reference

I have bumped into this recently while doing a replaceAll() and I had to do some research as to why it was happening. It is actually very simple. Your replaceAll() text likely contains $ or \. replaceAll() uses the Pattern() and Matcher() classes to do the matching. One of the features of Matcher is the ability to group sub-sequences using $. To allow the use of the string literal $ in the matcher sequence for the replacement string you can use the escape character \. So you can probably see the problem now. In the case of Match $ not followed by a number will throw and IllegalArgumentException.

java.lang.ClassCastException [Ljava.lang.String; cannot be cast to java.lang.String

This explains how to deal with the Ljava.lang.String cannot cast exception and outlines places where it is regularly encountered.

java.lang.UnsupportedClassVersionError: Bad version number in .class file

This error is simple enough to deal with. This is caused by a trying to run a java application (jar etc) which has been compiled using a different version then the version you are attempting to run with.

java.lang.NoClassDefFoundError

This one of the more obscure Java errors that you can get when attempting to deploy. Unlike its companion ClassNotFoundException this does not mean that the listed class can't be found but actually means that there is a dependency for this class that can't be met.

CORBA BAD PARAM

On a recent project I had the misfortune of trying to diagnose a org.omg.CORBA.BAD_PARAM error in the logs. I used all the standard tools debugging my way and could see no reason for this error.

Tomcat Deletes Context XML files

Apache Tomcat 5/6 deletes your context .xml file when you shutdown Tomcat. This one plagued a colleague of mine for a month before he blew his top. Essentially each time you stop Tomcat it deletes the file.

Tomcat Set Expires Headers

The majority of my most recent projects have revolved around Java on Tomcat. Tomcat is a nice Java server but lacks some of the features associated with the larger containers. One such feature is the inability for Tomcat to set Far Future Expires Headers natively.

Eclipse Remote Debugging

First of all debugging is the process of stepping through the code to help identify bugs or their causes. This is usually done locally as part of the development process but on occassion bugs occur in particular environments only or in situations that cannot be replicated in the development environment. In these case remote debugging is used. Remote debugging operates in a manner similar to local debug with the exception of the application running in a remote location. It is advisable to always have the same version of the code as is running in the remote location in your eclipse workspace or else you will see that the line numbers don't match up or your debug points don't exist.

Write to a file

To create and write to a file in Java you can simply create a FileWriter as in the first example and use the write method to print to the file. This is the simplest means and offers the most direct way.

Timezone Date Calendar

This one gets me every time, I have a timestamp or date object in one timezone and I want it in another. The most common problem is that when a timestamp is captured it is not in a known state. I have worked on many projects where systems stamp with current time. This can cause no end of trouble, the smartest way is to pick a common time and use that.

Simple Date Formatter

This is the easiest way of formatting today's date in Java. We will use a date formatter to format the date in the desired format.

Memory

When Java Memory is mentioned the words you often hear include Heap, Non Heap, PermGen and Eden etc. I have noticed over the years people are aware of the names but not the purpose or type of each. I have put a little diagram together to show how they fit. Boxes inside boxes. There is a desciption of the memory use and configuration value for each.

Logging when to use isDebugEnabled

This is something that I see again and again OMITTED when I do code review. There is debug logging which is not wrapped in if isDebugEnabled(). It is convention and can be less resource intensive if you follow this process.

Loading and Using Properties Files

At the start of every project or at least once during it I try to remember how to load properties files. This is a fairly basic thing but if you are like me and strive to maintain consistency within your work then you will need a common or simple format. There are several ways of doing this. I will outline them below. There are the simple FileInputStream methods and there are the ClassLoader and ResourceBundles also. I will leave it up to you as to which is the best approach, I find that as long as you are consistant you will be fine.

JMS Message Types

Having recently outlined how to Produce and Consume JMS messages it was time to outline how to send different message types. The previous examples used TextMessages but there is more to JMS than TextMessages; there is BytesMessage, MapMessage, ObjectMessage and StreamMessage.

JMS Producer

If you are here then you are looking for a way to populate and consume messages in a JMS queue. I have outlined the process below for a message Producer, Consumer and a Queue Browsers. I have provided an example of an abstract example class for both writing to (Produce) and reading (Consume) from the Queue. I have used ActiveMQ as it is a common message queue solution.

JMS Consumer

Following on from the previous article on creating a JMS Producer I have created this on creating a JMS Consumer. Once again consume messages from a JMS queue. I have outlined the process below for a message Consumer. I have provided an example of an abstract example class for both reading from (Consume) the Queue. I have used ActiveMQ as it is a common message queue solution.

JMS ActiveMQ Monitoring

When you have a running system one of the interesting elements that tends to pop up in monitoring. JMX is Java solution to this problem. In the case of a JMS queue you will want to keep an eye on the queue size along with the enqueue and dequeue rates. As we have used ActiveMQ in the examples JMS Producer, JMS Consumer and JMS Message Types we will stick with ActiveMQ for this short tutorial.

Import, Layer and Output Images

A recent project required me to accept an image from a user upload and to overlay the customer logo, before saving the file.  This wasn't a watermarking exercise but placing a voucher code on the image. 

HashMap toString and Back to HashMap

Every now and then I have to save a HashMap to a database or something and the most sensible way is to use the toString() method which gives a comma separated, equals delimited name value pair string, e.g. {name=bob,address=somewhere,phone=00-353-01-9875666}. This is useful for logging also (or audit trails). The problem arises when you want to read that string to a HashMap again. There is no native function to accomplish this. I have outlined a simple method below which will accomplish this

Generate HMac MD5 And SHA1

In my most recent work I have been tasked with managing payment gateways. I have noticed that in each case we require a HMAC (Hash-based Message Authentication Code). I also noted that in most cases I was given a string key. I found it initially difficult to get these elements to work and so I thought that I would outline how to do it here. This tutorial use JCE (Java Cryptography Extension).

Extended Email Validation Using DNS MX Lookup

I have on several occasions been asked what is the best way to validate an email address.  There is no simple answer, once upon a time you could query mail-exchanges (MX) directly to validate a user account but unless you have an internal mail server that is secured from the web then this is not likely to be possible.

Credit Card Number Validation Using Luhn Algorithm

The simple Luhn algorithm or Luhn formula is a method used for quickly validating credit card numbers (also IMEI and many others), it is explained in full on wikipedia. As it states it is useful for catching single digit errors or the transposition of adjacent digits, it is effective as an initial checker for credit card number submission.

Create PDF And Add Content

To generate this PDF we will use the iText Java PDF library.  We will first create a document of the correct size set some metadata and finally add some content.  At the end we will show you how to return a PDF (in this case our newly created PDF) to the users browser.

Convert File from UTF8 To ASCII

Often you will encounter a client with a legacy system that will only handle US-ASCII and in the world of UTF-8 that can be a pain.  In one case I had an API the served up a CSV file in UTF-8 which customers consumed.

Convert an array to a list or a list to an array

It is a simple process to convert an array to a list or vice-versa.

Convert an array to a list

Class Path

How to Get the Class Path using System Properties. If you need to access or see the contents of your java classpath inside an application you can access the java.class.path property under system property.

BufferedReader or BufferedInput The Correct Way

In development Buffers are a necessary evil, I say evil because it is often the case that they are not used cleanly. Due to the pressures of development it impetus in more often on getting it done over getting it done right. To Buffers this usually means the omission of the try/catch and the close statement. While these are not that big a deal it is something that is often picked up in code review or when running analytics software.

Articles

Java

This what I have spent most of my time working in over the years and these are the little bits of logic or snippets I have come across. Some of these are things I have needed to search for or I have found I needed to feedback on code reviews.

Oracle WebCenter (FatWire)

During my time working in consulting I was tasked many times with delivering FatWire sites. I took notes due to the lack of useful documentation at the time. These are the results of those notes made and shared.

CSS HTML JS

I believe the majority of time on a project is spent with the UI. Web is no exception. I have compiled a set of articles covering HTML, CSS and JS with the intention of taking the sting out of this work.

DevOps

A space dedicated to all those things you need to know beyond writing code. This covers Linux, Windows, Git and SVN among other hopefully useful nuggets.

Security

I picked up some pointers over the years consulting for government and banking sectors before entering a PCI DSS development environment. This section covers aspects like coding, testing, code review and best practice.

Apps

Apps is a section which offers access to bits and pieces I have put together over the last few years. This includes Random Password Generator and Base64 Encoder.