views:

71

answers:

2

I often use this design in my code to maintain configurable values. Consider this code:

public enum Options {

    REGEX_STRING("Some Regex"),
    REGEX_PATTERN(Pattern.compile(REGEX_STRING.getString()), false),
    THREAD_COUNT(2),
    OPTIONS_PATH("options.config", false),
    DEBUG(true),
    ALWAYS_SAVE_OPTIONS(true),
    THREAD_WAIT_MILLIS(1000);

    Object value;
    boolean saveValue = true;

    private Options(Object value) {
        this.value = value;
    }

    private Options(Object value, boolean saveValue) {
        this.value = value;
        this.saveValue = saveValue;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public String getString() {
        return value.toString();
    }

    public boolean getBoolean() {
        Boolean booleanValue = (value instanceof Boolean) ? (Boolean) value : null;
        if (value == null) {
            try {
                booleanValue = Boolean.valueOf(value.toString());
            }
            catch (Throwable t) {
            }
        }

        // We want a NullPointerException here
        return booleanValue.booleanValue();
    }

    public int getInteger() {
        Integer integerValue = (value instanceof Number) ? ((Number) value).intValue() : null;
        if (integerValue == null) {
            try {
                integerValue = Integer.valueOf(value.toString());
            }
            catch (Throwable t) {
            }
        }
        return integerValue.intValue();
    }

    public float getFloat() {
        Float floatValue = (value instanceof Number) ? ((Number) value).floatValue() : null;
        if (floatValue == null) {
            try {
                floatValue = Float.valueOf(value.toString());
            }
            catch (Throwable t) {
            }
        }
        return floatValue.floatValue();
    }

    public static void saveToFile(String path) throws IOException {
        FileWriter fw = new FileWriter(path);
        Properties properties = new Properties();
        for (Options option : Options.values()) {
            if (option.saveValue) {
                properties.setProperty(option.name(), option.getString());
            }
        }
        if (DEBUG.getBoolean()) {
            properties.list(System.out);
        }
        properties.store(fw, null);
    }

    public static void loadFromFile(String path) throws IOException {
        FileReader fr = new FileReader(path);
        Properties properties = new Properties();
        properties.load(fr);

        if (DEBUG.getBoolean()) {
            properties.list(System.out);
        }
        Object value = null;
        for (Options option : Options.values()) {
            if (option.saveValue) {
                Class<?> clazz = option.value.getClass();
                try {
                    if (String.class.equals(clazz)) {
                        value = properties.getProperty(option.name());
                    }
                    else {
                        value = clazz.getConstructor(String.class).newInstance(properties.getProperty(option.name()));
                    }
                }
                catch (NoSuchMethodException ex) {
                    Debug.log(ex);
                }
                catch (InstantiationException ex) {
                    Debug.log(ex);
                }
                catch (IllegalAccessException ex) {
                    Debug.log(ex);
                }
                catch (IllegalArgumentException ex) {
                    Debug.log(ex);
                }
                catch (InvocationTargetException ex) {
                    Debug.log(ex);
                }

                if (value != null) {
                    option.setValue(value);
                }
            }
        }
    }
}

This way, I can save and retrieve values from files easily. The problem is that I don't want to repeat this code everywhere. Like as we know, enums can't be extended; so wherever I use this, I have to put all these methods there. I want only to declare the values and that if they should be persisted. No method definitions each time; any ideas?

+1  A: 
polygenelubricants
Do you think extending from EnumMap and putting all my methods like getInteger and saveToFile; and providing a constructor that accepts a class instance of enum of required specific configuration identifiers (e.g Options.class) is a good idea?
Omer Akhter
@Omer: _Effective Java 2nd Edition, Item 16: Favor composition over inheritance_. I don't think extending `EnumMap` is a good idea; creating something that has an `EnumMap` field is better. Search around for the phrase "composition vs inheritance" etc for full discussion.
polygenelubricants
I was not thinking correctly, my idea would not solve the problem.But what you suggested seems to be of use in case we want multiple values for SAME config keys/identifies.What I am looking for is single set of value for each of multiple sets of config keys/identifiers each defined in different enums. For example, enum NetworkOptions, enum ParserOptions, enum FileOptions... But what I don't want is adding all these getters and saveToFile methods to be put in each of the enums separately. I want somehow to put these in one place and let every Option enum use it.
Omer Akhter
A: 

i tried doing something similar with enum maps and properties files (please see code below). but my enums were simple and only had one value except for an embedded case. i may have something that is more type safe. i will look around for it.

package p;

import java.util.*;
import java.io.*;

public class GenericAttributes<T extends Enum<T>> {
    public GenericAttributes(final Class<T> keyType) {
        map = new EnumMap<T, Object>(this.keyType = keyType);
    }

    public GenericAttributes(final Class<T> keyType, final Properties properties) {
        this(keyType);
        addStringProperties(properties);
    }

    public Object get(final T key) {
        // what does a null value mean?
        // depends on P's semantics
        return map.containsKey(key) ? map.get(key) : null;
    }

    public boolean contains(final T key) {
        return map.containsKey(key);
    }

    public void change(final T key, final Object value) {
        remove(key);
        put(key, value);
    }

    public Object put(final T key, final Object value) {
        if (map.containsKey(key))
            throw new RuntimeException("map already contains: " + key);
        else
            return map.put(key, value);
    }

    public Object remove(final T key) {
        if (!map.containsKey(key))
            throw new RuntimeException("map does not contain: " + key);
        return map.remove(key);
    }

    public String toString() {
        return toString(defaultEquals, defaultEndOfLine);
    }

    // maybe we don;t need this stuff
    // we have tests for it though
    // it might be useful
    public String toString(final String equals, final String endOfLine) {
        final StringBuffer sb = new StringBuffer();
        for (Map.Entry<T, Object> entry : map.entrySet())
            sb.append(entry.getKey()).append(equals).append(entry.getValue()).append(endOfLine);
        return sb.toString();
    }

    public Properties toProperties() {
        final Properties p = new Properties();
        for (Map.Entry<T, Object> entry : map.entrySet())
            p.put(entry.getKey().toString(), entry.getValue().toString());
        return p;
    }

    public void addStringProperties(final Properties properties) {
        // keep this for strings, but mostly do work in the enum class
        // i.e. static GenericAttributes<PA> fromProperties();
        // which would use a fromString()
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            final String key = (String) entry.getKey();
            final String value = (String) entry.getValue();
            addProperty(key, value);
        }
    }

    public void addProperty(final String key, final Object value) {
        try {
            final T e = Enum.valueOf(keyType, key);
            map.put(e, value);
        } catch (IllegalArgumentException e) {
            System.err.println(key + " is not an enum from: " + keyType);
        }
    }

    public int size() {
        return map.size();
    }

    public static Properties load(final InputStream inputStream,final Properties defaultProperties) {
        final Properties p=defaultProperties!=null?new Properties(defaultProperties):new Properties();
        try {
            p.load(inputStream);
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
        return p;
    }
    public static Properties load(final File file,final Properties defaultProperties) {
        Properties p=null;
        try {
            final InputStream is=new FileInputStream(file);
            p=load(is,defaultProperties);
            is.close();
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
        return p;
    }
    public static void store(final OutputStream outputStream, final Properties properties) {
        try {
            properties.store(outputStream, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void store(final File file, final Properties properties) {
        try {
            final OutputStream os = new FileOutputStream(file);
            store(os, properties);
            os.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    final Class<T> keyType;
    static final String defaultEquals = "=", defaultEndOfLine = "\n";
    private final EnumMap<T, Object> map;

    public static void main(String[] args) {
    }
}

package p;
import static org.junit.Assert.*;
import org.junit.*;
import java.io.*;
import java.util.*;
enum A1 {
    foo,bar,baz;
}
enum A2 {
    x,y,z;
}
public class GenericAttributesTestCase {
    @Test public void testGenericAttributes() {
        new GenericAttributes<A1>(A1.class);
    }
    @Test public void testGenericAttributesKeyTypeProperties() {
        final Properties expected=gA1.toProperties();
        final GenericAttributes<A1> gA=new GenericAttributes<A1>(A1.class,expected);
        final Properties actual=gA.toProperties();
        assertEquals(expected,actual);
    }
    @Test public void testGet() {
        final A1 key=A1.foo;
        emptyGA1.put(key,null);
        final Object actual=emptyGA1.get(key);
        assertEquals(null,actual);
    }
    @Test public void testGetInteger() {
    // attributes.add(key,integer);
    // assertEquals(integer,attributes.get("key"));
    }
    @Test public void testContains() {
        for(A1 a:A1.values())
            assertFalse(emptyGA1.contains(a));
    }
    @Test public void testChange() {
        final A1 key=A1.foo;
        final Integer value=42;
        emptyGA1.put(key,value);
        final Integer expected=43;
        emptyGA1.change(key,expected);
        final Object actual=emptyGA1.get(key);
        assertEquals(expected,actual);
    }
    @Test public void testAdd() {
        final A1 key=A1.foo;
        final Integer expected=42;
        emptyGA1.put(key,expected);
        final Object actual=emptyGA1.get(key);
        assertEquals(expected,actual);
    }
    @Test public void testRemove() {
        final A1 key=A1.foo;
        final Integer value=42;
        emptyGA1.put(key,value);
        emptyGA1.remove(key);
        assertFalse(emptyGA1.contains(key));
    }
    @Test public void testToString() {
        final String actual=gA1.toString();
        final String expected="foo=a foo value\nbar=a bar value\n";
        assertEquals(expected,actual);
    }
    @Test public void testToStringEqualsEndOfLine() {
        final String equals=",";
        final String endOFLine=";";
        final String actual=gA1.toString(equals,endOFLine);
        final String expected="foo,a foo value;bar,a bar value;";
        assertEquals(expected,actual);
    }
    @Test public void testEmbedded() {
        final String equals=",";
        final String endOfLine=";";
        //System.out.println("toString(\""+equals+"\",\""+endOFLine+"\"):");
        final String embedded=gA1.toString(equals,endOfLine);
        GenericAttributes<A2> gA2=new GenericAttributes<A2>(A2.class);
        gA2.put(A2.x,embedded);
        //System.out.println("embedded:\n"+gA2);
        // maybe do file={name=a.jpg;dx=1;zoom=.5}??
        // no good, key must be used more than once
        // so file:a.jpg={} and hack
        // maybe file={name=...} will work
        // since we have to treat it specially anyway?
        // maybe this is better done in ss first
        // to see how it grows?
    }
    @Test public void testFromString() {
    // final Attributes a=Attributes.fromString("");
    // final String expected="";
    // assertEquals(expected,a.toString());
    }
    @Test public void testToProperties() {
        final Properties expected=new Properties();
        expected.setProperty("foo","a foo value");
        expected.setProperty("bar","a bar value");
        final Properties actual=gA1.toProperties();
        assertEquals(expected,actual);
    }
    @Test public void testAddProperties() {
        final Properties p=gA1.toProperties();
        final GenericAttributes<A1> ga=new GenericAttributes<A1>(A1.class);
        ga.addStringProperties(p);
        // assertEquals(ga1,ga); // fails since we need to define equals!
        // hack, go backwards
        final Properties p2=ga.toProperties();
        assertEquals(p,p2); // hack until we define equals
    }
    @Test public void testStore() throws Exception {
        final Properties expected=gA1.toProperties();
        final ByteArrayOutputStream baos=new ByteArrayOutputStream();
        GenericAttributes.store(baos,expected);
        baos.close();
        final byte[] bytes=baos.toByteArray();
        final ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
        final Properties actual=GenericAttributes.load(bais,null);
        bais.close();
        assertEquals(expected,actual);
    }
    @Test public void testLoad() throws Exception {
        final Properties expected=gA1.toProperties();
        final ByteArrayOutputStream baos=new ByteArrayOutputStream();
        GenericAttributes.store(baos,expected);
        baos.close();
        final ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
        final Properties actual=GenericAttributes.load(bais,null);
        bais.close();
        assertEquals(expected,actual);
    }
    @Test public void testMain() {
    // fail("Not yet implemented");
    }
    GenericAttributes<A1> gA1=new GenericAttributes<A1>(A1.class);
    {
        gA1.put(A1.foo,"a foo value");
        gA1.put(A1.bar,"a bar value");
    }
    GenericAttributes<A1> emptyGA1=new GenericAttributes<A1>(A1.class);
}

answering your comment:

seems like i am getting values by using the enum as the key. i am probably confused.

an enum can implement an interface and each set of enums could have an instance of that base class and delegate calls to it (see item 34 of http://java.sun.com/docs/books/effective/toc.html)

i found the other code that went with my generic attributes (please see below), but i can't find any tests for it and am not quite sure what i was doing other than perhaps to add some stronger typing.

my motivation for all of this was to store some attributes for a photo viewer like picasa, i wanted to store a bunch of attributes for a picture in a single line of a property file

package p;
import java.util.*;
public enum GA {
    // like properties, seems like this wants to be constructed with a set of default values
    i(Integer.class) {
        Integer fromString(final String s) {
            return new Integer(s);
        }
        Integer fromNull() {
            return zero; // return empty string?
        }
    },
    b(Boolean.class) {
        Boolean fromString(final String s) {
            return s.startsWith("t")?true:false;
        }
        Boolean fromNull() {
            return false;
        }
    },
    d(Double.class) {
        Double fromString(final String s) {
            return new Double(s);
        }
        Double fromNull() {
            return new Double(zero);
        }
    };
    GA() {
        this(String.class);
    }
    GA(final Class clazz) {
        this.clazz=clazz;
    }
    abstract Object fromString(String string);
    abstract Object fromNull();
    static GenericAttributes<GA> fromProperties(final Properties properties) {
        final GenericAttributes<GA> pas=new GenericAttributes<GA>(GA.class);
        for(Map.Entry<Object,Object> entry:properties.entrySet()) {
            final String key=(String)entry.getKey();
            final GA pa=valueOf(key);
            if(pa!=null) {
                final String stringValue=(String)entry.getValue();
                Object value=pa.fromString(stringValue);
                pas.addProperty(key,value);
            } else throw new RuntimeException(key+"is not a member of "+"GA");
        }
        return pas;
    }
    // private final Object defaultValue; // lose type?; require cast?
    /* private */final Class clazz;
    static final Integer zero=new Integer(0);
}
Ray Tayek
Problem is still there, I have to specify string constants, not identifiers, to get values. What's the difference? An identifier is checked at compile-time, a string constant will be checked at run-time.I think the one way to go around it would be to create an abstract class with all these methods and then inherit classes like FileOptions, NetworkOptions etc from it where I define static final options like FileName etc
Omer Akhter