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:

1MYPARAMETER1=VALUE1
2MYPARAMETER2=VALUE2
3MYPARAMETER3=VALUE3
4MYPARAMETER4_INT=123
5MYPARAMETER5_DOUBLE=123.45
6MYPARAMETER6_BOOL=true



We need the librairies commons-configuration-1.5.jar and commons-collections-3.2.jar:
01package com.huo.test.javaconfig;
02 
03import java.text.MessageFormat;
04 
05import org.apache.commons.configuration.PropertiesConfiguration;
06import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
07 
08/**
09 * Class Test for test loading configuration
10 */
11public class TestConfig  {
12 
13    public static void main(String[] args) {
14        try {
15            System.out.println(" ############################## EXECUTION "+TestConfig.class+" - START ############################## ");
16            PropertiesConfiguration docbaseConfig = new PropertiesConfiguration(MessageFormat.format("{0}/src/com/huo/test/javaconfig/myfile.properties", System.getProperty("user.dir")));
17            docbaseConfig.setListDelimiter(',');
18            docbaseConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
19            {
20                final String parameter1 = docbaseConfig.getString("MYPARAMETER1");
21                System.out.println("The value of MYPARAMETER1 is :"+parameter1);
22                final String parameter2 = docbaseConfig.getString("MYPARAMETER2", "");
23                System.out.println("The value of MYPARAMETER2 is :"+parameter2);
24                final String parameter3 = docbaseConfig.getString("MYPARAMETER3", "");
25                System.out.println("The value of MYPARAMETER3 is :"+parameter3);
26                //
27                final int parameter4 = docbaseConfig.getInt("MYPARAMETER4_INT");
28                System.out.println("The value of MYPARAMETER4_INT is :"+parameter4);
29                final double parameter5 = docbaseConfig.getDouble("MYPARAMETER5_DOUBLE");
30                System.out.println("The value of MYPARAMETER5_DOUBLE is :"+parameter5);
31                final boolean parameter6 = docbaseConfig.getBoolean("MYPARAMETER6_BOOL");
32                System.out.println("The value of MYPARAMETER6_BOOL is :"+parameter6);
33            }
34 
35        } catch (Throwable e) {
36            e.printStackTrace();
37        }finally{
38            System.out.println(" ############################## EXECUTION "+TestConfig.class+" - END ############################## ");
39        }
40    }
41}
The outputs are:
1############################## EXECUTION class com.huo.test.javaconfig.TestConfig - START ##############################
2The value of MYPARAMETER1 is :VALUE1
3The value of MYPARAMETER2 is :VALUE2
4The value of MYPARAMETER3 is :VALUE3
5The value of MYPARAMETER4_INT is :123
6The value of MYPARAMETER5_DOUBLE is :123.45
7The value of MYPARAMETER6_BOOL is :true
8 ############################## 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 :
001package com.huo.test.java.parser.scanner.test1;
002 
003import java.io.File;
004import java.io.IOException;
005import java.util.Scanner;
006 
007/**
009 *
010 */
011public class JavaFileScanner {
012 
013    /**
014     * 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.
015     *
016     * 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.
017     *
018     * 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,
019     *      Integer and other wrapper classes.
020     *
021     * @param args
022     * @throws IOException
023     */
024     public static void main(String[] args) throws IOException {
025          
026         // 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.
027          
028            // ----------------- TEST 1 : read file line by line
029            /**
030             *  My Name is Pankaj
031             *  My website is journaldev.com
032             *  Phone : 1234567890
033             */
034            String fileName = "C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test1\\source.txt";
035            // JDK 1.7
036            //Path path = Paths.get(fileName);
037            //Scanner scanner = new Scanner(path);
038            Scanner scanner = new Scanner(new File(fileName));
039            scanner.useDelimiter(System.getProperty("line.separator"));
040            while(scanner.hasNext()){
041                System.out.println("Lines: "+scanner.next());
042            }
043            scanner.close();
044            // RESULTS:
045            // Lines: My Name is Pankaj
046            // Lines: My website is journaldev.com
047            // Lines: Phone : 1234567890
048             
049             
050            // ----------------- TEST 2 : read CSV Files and parse it to object array
051            /**
052             * Pankaj,28,Male
053             * Lisa,30,Female
054             * Mike,25,Male
055             */
056            // JDK 1.7
057            // scanner = new Scanner(Paths.get("/Users/pankaj/data.csv"));
058            scanner = new Scanner(new File("C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test1\\data.csv"));
059            scanner.useDelimiter(System.getProperty("line.separator"));
060            while(scanner.hasNext()){
061                //parse line to get Emp Object
062                Employee emp = parseCSVLine(scanner.next());
063                System.out.println(emp.toString());
064            }
065            scanner.close();
066            // RESULTS:
067            //Name=Pankaj::Age=28::Gender=Male
068            //Name=Lisa::Age=30::Gender=Female
069            //Name=Mike::Age=25::Gender=Male
070             
071             
072            // ----------------- TEST 3 : read from system input
073            System.out.println("Read from system input:");
074            scanner = new Scanner(System.in);
075            System.out.println("Input first word: "+scanner.next());
076            // RESULTS:
077            //Read from system input:
078            //Pankaj Kumar
079            //Input first word: Pankaj
080        }
081         
082        private static Employee parseCSVLine(String line) {
083             Scanner scanner = new Scanner(line);
084             scanner.useDelimiter("\\s*,\\s*");
085             String name = scanner.next();
086             int age = scanner.nextInt();
087             String gender = scanner.next();
088             JavaFileScanner jfs = new JavaFileScanner();
089             return jfs.new Employee(name, age, gender);
090        }
091 
092        public class Employee{
093            private String name;
094            private int age;
095            private String gender;
096             
097            public Employee(String n, int a, String gen){
098                this.name = n;
099                this.age = a;
100                this.gender = gen;
101            }
102             
103            @Override
104            public String toString(){
105                return "Name="+this.name+"::Age="+this.age+"::Gender="+this.gender;
106            }
107        }
108 
109         
110     
111}
data.csv
1Pankaj,28,Male
2Lisa,30,Female
3Mike,25,Male            
source.txt
1My Name is Pankaj
2My website is journaldev.com
3Phone : 1234567890
Output:
1Lines: My Name is Pankaj
2Lines: My website is journaldev.com
3Lines: Phone : 1234567890
4Name=Pankaj::Age=28::Gender=Male
5Name=Lisa::Age=30::Gender=Female
6Name=Mike::Age=25::Gender=Male          
7Read from system input:


Example 2 :
01package com.huo.test.java.parser.scanner.test2;
02 
03import java.io.File;
04import java.io.IOException;
05import java.util.Scanner;
06 
07/**
08 * 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.
09 *
11 */
12public class ReadWithScanner {
13 
14    // PRIVATE
15    private final String fFilePath;
16    private final static String ENCODING = "UTF-8";
17 
18    private static void log(Object aObject) {
19        System.out.println(String.valueOf(aObject));
20    }
21 
22    private String quote(String aText) {
23        String QUOTE = "'";
24        return QUOTE + aText + QUOTE;
25    }
26 
27     
28    public static void main(String... aArgs) throws IOException {
29        ReadWithScanner parser = new ReadWithScanner("C:\\Workspaces\\TestDCTMHUO\\src\\com\\huo\\test\\java\\parser\\scanner\\test2\\test.txt");
30        parser.processLineByLine();
31        log("Done.");
32    }
33 
34    /**
35     * Constructor.
36     *
37     * @param aFileName
38     *            full name of an existing, readable file.
39     */
40    public ReadWithScanner(String aFileName) {
41        fFilePath = aFileName;
42    }
43 
44    /** Template method that calls {@link #processLine(String)}. */
45    public final void processLineByLine() throws IOException {
46        Scanner scanner =  new Scanner(new File(fFilePath), ENCODING);
47          while (scanner.hasNextLine()){
48            processLine(scanner.nextLine());
49          }     
50  }
51 
52    /**
53     * Overridable method for processing lines in different ways.
54     *
55     * <P>
56     * This simple default implementation expects simple name-value pairs,
57     * separated by an '=' sign. Examples of valid input:
58     * <tt>height = 167cm</tt> <tt>mass =  65kg</tt>
59     * <tt>disposition =  "grumpy"</tt>
60     * <tt>this is the name = this is the value</tt>
61     */
62    protected void processLine(String aLine) {
63        // use a second Scanner to parse the content of each line
64        Scanner scanner = new Scanner(aLine);
65        scanner.useDelimiter("=");
66        if (scanner.hasNext()) {
67            // assumes the line has a certain structure
68            String name = scanner.next();
69            String value = scanner.next();
70            log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()));
71        } else {
72            log("Empty or invalid line. Unable to process.");
73        }
74    }
75 
76}
test.txt
1height = 167cm
2mass =  65kg
3disposition =  "grumpy"
4this is the name = this is the value
Output:
1Name is : 'height', and Value is : '167cm'
2Name is : 'mass', and Value is : '65kg'
3Name is : 'disposition', and Value is : '"grumpy"'
4Name is : 'this is the name', and Value is : 'this is the value'
5Done.

That’s all!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post