JavaBlog.fr / Java.lu DEVELOPMENT,Java Apache : Commons Configuration

Apache : Commons Configuration

Hi,

Here, a simple java example using the Apache Commons Configuration library. The Apache Commons Configuration software library provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources.

Some resources:
https://commons.apache.org/proper/commons-configuration/
https://commons.apache.org/proper/commons-configuration/userguide/quick_start.html

A simple file properties myfile.properties:

MYPARAMETER1=VALUE1
MYPARAMETER2=VALUE2
MYPARAMETER3=VALUE3
MYPARAMETER4_INT=123
MYPARAMETER5_DOUBLE=123.45
MYPARAMETER6_BOOL=true



We need the librairies commons-configuration-1.5.jar and commons-collections-3.2.jar:
package com.huo.test.javaconfig;

import java.text.MessageFormat;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

/**
 * Class Test for test loading configuration
 */
public class TestConfig  {

	public static void main(String[] args) {
		try {
			System.out.println(" ############################## EXECUTION "+TestConfig.class+" - START ############################## ");
			PropertiesConfiguration docbaseConfig = new PropertiesConfiguration(MessageFormat.format("{0}/src/com/huo/test/javaconfig/myfile.properties", System.getProperty("user.dir")));
			docbaseConfig.setListDelimiter(',');
			docbaseConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
			{
				final String parameter1 = docbaseConfig.getString("MYPARAMETER1");
				System.out.println("The value of MYPARAMETER1 is :"+parameter1);
				final String parameter2 = docbaseConfig.getString("MYPARAMETER2", "");
				System.out.println("The value of MYPARAMETER2 is :"+parameter2);
				final String parameter3 = docbaseConfig.getString("MYPARAMETER3", "");
				System.out.println("The value of MYPARAMETER3 is :"+parameter3);
				//
				final int parameter4 = docbaseConfig.getInt("MYPARAMETER4_INT");
				System.out.println("The value of MYPARAMETER4_INT is :"+parameter4);
				final double parameter5 = docbaseConfig.getDouble("MYPARAMETER5_DOUBLE");
				System.out.println("The value of MYPARAMETER5_DOUBLE is :"+parameter5);
				final boolean parameter6 = docbaseConfig.getBoolean("MYPARAMETER6_BOOL");
				System.out.println("The value of MYPARAMETER6_BOOL is :"+parameter6);
			}

		} catch (Throwable e) {
			e.printStackTrace();
		}finally{
			System.out.println(" ############################## EXECUTION "+TestConfig.class+" - END ############################## ");
		}
	}
}
The outputs are:
 ############################## EXECUTION class com.huo.test.javaconfig.TestConfig - START ##############################
The value of MYPARAMETER1 is :VALUE1
The value of MYPARAMETER2 is :VALUE2
The value of MYPARAMETER3 is :VALUE3
The value of MYPARAMETER4_INT is :123
The value of MYPARAMETER5_DOUBLE is :123.45
The value of MYPARAMETER6_BOOL is :true
 ############################## EXECUTION class com.huo.test.javaconfig.TestConfig - END ##############################

Others solutions


An other solution without Apache would be the use of Java Scanner class (java.util.Scanner) which was introduced in Java 1.5 as a simple text scanner which can parse primitive types and strings using regular expressions.
Java Scanner class can be used to break the input into tokens with any regular expression delimiter and it’s good for parsing files also.
 Java Scanner class can be used to read file data into primitive and it types, it also extends String split() functionality to return tokens as String, int, long, Integer and other wrapper classes.
Example from Test from http://www.journaldev.com/872/java-scanner-class-java-util-scanner

Example 1 :

package com.huo.test.java.parser.scanner.test1;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Test from http://www.journaldev.com/872/java-scanner-class-java-util-scanner
 *
 */
public class JavaFileScanner {

	/**
	 * Java Scanner class (java.util.Scanner) was introduced in Java 1.5 as a simple text scanner which can parse primitive types and strings using regular expressions.
	 * 
	 * Java Scanner class can be used to break the input into tokens with any regular expression delimiter and it’s good for parsing files also.
	 * 
	 * Java Scanner class can be used to read file data into primitive and it types, it also extends String split() functionality to return tokens as String, int, long, 
	 * 		Integer and other wrapper classes.
	 * 
	 * @param args
	 * @throws IOException
	 */
	 public static void main(String[] args) throws IOException {
		 
		 // Here, using Scanner to read a file line by line, parsing a CSV file to create java object easily and read from the user input.
		 
	        // ----------------- TEST 1 : read file line by line
	        /**
	         *  My Name is Pankaj
	         *  My website is journaldev.com
	         *  Phone : 1234567890
	         */
	        String fileName = "C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test1\\source.txt";
	        // JDK 1.7 
	        //Path path = Paths.get(fileName);
	        //Scanner scanner = new Scanner(path);
	        Scanner scanner = new Scanner(new File(fileName));
	        scanner.useDelimiter(System.getProperty("line.separator"));
	        while(scanner.hasNext()){
	            System.out.println("Lines: "+scanner.next());
	        }
	        scanner.close();
	        // RESULTS:
	        // Lines: My Name is Pankaj
	        // Lines: My website is journaldev.com
	        // Lines: Phone : 1234567890
	        
	        
	        // ----------------- TEST 2 : read CSV Files and parse it to object array
	        /**
	         * Pankaj,28,Male
	         * Lisa,30,Female
	         * Mike,25,Male
	         */
	        // JDK 1.7 
	        // scanner = new Scanner(Paths.get("/Users/pankaj/data.csv"));
	        scanner = new Scanner(new File("C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test1\\data.csv"));
	        scanner.useDelimiter(System.getProperty("line.separator"));
	        while(scanner.hasNext()){
	            //parse line to get Emp Object
	            Employee emp = parseCSVLine(scanner.next());
	            System.out.println(emp.toString());
	        }
	        scanner.close();
	        // RESULTS:
	        //Name=Pankaj::Age=28::Gender=Male
	        //Name=Lisa::Age=30::Gender=Female
	        //Name=Mike::Age=25::Gender=Male
	        
	        
	        // ----------------- TEST 3 : read from system input
	        System.out.println("Read from system input:");
	        scanner = new Scanner(System.in);
	        System.out.println("Input first word: "+scanner.next());
	        // RESULTS:
	        //Read from system input:
	        //Pankaj Kumar
	        //Input first word: Pankaj
	    }
	    
	    private static Employee parseCSVLine(String line) {
	         Scanner scanner = new Scanner(line);
	         scanner.useDelimiter("\\s*,\\s*");
	         String name = scanner.next();
	         int age = scanner.nextInt();
	         String gender = scanner.next();
	         JavaFileScanner jfs = new JavaFileScanner();
	         return jfs.new Employee(name, age, gender);
	    }

	    public class Employee{
	        private String name;
	        private int age;
	        private String gender;
	        
	        public Employee(String n, int a, String gen){
	            this.name = n;
	            this.age = a;
	            this.gender = gen;
	        }
	        
	        @Override
	        public String toString(){
	            return "Name="+this.name+"::Age="+this.age+"::Gender="+this.gender;
	        }
	    }

	    
	
}

data.csv
Pankaj,28,Male
Lisa,30,Female
Mike,25,Male	         
source.txt
My Name is Pankaj
My website is journaldev.com
Phone : 1234567890
Output:
Lines: My Name is Pankaj
Lines: My website is journaldev.com
Lines: Phone : 1234567890
Name=Pankaj::Age=28::Gender=Male
Name=Lisa::Age=30::Gender=Female
Name=Mike::Age=25::Gender=Male	         
Read from system input:



Example 2 :
package com.huo.test.java.parser.scanner.test2;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * This example uses Scanner. Here, the contents of a file containing name-value pairs is read, and each line is parsed into its constituent data. 
 * 
 * http://www.javapractices.com/topic/TopicAction.do?Id=87
 */
public class ReadWithScanner {

	// PRIVATE
	private final String fFilePath;
	private final static String ENCODING = "UTF-8";

	private static void log(Object aObject) {
		System.out.println(String.valueOf(aObject));
	}

	private String quote(String aText) {
		String QUOTE = "'";
		return QUOTE + aText + QUOTE;
	}

	
	public static void main(String... aArgs) throws IOException {
		ReadWithScanner parser = new ReadWithScanner("C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test2\\test.txt");
		parser.processLineByLine();
		log("Done.");
	}

	/**
	 * Constructor.
	 * 
	 * @param aFileName
	 *            full name of an existing, readable file.
	 */
	public ReadWithScanner(String aFileName) {
		fFilePath = aFileName;
	}

	/** Template method that calls {@link #processLine(String)}. */
	public final void processLineByLine() throws IOException {
		Scanner scanner =  new Scanner(new File(fFilePath), ENCODING);
	      while (scanner.hasNextLine()){
	        processLine(scanner.nextLine());
	      }      
  }

	/**
	 * Overridable method for processing lines in different ways.
	 * 
	 * <P>
	 * This simple default implementation expects simple name-value pairs,
	 * separated by an '=' sign. Examples of valid input:
	 * <tt>height = 167cm</tt> <tt>mass =  65kg</tt>
	 * <tt>disposition =  "grumpy"</tt>
	 * <tt>this is the name = this is the value</tt>
	 */
	protected void processLine(String aLine) {
		// use a second Scanner to parse the content of each line
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter("=");
		if (scanner.hasNext()) {
			// assumes the line has a certain structure
			String name = scanner.next();
			String value = scanner.next();
			log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()));
		} else {
			log("Empty or invalid line. Unable to process.");
		}
	}

}


test.txt
height = 167cm
mass =  65kg
disposition =  "grumpy"
this is the name = this is the value
Output:
Name is : 'height', and Value is : '167cm'
Name is : 'mass', and Value is : '65kg'
Name is : 'disposition', and Value is : '"grumpy"'
Name is : 'this is the name', and Value is : 'this is the value'
Done.


That’s all!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post