I have a multiple property files with params like this
login-page.login-button.text
login-page.notification.wrong-password
And this values should be used in assertions like this
Assert.that(actualNotification, expectedNotificationFromProperties)
Is there better way than create multiple classes with public static final fields, which will be initialized by some property reader?
Solution without spring framework would be perfect for me
Related
In spring, we can use #value annotation to refer a property value that is defined in the property file. In this approach, the way it would be something like
To have a separate property file and define the property name and value
To list this property class path in a spring config file
Finally referring the value in a class with #value annotations as
#value("{key_name}") String abc;
Other hand , we can try simply define that property value as a constant in the class something like the below and use it in the class.
public static final String key_name = "1q2w3e";
Since we have this simple approach, why we are using #value annotation approach as defined above.
Please help me to understand in detailed about it.
Using configuration values from external sources (e.g. property files) has many advantages. Some of them:
You can change the configuration without recompiling your code.
You can have multiple instances of the same binary-code running with different configuration values.
Configuration values can not only come from property-files that are bundled with your application, but from different sources like system-properties, environment-values, a database or any other custom source.
As a general rule only use constant values for things that will never change like the value of PI.
There's a big disadvantage in using the second method. Think of a scenario where you changed the language. If you were relying on the first approach you'd have to go through each class and change the value assigned to key_name. Now, if you were using the second method you'd only have to change the value assigned to key_name in one place, and that's in the properties file which is much simpler and make things more manageable.
Are there any libraries that easily allow projections of Java beans?
I have a bean written with getters and setters as per the Javabean convention, and at runtime in different places I want to take a fully-populated bean, and create a new instance with only a subset of its properties populated from the original.
Could something like QueryDSL be used for this? Jackson has views that could be used in the context of JSON serialization, but I was looking for a Java-to-Java solution.
Dozer is a bean-mapper that will copy properties using reflection. It can be configured to include only a subset of properties if you want.
Check out Apache Commons BeanUtils
I'm developing a Scala extension to an existing Java ORM (Ebean). The goal of this project is to add as much type safety as possible to the ORM.
Instead of
Ebean.find(Product.class).fetch("name", "unit").findList()
I would finally like to be able to write something like
(objects of entity[Product] with attributes name and unit) getIt
(note that this is just a very first DSL approach).
The ORM model is already defined as
#Entity
public class {
public String name;
public String unit;
}
In order to achieve type safety at compile time for the attributes in the query, I would need to access them on e.g. a dummy object like (new Product()).name.
I think this is the best way to ensure that only such model members are used that exists on that class, but, at runtime, I need a way to recognize that this variable was accessed. Otherwise I would just call that member name and wouldn't know about this in my query.
Does anybody know a way how to achieve this? Is there a possibility to trace when a variable is accessed and to give that information, at runtime, to any other object?
I already thought about hooking into getters and setters instead of using public members in the model classes, but this would either make the query or the model very ugly. Another problem is that any additional specific methods would have to be added manually for each model.
I would be happy if anyone could suggest possible solutions. Thanks!
If you are willing to define the fields of your model objects as something like the Record Fields, what Emil suggested could work, but if you're building your solution on top of a Java ORM using custom types might be an issue. If you need to track field access I think your best bet will be runtime bytecode instrumentation using a library like CGLib or Javassist. You can pass an instrumented "dummy" object into the body of your function, then track which field was accessed in a thread local. That's how it's done in Squeryl.
You could take a gander at how the Lift folks have implemented Mapper and Records. It allows for type safe queries using companion objects (as well as using raw sql). It does require inheriting traits into your model and the fields are specified as objects and not regular vals. Might be helpfull though. You can find the source for the persistance stuff here.
I'm developing a framework in java which relies on a number of XML files with large number of parameters.
When reading the parameters from the XML file, I have to have a large if-else statement to decide what the parameters is and then call appropriate methods.
Is this normal? to have a large if-else statement?
I am thinking that there is a simple and neater way of doing this, e.g. Java XML mapping or Java Reflections? is this the answer? if so, can you please provide examples of how this is done so I don't have to rely on a large if-else statement?
Thanks!
You want to first create an interface:
public interface XMLParameterHandler {
public handle_parameter (String XMLData);
}
Next you want to create a map:
private Map<string, XMLParameterHandler> handlers;
...and initialize it with one of the relevant Map implementations:
this.handlers = new HashMap<>();
You need to implement the interface on a number of classes, one for each parameter you intend to handle. This is a good use of inner classes. Insert each of these implemented handerls into the map:
handlers.put ("Param1", new XMLParam1HandlerImpl());
handlers.put ("Param2", new XMLParam2HandlerImpl());
Then you can call the handler from the xml processing loop:
handlers.get (paramValue).handle_parameter(XmlData);
There is JAXB (http://en.wikipedia.org/wiki/Java_Architecture_for_XML_Binding) for mapping java class to xml.
But you can't map methods with it: you only can map attributes to xml file values (deserialize parameters from xml).
i recommend to use Map, that have parameter as key and xml entry as value(not whole xml)
Reflection would be one approach. Perhaps combined with a custom annotation on the target method to indicate which parameter to pass to that method. This is an advanced technique, though.
A more standard technique would be to use a map, where the key is the attribute name, and the value is an instance of an implementation of some interface you define, like AttributeHandler. The implementations then contain the code for each attribute. This involves writing a lot of little classes, but you can do them as anonymous classes to save space and keep the code inline.
a large if-else statement to decide what the parameters is and then call appropriate methods
You could instead use the Strategy design pattern, with one Strategy object per parameter, and use a map from the parameter name to the Strategy object to use. I've found this approach useful for even a moderately complicated application of XML.
It sounds to me as if you want a data-driven rule-based approach to writing your application, rather like you get in XSLT. One way of achieving this is to write it in XSLT instead of Java - XSLT, after all, was specifically designed for processing XML, while Java wasn't. If you can't do that, you could study how XSLT does it using rules and actions, and emulate this design in your Java code.
N functions with M parameters can always be implemented with a single function with M + 1 parameters.
If you need a big if then else statement to decide which method to dispatch to, then you can just add a parameter to your method and call a single method.
You shouldn't need an if-then-else statement to bind the parameter values.
If there is complex logic dependent on the particular parameter values, you might use a table driven approach. You can map various combinations of paramemter values into equivalence classes, then variouos equivalence class combinations into a row in a table with a unique id, then have a switch statement based on that unique id.
I have a series of application properties which all have different types.
The types could include, booleans, dates, timestamps, or strings.
I need to be able to provide the ability for administrative users to change these properties and have the system to remember / persist them to a file.
I am looking for a best practice way to store these application properties and be able to persist them on change and load them on start up.
Message from the future: the link is already dead.
Java has a facility built specifically for this purpose - Properties.
Here is very good article about it
https://docs.oracle.com/javase/tutorial/essential/environment/properties.html
Since you have a requirement of storing and reading various properties of different types like boolean, integers, etc. I think the java.util.prefs API is a good choice for you. It allows you to store and read various data types.
Here's the API documentation
java.util.Properties is the easiest way. A Properties object can be created from a properties file (a file containing properties in the format name=value) or even a simple XML file. You can modify the object in memory and then write it back to a properties or XML file.
If you need more flexibility in structuring the properties, you can consider designing your own XML configuration file, although it will be a bit more work to read and write. You can however use a marshalling/unmarshalling API like JAXB, XStream etc to make that task easier.
These files can easily be modified manually as well.
Assuming you are using Java, take a look at apache commons DatabaseConfiguration (http://commons.apache.org/configuration/apidocs/org/apache/commons/configuration/DatabaseConfiguration.html).
Basically, what it does is pretty simple. It scans a table that has key-value pairs and exposes that table as a java.util.Properties. You can use this to load your application properties from the database.
Once loaded, you can cache these properties in your application. Remember to invalidate this cache whenever you make changes to the application properties.
I use this code and it works quite good for me (only partial code, coding from memory..):
(This is used in conjunction with the Properties class of java, but it makes it easier to add properties and keep your property file template in sync.)
to use:
Date date = Conf.value(Prop.SOME_DATE,Date.class);
and
enum Prop {
SOME_DATE(Date.class, "2009-10-28", "Some date"){
Object parse(String value){
return new Date(value);
}};
private final Class<?> type;
private final String description;
private final Object default;
Properties(Class<?> type, String defaultValue, String desc){
this.type = type;
this.description = desc;
this.default = this.parse(defaultValue);
}
abstract Object parse(String value);
}
and
class Conf {
private static final String PROP_FILE_NAME = "some.properties";
private volatile Map<Prop,Object> store;
public void load(){
//Read from property file and use default if not given.
//I code it in a way that it will not permit null as value, so
//if default is null the user is forced to provide setting.
}
public <T> T value(Prop prop, Class<T> clazz){
return (T)this.store.get(prop);
}
public static void main(String[] args){
//code to autogenerate property file
//Something like:
//#Default : 2009-10-28 Description : Some date. Type:Date
//#SOME_DATE=2009-10-28
}
}
The class argument makes the method a little verbose, but sometimes it is irritating if you can only let java infer the type, like this:
CountDownLatch latch = Conf.value(Prop.SOME_INTEGER);
//Compilation error! Since it expects int and won't unbox.
CountDownLatch latch = Conf.value(Prop.SOME_ITEGER,Integer.class);
//Verbose, but works everytime. Of course you could get a
//ClassCastException, but you should notice that early
//in the development...
You can store them in your Database, however due to the difference in data types of your properties you'll have to store them in their String representation. You could use another column to specify maybe the data type.
That form of application parametrization is something you've used successfully at my work. That's the general idea, I hope you could arrive to your solution with this.
You can use SQLite
Firefox uses it to persist properties
Even though you should use Preferences API or Properties, here is a hack that might also work:
Create a HashMap<String, Object> and use XMLEncoder/XMLDecoder for saving/loading. Most of the standard java classes can be serialized this way as java beans. You can make a simple wrapper class for getting various properties, handling default values etc. This way you can also store nested collections which is handy sometimes. It's really easy to implement.