Properties properties = AppConfigurationManager.getInstance().getProperties(ObjectContainer.class);
I have this code that populates properties.
i want to decorate this for validation for one field.
public class PropertiesDecorator extends Properties{
public void ValidateFooservHost(){
for(Entry<Object, Object> element : this.entrySet()){
if(element.getKey().toString().equals("ffxserv_host")){
String newHostValue = ffxServHostCheck(element.getValue().toString());
put(element.getKey(), newHostValue);
}
}
}
@Override
public Object setProperty(String name, String value) {
if(name.equals("foo")){
value = fooHostCheck(value);
}
return put(name, value);
}
public String fooHostCheck(String valueFromConfig){
String firstTwoChars = valueFromConfig.substring(0, 2);
if(firstTwoChars.equals("1:")){
return valueFromConfig.substring(2, valueFromConfig.length());
}
return valueFromConfig;
}
}
However,
PropertiesDecorator properties = (PropertiesDecorator) AppConfigurationManager.getInstance().getProperties(ObjectContainer.class);
this fails. I dont have a informative description but it just says it failed. not sure. what.
What am i doing wrong here? also?
How can i fix this?
Or would u recommend something differnt?
Should i use Strategy pattern? pass Properties to the PropertiesDecorator, and make the validation there ?
EDIT: I have seen that I m getting class cast exception.
Thanks.
You are getting a ClassCastException because the third party code is returning an instance of Properties, and not an instance of your PropertiesDecorator. A simple solution would be to have your PropertiesDecorator accept a Properties object, and have it merge all of its properties into yours. That is if you want your PropertiesDecorator to have an "is a" relationship with Properties.
Otherwise, you could just have a PropertiesAdapter using the Adapter pattern that delegates to an underlying Properties instance and does your validation. For completeness, below is a very basic adapter class for Properties. Add validation code and additional delegate mthods where necessary.
public class PropertiesAdapter{
private Properties props;
public PropertiesAdapter(){
this.props = new Properties();
}
public PropertiesAdapter(Properties props){
this.props = props;
}
public Object set(String name, String value){
return this.props.setProperty(name, value);
}
public String get(String name){
return this.props.getProperty(name);
}
}