Code

Convert Properties File To java.util.Map

A sample piece of code used to load the data in a properties file in a java.util.Map

package com.davidking.principles;

import org.junit.Test;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;

/**
 * DynamicMethodInvocationTest
 * User: David King, enterprise.saas@gmail.com
 * Date: 5/12/13
 * Time: 7:28 PM
 */
public class DynamicMethodInvocationTest {
    private Logger log = Logger.getLogger(DynamicMethodInvocationTest.class.getName());


    @Test
    public void testBuildMethodMappings() {
        String methodToInvoke = getMethodToInvoke("get_user");
        assertEquals("GetUserById", methodToInvoke);
        log.log(Level.INFO, "Method to invoke is - {0}", methodToInvoke);
    }

    private String getMethodToInvoke(String requestMethodName) {
        Properties properties = new Properties();
        try {
            properties.load(DynamicMethodInvocationTest.class.getClassLoader().getResourceAsStream("com/davidking/principles/methodNameMappings.properties"));
        } catch (IOException e) {
            log.info(e.toString());
        }

        log.log(Level.INFO, "properties loaded with this data - {0} ", properties);

        Map<String, Object> mappings = new ConcurrentHashMap<String, Object>();

        Enumeration elements = properties.propertyNames();
        while(elements.hasMoreElements()) {
            String keyProps = (String)elements.nextElement();
            String valProps = properties.getProperty(keyProps);

            // populate the Map
            mappings.put(keyProps, valProps);
        }


        if (mappings.containsKey(requestMethodName)) {
            return mappings.get(requestMethodName).toString();
        }
        return null;
    }
}

NOTE: The property file is in a package…

The properties file contents are as follows:

# Map action names to proper method names to invoke
get_user=GetUserById
create_user=CreateUser
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s