Often in JSP we find ourselves creating links to other pages within our web application.  The below code allows us to easily get the web application context path from within a JSP file.

${pageContext.request.contextPath}

Utilizing JSTL we could also set this value to a variable so that we have a short hand method for getting the context path.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="cp" scope="session"
        value="${pageContext.request.contextPath}" />

This enables you to use ${cp} to output the context path.

, ,

Why should developers use logging?

Logging to those new in the development world is the process of putting output statements inside your code to facilitate debugging and analysis of performance or issues.  Development of an application is completed by going through a life-cycle that typically includes requirements, code production, testing, and deployment in some manor. Logging enables developers to easily debug their code while in the testing phase by readily seeing output of variables and trace statements placed in their code, also while in the deployment phase having logging set up can enable the developer to analyze where an error occurred if the application crashes or gets hung up.

Be warned though that logging can slow down an application if used excessively. Be sure to use as needed during development but in production only have logging enabled for critical sections of the code.

What is log4j?

Log4j is a popular logging package for the java language licensed under the Apache Software License. It enables a developer to easily add logging to their applications that is easily configurable on run-time to restrict which statements are to be logged, how they are formatted, and where they should be logged. For those who program in the C family of languages log4j has been ported to C, C++, C#, and other languages.

How do I use log4j?

To utilize log4j in your application you need to have the log4j jar file in the project library and have the main Logger class imported by the statement:

import org.apache.log4j.Logger

Once the Logger is imported you can instantiate it for a Class by using the getLogger method, I suggest creating a static logger property for your class you want to do logging in. The getLogger method takes a string parameter to define the logger instance it is common practice to use the Classes class as the value.

private static Logger log = Logger.getLogger( ClassName.class );

To log a statement you simply use the trace, debug, info, warn, error, and fatal methods. These will log the inputted string at the level that matches the method.

log.info( "my first log statement" );

At this point your logging statements are all set to go but you have not as yet defined where they should be outputted. For beginners it is best to use the BasicConfigurator to configure the Logger to ouput to the console. This is great for development purposes and as you get more advanced you can move on to Property and DOM Configurators that enable more advanced configurations. It is important to remember that the configuration only needs to be run once per application and should be done before any logging statements.

import org.apache.log4j.BasicConfigurator;
BasicConfigurator.configure()

Resources

, ,

What is Test-driven Development?

Test-driven development is a process or technique for the development of software or code. The main focus with this process is the understanding of the requirements to enable the developer to write tests for new functionality and features before they write any code. This enables the developer to have a specific goal to work towards.

The development process contains 5 basic steps:

  1. Write a Test Case that will test a new feature or functionality.
  2. Run the Test Case
    1. The Test passes – Then either the new feature already exists in the code or the test does not test the requirement, return to Step 1
    2. The Test fails for unexpected reason – verify the Test is correct as it may not be written to properly test the feature, return to Step 1
    3. The Test fails as expected – proceed to step 3
  3. Write code
  4. Run the Test Case
    1. The Test fails – modify the code as it does not provide the necessary functionality, return to step 3
    2. The Test passes – new functionality added, proceed to step 5
  5. Refactor the code.  In this step the developer cleans up the code by removing magic numbers doing performance enhancements. By rerunning the Test Cases the developer can be assured that no bugs were introduced into the code.

This short 5 step life cycle enables the quick development of new features and functionality to an application. It also allows for regression testing of the software as new features are introduced ensuring that old functionality is not broken by any new enhancements.

What are some benefits to Test-driven Development?

Like all techniques the end results are dependent on the developer but some of the benefits that can be obtained by using this process are:

  • The quick development of new features as developers write code to add one feature at a time.
  • Enhanced confidence in the end product as in theory there is a Test Case for every functionality.
  • Backwards compatibility – by having a test suite for all functionality previous functionality will still be working correctly unless their Test Cases fail
  • Quick Roll Back capability – by tracking the code when each new feature is functional it allow the developer to quickly roll back to a previous state if the current code they are writing is failing to pass the Test Case.
  • Enhanced Developer confidence in themselves as the Test Cases give instant gratification that what they are writing works.
,

What is a Property File?

A .properties file is a file used to store the configurable parameters of your Java application. The standard format for the Property File is one parameter per line with key value pairs delimited by the  equals (=) character. Comments are allowed in the file by placing a # or ! character at the beginning of the line. If by chance you would like to use multiple lines for your property value the back slash (\) character can be used to denote the value continues on the next line.

Sample File

#sample comment
user = MDBitz
password = test123
website = mdbitz.com

Loading the Properties File into your application

Properties can be loaded into your application in various methods the two most common is to load the properties from the classpath or from an external properties file. Loading the properties from the classpath means the file is bundled in with the java source code and a new deploy will be needed to modify the properties while external files can be changed more readily.

Loading from the Classpath

Loading from the classpath is performed by utilizing the ClassLoader to obtain the url of the desired property file. The Properties object then loads the input stream of the url that is returned by the openStream method.

Properties props = new Properties();
URL url = ClassLoader.getSystemResource(propsName);
props.load( url.openStream() );

Loading from an external file

To load an external file we first instantiate a new Properties object, then proceed to load the file by use of a FileInputStream. After loading the file we close the input stream to clean up our resource usage.

Properties props = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
props.load( fis );
fis.close();

Using the Properties Class

Once the properties have been loaded they can be utilized by the getProperty method. This method takes a string representing the key and returns the property assigned to that key.  To verify that a property exists before trying to obtain it the containsKey method can be used to check if the Properties object cans a property with the inputted key.

if( props.containsKey( "website" ) ) {
    System.out.println( props.getProperty( "website" ) );
} else {
    System.out.println( "Default Website" );
}

Conclusion

The use of a Properties Files can easily add dynamic elements to your application on run time. They can be used to specify the database connections to be utilized or more general properties such as labels or logging levels.

Resources

PropertiesUtil Class

package com.mdbitz.utils;
 
/*
 * Import Statements
 */
import java.util.Properties;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.net.URL;
 
/**
 * Utility for loading property file into Properties object
 * @author MDBitz - (Matthew Denton)
 */
public class PropertiesUtil {
 
	/**
	 * Private constructore to disallow instantiation
	 */
	private PropertiesUtil()
	{
 
	}
 
    /**
     * Load a properties file from the classpath
     * @param propsName
     * @return Properties
     * @throws Exception
     */
    public static Properties load(String propsName)
        throws Exception
    {
        Properties props = new Properties();
        URL url = ClassLoader.getSystemResource(propsName);
        props.load(url.openStream());
        return props;
    }
 
    /**
     * Load a Properties File
     * @param propsFile
     * @return Properties
     * @throws IOException
     */
    public static Properties load(File propsFile)
        throws IOException
    {
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);
        fis.close();
        return props;
    }
 
}
, ,

Java Calendar

The Calendar class is a java utility for obtaining and modifying the current date and time. It contains all the functionality necessary to get the current time in any time zone as well as methods for manipulating the Date.

import java.util.Calendar;

Java SimpleDateFormat

The SimpleDateFormat is another utility that is used to format a Date object into a String based on the supplied format. The SimpleDateFormat object can be used to return the full date and time, date only, the month, or any such combination.

import java.text.SimpleDateFormat

How to use the Calendar utility

The Calendar object is instantiated by using the getInstance method.

Calendar calendar = Calendar.getInstance();

Once you have an instance of the calendar you can obtain the Date by use of the getTime method

calendar.getTime()

It is a common practice of having to modify the Date object to a different time in our applications. This is done by the set and add methods. The add method is used to manipulate a parameter of the Date while the set method is used to set a parameter to a certain value.

For example if we wanted to get yesterdays date we would use the add method and modify the Date by -1.

calendar.add( Calendar.DATE, -1 );

We could also modify the month the same way.

calendar.add( Calendar.MONTH, 1 );

However if we wanted to change the Date to the first of the month we would use the set method

calendar.set( Calendar.DAY_OF_MONTH, 1 );

In addition to the constants above that represent the date, month, and day of month there are others for year, seconds, hours, and etc that can be used to modify the date in any many necessary for your application.

Using the SimpleDateFormat Object to return the Date in readable format.

To return a readable string representation of the Date obtained by the Calendar object the SimpleDateFormat format method is utilized. This method returns a string that represents the inputted date based on the format of the SimpleDateFormat object.

To instantiate the SimpleDateFormat object you call its constructor passing the textual format of the desired output of the date.  The format object understands the standard date and time representations of dd, mm, MM, YYYY, yy, and etc.  The example below shows how to display the time format as Date/Month/Year.

SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yy" );
String date = dateFormat.format( calendar.getTime() );

Conclusion

Utilizing the Calendar and SimpleDateFormat objects allows you as a developer to easily obtain and modify the Date without doing custom arithmetic. They can be especially helpful in generating SQL queries for obtaining data for the past month, year, or a range of times.

Resources

, , , ,