Showing posts with label maven. Show all posts
Showing posts with label maven. Show all posts

Tuesday, January 14, 2014

Unit Testing Example with Code Coverage using Cobertura

Cobertura Coverage in NetBeans 7.4
I gave a presentation on unit testing a few months ago at Greenville Java Users Group (GreenJUG) about unit testing using JUnit and Cobertura. I finally have gotten around to publishing the code with a little cleanup.

NetBeans will detect the addition of Cobertura in the POM file and automatically add menu items for checking code coverage. This is a very slick feature in NetBeans.

The Cobertura coverage shows 90% in the project because it does not handle the generics correctly at this time.

The Apache Maven based project can be downloaded from Bitbucket below:

unit-testing-demo

Here is an example snippet of the code.

ListDataStoreImplTest.java


Saturday, November 30, 2013

Java EE 7 Tip of the Day: Web Application Lifecycle Listeners

Introduction

I have been trying to come up with a way to highlight these fascinating classes in a way that demonstrates their power and usefulness. In my post Java EE 7 Tip of the Day: Programmatic Control of Session Tracking with ServletContextListener I highlighted the use of the ServletContextListener to set session tracking programmatically. However, there are a number of listener classes that can help you. Here they are in generally decreasing scope:

Web Application Lifecycle Listeners

ServletContainerInitializer

The ServletContainerInitializer is a special case that must be registered with the Service Provider Interface (SPI) loading mechanism. Please see the Javadocs for more details on its usage. That is a topic for a different post.

ServletContextListener

The ServletContextListener has been previously mentioned in another post as noted above. This listener is notified of lifecycle changes, e.g. context initialized and destroyed. This gives the developer the opportunity to perform application setup such as setting a logger, or enabling other listeners. It also provides a clean mechanism to handle application cleanup when an application is shutdown, or disabled.

ServletContextAttributeListener

The ServletContextAttributeListener listens for events that occur when attributes are added, modified, or removed from the ServletContext. This could be used to modify those attributes, or perhaps log them. Interestingly, the order in which the implementations are invoked is not specified.

HttpSessionListener

The HttpSessionListener listens for session creation, and destruction events. I have found this to be one of the most useful classes in a web application. This can be used to set up a persistent data connection while the session is valid, and close the connection when the session expires, or is invalidated.

The listener implementations are invoked in the order of declaration, and destroyed in reverse order. A way to think of this is like the layers of filo dough. If you go from top to bottom, then you must reverse order from bottom to top.

HttpSessionAttributeListener

The sibling interface HttpSessionAttributeListener is the second most used class in my toolbox for listeners behind the ServletContextListener and HttpSessionListener. I have found that I often need to examine when attributes are added, modified, or removed from a session. This is the tool I use to manage that.

Keep in mind that the HttpSessionAttributeListener behaves like the ServletContextAttributeListener in that the order in which the implementations are invoked is unspecified. This means that you can not rely on a specified ordering to take place across containers. Usually, the ordering is consistent on a container basis, but the contract is explicit that the ordering is undefined.

HttpSessionIdListener

This is a new to Java EE 7. The HttpSessionBindingListener is used to handle when a HttpSession ID changes. This is usually the result of a HttpServletRequest.changeSessionId() command. This was added in Java EE 7 to help solve a security issue called Session Fixation. Typically, you would change the session id after the user successfully authenticates. This can help you with this transition. Otherwise, you need to do a lot of work to make it happen. In this case, it is just great to be able to let the API handle it.

This interface will allow you to modify your application based on the ID change. Please note that the order in which the implementations are invoked is not specified.

HttpSessionBindingListener

The HttpSessionBindingListener listens for binding events. This occurs when an object is bound, or unbound from a session. There are a couple of examples from BalusC on Stackoverflow. Here are a couple: Getting SessionScoped bean from HttpSessionListener? and How to access HTTP sessions in Java. These are just a couple of examples on its usage. I personally have never used it directly. I was just thinking I should come up with my own example for it.

ServletRequestListener

The ServletRequestListener is another listener that I use. However its usage is not as frequent as the other aforementioned ones. I usually end up checking the ServletRequest with an instanceof for HttpServletRequest and casting it. This listener will allow you to modify an individual request.

Since it has every request pass through it, you should make sure that there is no excessive overhead in the listener such as database lookups, or excessive logging. Abuse of this listener can result in massive performance issues.

ServletRequestAttributeListener

Finally, we have the ServletRequestAttributeListener that listens for request attribute changes. The same warning as noted in the ServletRequestListener applies here. Any excessive overhead will result in dramatic performance decreases.

Like the other attribute listeners, this listener does not have a specific order in which they are invoked.

Code Examples

The code for this project was developed using NetBeans 7.4, Apache Maven, Mercurial, and is hosted on Bitbucket. The code in the examples is somewhat contrived, but does demonstrate the functionality of the listeners.

I strongly recommend downloading the code, executing it, and looking at the output. It will give you a better picture of how the code works, and also show you some hidden "features" of your application that you may be unaware of.

The source code can be downloaded from here: web-application-listeners.

ServletContextListenerImpl.java



ServletContextAttributeListenerImpl.java



HttpSessionListenerImpl.java



HttpSessionAttributeListenerImpl.java



ServletRequestListenerImpl.java



ServletRequstAttributeListenerImpl.java


Conclusion

Web application lifecycle listeners are essential tools for the web developer. If you are not using them, you should consider them to simplify your web development. Hopefully the explanations and code provided help you along your path to becoming a great developer.

Friday, November 29, 2013

Cleaning Multiple Maven and Ant Projects

I am trying to put a bunch of my code on my Google Drive to back it up. I have had a couple of bad experiences lately around failed hardware, and needing some code that I could not get to from a remote machine. I copied all of the projects to the Google Drive in the interim. I am not sure if this is a good idea since the builds in the IDE seem cause it some issues, but until I have everything on Bitbucket, I will need to have it on the drive.

Anyway, I was looking for a way to make sure all of the projects were clean so that I could conserve space, save money, and keep the scanning to a more minimal level. So how do you step through each directory and issue commands to clean the projects. Here are my examples:

Maven


Ant



Please note that I set the maxdepth to 1 so that it would not recursively keep digging down directory levels invoking the command. The -type d option is to only examine directories starting from the current directory. The cd{} shell command tells the script to go into the directory that was found and execute the following command.

I hope that this might save someone a few minutes.

Saturday, May 05, 2012

JSF 2 Tip of the Day: Programmatic PhaseListener

I had a use case where I needed to use a PhaseListener programmatically. I had originally tried to use a faces-config.xml to add the listener. I encountered a problem with an ear file which contained a war that contained a space. When Weblogic expanded the ear file it could not find the faces-config.xml since the path from expanded ear file had a space. Unfortunately, the program had too many dependencies to change to remove the space. So I decided to inject it. I was quite surprised to find that there was no annotation for PhaseListener in JSF 2.1.

Undaunted, I decided to figure it out. Admittedly, after I figured it out, I searched on Google, but everyone who had posted a solution did not a good example , or it was not quite as elegant as mine. I believe.

Specifically, my use case was to provide programmatic login where I use a PhaseListener to determine if the user is authenticated before restoring the view. This particular use case means that I must have the PhaseListener injected prior to responding to any requests. Fortunately, the JSF 2 API makes it very easy to do this.

The basic design is as follows:
  1. Use a @ManagedBean(eager=true) annotation. The eager attribute forces the container to load the bean immediately rather than lazy loading.
  2. Use the @ApplicationScoped annotation. This will allow us to set the PhaseListener for the whole application.
  3. Create a method which has a @PostConstruct annotation. This will allow us to set the listener immediately following the constructor.
    Note: You will want to follow this design so that if there are any annotations, they will be processed prior to adding the PhaseListener.
  4. Add the listener in the @PostConstruct method.

The JSF 2 API does a great job of explaining, how to use the LifecycleFactory to get a reference to the Lifecycle object. This is the key to adding the PhaseListener. If you are an API developer, this is a great example of documentation for people who want to use your API.

Code

The code for the project was developed using NetBeans 7.1.2 using Apache Maven. The code can be found here: programmatic-phaselistener.zip

ApplicationBean.java


Thursday, January 12, 2012

JAX-RS Tip of the Day: Client Content Negotiation

One of the less discussed aspects of JAX-RS based on the HTTP 1.1 specification is client negotiation. We often write our applications from the server side and expect the client to send us an Accept: */* header which details which media types the client can accept. The server simply returns whatever we have coded for example @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}). However I bet a number of you have seen something like this before:
http://www.example.com/documents/mydoc?format=doc
http://www.example.com/documents/mydoc.xml
The first example is not very subtle. It tells you the client wants a mydoc.doc by requesting a specific format. The second example is more subtle, and the end user (client) may not notice. I made it a "little" more obvious by changing it to .xml. However, most folks would have missed it if I used mydoc.doc. You would have assumed it was a MS Word document to start with. In actuality, the media type returned here is controlled by the file extension.

Note: Updated the source code to include header based negotiation, but this is just mimicking server content negotiation.

In the attached Apache Maven project developed on NetBeans 7.1: jersey-content-negotiation.zip. I demonstrate how to do it.

The first example returns JSON by default, and other media formats as requested. If it does not understand the media type requested, it simply returns plain text.

On the second example which uses the media type extension, I return a 400 - Bad Request instead of plain text like the first example. This subtlety is based on the fact that the client is requesting a specific type based on extension. If you ask for .pdf and get .txt, the result may cause an unanticipated consequence so it is better to throw an exception.

The mixed media type returns are possible because of the Response being wrapped as demonstrated in a previous post: JAX-RS Tip of the Day: Use Response to wrap... Responses.

ContentNegotiationResource.java



Client Negotiation Examples

Thursday, December 15, 2011

Java Tip of the Day: Using ProcessBuilder to Make System Calls

A few years ago I posted an article on how to execute OS level system calls using the Runtime class. When I wrote that article I was using a methodology which has been around since the 1.0 days of Java. In Java 5 Standard Edition, and subsequently improved in Java 6 and Java 7, is a class called ProcessBuilder. This class is a significant improvement over using the Runtime class. It provides complete flexibilty around the system call in terms of environment including directories, input and output streams, and execution.

Here is the NetBeans 7.1 Apache Maven project: process-builder-example.zip


When I execute it from NetBeans I get something like this:
[exec:exec]
total 24
drwxr-xr-x  12 jyeary  staff   408B Dec 15 08:19 .hg
-rw-r--r--   1 jyeary  staff    52B Dec 15 08:08 .hgignore
-rw-r--r--   1 jyeary  staff   1.7K Dec 15 07:59 nbactions.xml
-rw-r--r--   1 jyeary  staff   2.0K Dec 15 08:19 pom.xml
drwxr-xr-x   4 jyeary  staff   136B Dec 14 23:31 src
drwxr-xr-x   4 jyeary  staff   136B Dec 15 08:35 target
Exit Status : 0

Friday, December 02, 2011

Coding Tip of the Day: Using Map<?,?> Collections

I was working on some code in the last few days where I came across a protected Map map instance variable. I examined the code and javadocs which indicated that the intent was to provide a mapping of keys and values. However the actual implementation was setting the keys and values to the same value. This again is not really an issue. However, the usage of the Map was incorrect.

See if you can determine the issue from the code below.
The MapValueHolder<K,V> looks like the following. Here is the implementation.
As a general rule, you should use the key to fetch the value. Even if you expect that the values are the same. Since the instance variable is protected it can be modified in a sub-class, or any class in the same package. Since we code to interfaces, or abstractions (super classes). We can not be sure that the implementation class we are provided does what we expect. In this case, it does what we expect.
MapValueHolder Key --> A
MapValueHolder Key --> B
MapValueHolder Key --> C
A --> A
B --> B
C --> C

Here we continue using another implementation.


This time the result looks different.


MapValueHolder Key --> A
MapValueHolder Key --> B
MapValueHolder Key --> C
A --> null
B --> null
C --> null

This is because our MapValueHolder<K,V> is different.


Admittedly, the implementation above is a bit contrived. We really are getting is a Set<K>. In the next example, we get another result.


The result is considerably different.


MapValueHolder Key --> A
A --> A

Here is the implementation. Again, this is a contrived result where we are just returning the first key and value in a Map<K,V>. Here is another example which demonstrates unexpected results. This results in this very strange result.

Map --> {}

Here I use reflection to modify the expected result. If you have followed me to this point, you will have learned a little bit about the Java Type system, reflection, abstraction, and Collections. Yet, you may be asking what is the tip? Here are some rules:
  1. Use the keys to fetch values.
  2. Check for null values. In my examples, I did not check for null values.
  3. Use the correct Java Collection.
The Java Collection Framework covers most common cases. Take the time to read about them. The code above was based on a couple of issues I discovered: (1) Using keys for values, and (2) not using the correct collection. In this case, they should have used a List<V>. If they wanted to use an ordered Map<K,V>, they should have used a LinkedHashmap<K,V>

The code for the examples are here: bad-mapping.implementation.zip

The code was developed using NetBeans 7.1 RC1.

Saturday, October 29, 2011

RESTful Web Services: DeliciousHttpClient Example

I have been working on designing a replacement architecture for an enterprise application at work. As a result, I have been doing a lot of work with REST. The seminal work on REST is RESTful Web Services by Leonard Richardson and Sam Ruby from O'Reilly & Associates. The book is a couple of years old, but relevant today. There is only one issue with the book. There are a number of examples that do not work as expected in the current framework editions.
One such example is using Apache Commons HTTP Client. This particular framework is deprecated, and has been replaced by Apache HTTP Components.
The example code below demonstrates how to perform a RESTful call to del.ic.io.us to retrieve saved bookmarks. This is based on the application listed on page 35 of the book.
The Apache Maven based project can be downloaded here: delicious.zip.

 

DeliciousHttpClient.java


Tuesday, July 05, 2011

JSF 2.x: Creating a Pure AJAX Application with Apache Tomahawk

Official logo of Greenville, South CarolinaImage via Wikipedia
I was working on creating an application to make calls to a MongoDB database. I was having some difficulties getting the REST based services to work. I decided to make sure that my coding principles were sound so I wrote this application.

The application uses Expression Language (EL), and "pure" JavaScript (no JS frameworks).

Disclaimer: There were no-frameworks harmed in the making of this application.

The application makes an AJAX call to a GeoNames web service called http://api.geonames.org/weatherIcaoJSON?ICAO=KGSP which returns the weather information for Greenville-Spartanburg (Greenville, SC) Airport. There are some other examples which demonstrate some of the things you can do in Expression Language (EL), and how to inject it into JavaScript.

The application I believe demonstrates that you can JSF without managed beans, and make separate AJAX calls to populate the page with data. This is not a normal method of creating a JSF application, but does demonstrate the flexibility of the JSF framework.

The application was done using Apache Maven on NetBeans 7.0 IDE. The source can be downloaded here: jsf2-tomahawk2.zip

Requirements
  • NetBeans 7.0 (You could use just Maven)
  • Apache Maven 2.2+
  • Internet Connection (Required if dependencies are not on system)

index.xhtml



project.js


/*
 * Copyright 2011 Blue Lotus Software, LLC.
 * Copyright 2011 John Yeary.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var weather;
var weatherJSON;

function ajaxWeather() {
    if (!document.getElementById('panelTab1.content').hasChildNodes()) {
        return;
    }
    var url = 'http://ws.geonames.org/weatherIcaoJSON?ICAO=KGSP';
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        alert('You are using Internet Explorer. Switch to a real browser!');
    }
    xhr.onreadystatechange=function(){
        if (xhr.readyState == 4 && xhr.status == 200){
            weather = xhr.responseText;
            weatherJSON = eval('(' + weather + ')');
            document.getElementById('panelTab1:unavailable').textContent = '';
            document.getElementById('panelTab1:stationName').textContent = weatherJSON.weatherObservation.stationName;
            document.getElementById('panelTab1:ICAO').textContent = weatherJSON.weatherObservation.ICAO;
            document.getElementById('panelTab1:latitude').textContent = weatherJSON.weatherObservation.lat + "\u02da";
            document.getElementById('panelTab1:longitude').textContent = weatherJSON.weatherObservation.lng + "\u02da";
            document.getElementById('panelTab1:temperature').textContent = weatherJSON.weatherObservation.temperature + "\u02daC";
            document.getElementById('panelTab1:humidity').textContent = weatherJSON.weatherObservation.humidity +"%";
            document.getElementById('panelTab1:windSpeed').textContent = weatherJSON.weatherObservation.windSpeed + " knots";
            document.getElementById('panelTab1:windDirection').textContent = weatherJSON.weatherObservation.windDirection +"\u02da"
        }
        if (xhr.readyState == 4 && xhr.status == 503){
            document.getElementById('panelTab1:unavailable').textContent = 'Weather service is unavailable. Please reload page';
        }
    }
    xhr.open('GET', url, true);
    xhr.send();
}

function setText(){
    if (document.getElementById('panelTab6:div1') != null) {
        document.getElementById('panelTab6:div1').textContent = msg;
    }
}

Enhanced by Zemanta

Sunday, July 03, 2011

Creating a Maven Web Application Archetype in NetBeans 7.0

Slide | The Seven Rules of Great Web Applicati...Image by quasarkitten via Flickr
The  basics for creating a Maven archetype can be found in the Maven - Guide to Creating Archetypes. The guide gives general guidelines for creating an archetype, but no specific details for web applications. This tutorial will show you a simple way of creating a web application archetype and using it. We will use NetBeans 7.0 to create our project, create the archetype, and consume it. This application uses JSF 2.x and GlassFish. However the principles are the same for web applications in general.

The first more practical approach is to create, or use an existing application, and convert it to an archetype.
  1. Create a new Maven web project in NetBeans.
  2. Modify the pom.xml to include the dependencies you require in the project.
  3. (Optional) Modify the pom.xml to include a license
  4. (Optional) Create a web.xml. This is not required for JEE6 web application generally. However, we need one for the Faces Servlet.
  5. (Optional) Add a resource file for externalizing message resources
  6. Create a basic web page, and supporting classes. JSF for example has the following.
    • Index.xhtml
    • IndexBean.java is a Java EE 6 JSF @ManagedBean, and @RequestScoped bean. You could use @Named and @RequstScoped from CDI as well.
  7. Once you are satisfied withe the project, execute mvn archetype:create-from-project. This will create your new archetype in the target/generated-sources/ directory.
  8. Open the newly created project in NetBeans and make any necessary changes.
  9. Next execute mvn install. This will install your new archetype in the local repository.
  10. Create a new project using the new archetype, and run it.
Here is a link to the project: jsf2.zip You can create the archetype from it.

I have created a Youtube video that demonstrates the process.




Enhanced by Zemanta

Sunday, June 26, 2011

How to Check JDK Supported Encodings and Locales

A map of the various different languages in EuropeImage via Wikipedia
I was working on an issue with a customer about supported locales.  The JDK comes in two varieties: one is for only western languages including European languages, and the other is multilingual. This includes languages like Thai which have different glyphs. The supported encodings for Java 6 are defined here: Supported Encodings. The issue was a download of the standard JDK download on Windows which does not include charsets.jar for use in an international application.

I figured out the issue by creating a simple web application to check the encodings. I figured I would provide it just in case other folks may be able to use it Otherwise it would just be good simple code gone to waste. Here is a link to the maven project: SupportedLocales.zip


Enhanced by Zemanta

Sunday, June 05, 2011

JSF 1.2 (Mojarra) Reference Implementation (RI) on Google App Engine

Image representing Google App Engine as depict...Image via CrunchBase
I am working on publishing the various methods for deploying JSF on Google App Engine. This example is deployed using JSF 1.2 reference implementation. I am using NetBeans 6.9.1 with the Google App Engine plugin. The code used is vanilla JSF with no additional frameworks.

The web.xml and Maven pom.xml files are posted on the deployed application which is running on the App Engine itself.

The implementation can be found here: http://gae-jsf12.bluelotussoftware.com/
Enhanced by Zemanta

Saturday, November 06, 2010

Apache Maven AntRun Plugin Configuration

Apache Maven logo.Image via Wikipedia
I was looking for an up-to-date example of how to use the Apache Maven AntRun plugin version 1.6. The examples that I found on the plugin's home page have not kept pace with the actual development.

I have included my build.xml example file below, and the pom.xml configuration to run it. Please note the comments under the antrun plugin to understand what is happening.

build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="mavenproject1" default="default" basedir=".">
    <target name="default">
        <echo message="Hello World from build.xml"/>
    </target>
</project>
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.bluelotussoftware.example.jsf</groupId>
    <artifactId>mavenproject1</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mavenproject1</name>
    <url>http://maven.apache.org</url>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <!-- Execute an ant task within maven -->
                                <echo message="Hello World from pom.xml"/>
                                <!-- Execute an ant task in an external build.xml file. It assumes the file is called 
                                build.xml and is located in the same directory as the pom.xml file. The target in
                                the external file is called default.
                                -->
                                <ant target="default"/>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
Enhanced by Zemanta

Wednesday, February 24, 2010

How to contribute to the Maven books

A friend of mine from the JUG community wrote a really neat article which explains (in depth I might add) on how to contribute to the Maven community by updating and fixing issues in the Maven books. A link to his article is listed below.

How to contribute to the Maven books

Sunday, February 14, 2010

Introduction to Apache Maven Presentation

This is an Introduction to Apache Maven presentation that I gave at the Greenville Java Users Group on the 11th of February.

It covers the basics of installing and configuring Apache Maven. It also demonstrates creating three projects from relatively simple to a more complex Apache MyFaces and Facelets example. I also demonstrate the power of using the Jetty plugin to deploy and test our application. Finally I create a project site which contains information gathered from the pom.xml and project files including any unit testing.

Here is a video presentation of the tutorial. The video is approximately 42 minutes long.




Here is the actual presentation.

Monday, January 18, 2010

Apache Commons Configuration Example

The other night at the Greenville Java Users Group meeting I asked the members of the JUG to join an open source project and make a difference. I told them that you do not need to necessarily contribute code, but providing documentation assistance would make a difference.

In the same meeting I asked how many people could tell me about any of the Apache Commons projects. I was surprised at how many people could only list a couple. No one had heard of the Apache Commons Configuration project. I use the project to load properties into some of my projects. I was surprised that so many people "roll their own" around properties files.

I decided to make an Apache Maven project which demonstrates the power and simplicity of the framework.

Here is the sample code: apache-commons-configuration-example.zip

/*
 * Copyright 2010 Blue Lotus Software, LLC.
 * Copyright 2010 John Yeary <jyeary@bluelotussoftware.com>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
/*
 * $Id: Application.java 168 2010-01-19 03:09:36Z jyeary $
 */
package com.bluelotussoftware.example.apache.commons;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * <p>Example application to demonstrate the Apache Commons
 * Configuration framework.</p>
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @version 1.0-SNAPSHOT
 */
public class Application {

    private static final String PROPERTIES_FILE_NAME = "configuration.properties";

    /**
     * <p>Default no-arg constructor.</p>
     */
    public Application() {
    }

    /**
     * <p>Main application entry point.</p>
     * @param args
     * @throws ConfigurationException
     */
    public static void main(String[] args) throws ConfigurationException {
        Application application = new Application();
        application.createProperties();
        application.setBackground("#c53478");
        String background = application.getBackground();
        System.out.println("background-color:" + background);
    }

    /**
     * <p>Creates a property file on the local system disk.</p>
     * @throws ConfigurationException if an <code>Exception</code> is encountered.
     */
    public void createProperties() throws ConfigurationException {
        // Create a new property and save it.
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.save(PROPERTIES_FILE_NAME);
    }

    /**
     * <p>Sets a property called <code>colors.background</code> to the value provided, or assigns a color
     * value{@literal #000000} if none is provided .</p>
     * @param backgroundColor
     * @throws ConfigurationException if an <code>Exception</code> is encountered. 
     */
    public void setBackground(String backgroundColor) throws ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.load(PROPERTIES_FILE_NAME);
        if (backgroundColor == null) {
            config.setProperty("colors.background", "#000000");
        } else {
            config.setProperty("colors.background", backgroundColor);
        }
        config.save(PROPERTIES_FILE_NAME);
    }

    /**
     * <p>Retrieves the background property from the properties file on
     * the system disk.</p>
     * @return the background color assigned in the properties file.
     * @throws ConfigurationException if an <code>Exception</code> is encountered.
     */
    public String getBackground() throws ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration();
        config.load(PROPERTIES_FILE_NAME);
        String background = (String) config.getProperty("colors.background");
        return background;
    }
}

Popular Posts