Automated Database Update Or Rollback
Here I’m taking mysql database as an example we can have same conventions for other databases also
Convention to manage rollback/updates of a release
- Each project codebase at it’s root will have a folder database_scripts
- The database_scripts folder will contain folder for each release i.e Release1_1, Release2_0…
- The database scripts release folder will in turn contains two folders update & rollback which will contain updates & rollbacks scripts for a release.
Automating the rollback/update
- The update folder will have a source input file FileSequencer.txt. This file will point to all the update scripts in correct order that needs to be executed for the release
- In the similar manner rollback folder will have a source input file FileSequencer.txt. This file will point to all the rollback scripts in correct order that needs to be executed for the release
- At last we will have a utility shell script, this script will take db details and execute all the scripts referred in FileSequencer.txt using mysql command
Release Strategy for Java Web based projects
A project can be primarily released in two ways
ย ย ย Incremental Release
ย ย ย Full Release
Incremental Release is done in big projects which has multiple modules & usually few modules gets updated between two releases. It makes sense to include only updated modules in release archive and during deployment only update those modules in application server.
Full release is usually done in small projects where the release archive contains all the components and then this release archive can be deployed to the application server as a whole
Both incremental & full release strategy has their pros & cons, where full release strategy scores in simple release archive generation & deployment incremental release has upper hand in space usage by only having modified components in it, although it brings overhead when doing rollback.
Release Steps in Incremental Release Strategy: If you are following incremental strategy in general you need to perform following steps
1.) Checkout the latest code for the release
2.) Generate the list of components which needs to be deloyed for the release
3.) Generate the release archive based on the list of components
4.) Stop the server(If hot deployment of components is not available)
5.) Take the backup of existing application on application server as we may need to do rollback in case of any issues
6.) Replace the components in application server with the components in the release archive
7.) Start the server(If hot deployment of components is not available)
Release steps in Full Release Strategy: As explained earlier Full release strategy is fairly simple, steps involved are:
1.) Checkout the latest code for the release
3.) Generate the release archive for whole application
4.) Stop the server(If hot deployment of components is not available)
6.) Deploy the release archive to the application server
7.) Start the server(If hot deployment of components is not available)
Git : How to fix issues in a merged branch
First solution is to fix the issue in issue branch and merge the issue branch again with master. This solution can work but the problem with this approach is that till the time you haven’t fixed the issue introduced due to issue branch and merged it back with master branch you can not create a new issue-branch and much bigger problem is you can’t release.
The second solution is if we can somehow revert the merge of issue branch with main branch and then fix the issue in issue-branch, after that merging the fixed issue branch with the main branch. This approach seems to be straight forward and more logical. Git comes up with a cool command git-revert which can revert existing commits and even revert merge of another branch. I’ll talk about the solution in the next blog ๐
My experience with Git
Few days ago I came to know about git, so to give it a try I created an account on github. To those who doesn’t know much about it GIT is a fast version control system :). Since I’m using windows I’ve to download a git client, so the first google result that came on typing “git window” was “msysgit”. Msysgit comes with 2 options “gitbash” a command line utility and git ui so you can use any of them, for initial learning perspective I preferred GitBash.
I’ll not explain the concepts of git as there is lot of information available on the net
http://en.wikipedia.org/wiki/Git
http://git-scm.com/
So first I’ve to create a remote repository. GitHub provides online project hosting using git, they have different plans as according to your needs. I’ve created a free account so I can create public repostiories, which means anybody can checkout the code and you can allow people to modify the code. If you want to create private repository then you have to create a paid account, they have multiple plans as per your need https://github.com/plans. So my user at github is sandy724.
In next blog I will discuss how I’ve used GitBash for synching up the code with remote repository
Equals implementation for Lazy loaded objects in Hibernate
Most of you already know about the standard way to implement equals and hashCode for a class. As an example lets consider a User class
public class User {
private Long id;
private String name;
private String address;
}
If we consider Id as unique identifier for logical equality of users then the equals and hashCode method can be written over “id”, as given below
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
Now lets assume User is an entity thats managed by hibernate and is lazily loaded. So actually you will be interacting with the proxy(HibernateProxy) of User and not the actual User class.
Now in this the equals implementation of User class will fail. If we check for equality of normal instance of User class with the proxy instance of User the equals method will return false. The reason for failure is the class check i.e
if (getClass() != obj.getClass())
return false;
Since the class of Proxy user object is not User but a HibernateProxy class.
To overcome this problem hibernate comes with a utility class HibernateProxyHelper which is used to get the actual class if the object passed to it is of type HibernateProzy. The above piece of code can be replaced with
if ( HibernateProxyHelper.getClassWithoutInitializingProxy(obj) != getClass() ) {
return false;
}
Another problem with the implementation of equals in case of proxy objects is we cannot directly access the fields i.e
if (!id.equals(other.id))
return false;
as proxy objects can access only the methods of the underlying object so instead of directly accessing the field we have to use the getter method
if (!id.equals(other.getId()))
return false;
So the updated equals implemention that should work perfectly fine in case of proxy objects also will be as given below
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if ( HibernateProxyHelper.getClassWithoutInitializingProxy(obj) != getClass() ) {
return false;
}
User other = (User) obj;
if (id == null) {
if (other.getId() != null)
return false;
} else if (!id.equals(other.getId()))
return false;
return true;
}
XStream Int parsing issue
This blog is about issue in parsing int data from an xml.
While working with XStream I experienced a problem, if the xml comprises an int data beginning from 0 XStream was throwing an Exception ConversionException. On digging deeper I patterned out that the converter(IntConverter) used to convert the string value into corresponding integer value was causing problem. If the string had 0 as prefix then that string is treated as an octal value and it try to decode it as an octal value. That’s why when a value such as 089 is processed by this converter, the converter processed that value as an octal and tried to decode it and since 8 & 9 are not in octal base that’s why converter was throwing this exception. To get the better of this problem you can either have the numeric values in xml without following 0s or you can write your own converter.
Template design pattern in action part1
So finally I got time to complete the blog ๐
I’ll discuss about how we can solve the problem using templating design pattern. So what we have done, we have written a Template class “CacheTemplate” having a method getCachedData.
getCachedData takes 2 parameters
key: Key for which we have data cached
cacheCallback: If we don’t have data cached then we will call this cacheCallback to get the data and store it into cache.
public class CacheTemplate {
private CacheProvider cacheProvider;
public T getCachedData(String key,
CacheCallback cacheCallback) {
T data = (T) cacheProvider.get(key);
if (data == null) {
data = cacheCallback.cacheOperation();
cacheProvider.put(key, data);
}
return data;
}
}
Now taking forward the example taken in previos blog, let us apply this template to the “getPersons” method
public List getPersons() {
return cacheTemplate.getCachedData("persons", new CacheCallback>() {
@Override
public List cacheOperation() {
_getPersons();
}
}
}
private List _getPersons() {
persons = //Business logic to get persons;
return persons;
}
Now if you compare the current implementation with the previous implementation and check the concerns we had they all are resolved.
1.) Now our business logic of retrieving the persons is at one place.
2.) Now we have a generic implementation of managing cache.
Property file reader
In my current project we have some property files and we need to read properties from those property files, so we come up with an approach to read property files. The main points that we need to focus was
1.) The properties should be loaded only once, In a way we need singleton behavior
2.) We can have multiple property files
One assumption that we have is property files will always be located in root class path
Now for the solution of this problem we thought of using Enum (effective java ;)) as they internally provide the feature of singleton behavior, also for multiple property file situation we created multiple instances corresponding property file.
So the code that we have written is like this
public enum PropertiesReader {
SEARCH("search.properties"),APP("app.properties");
Properties properties;
private Logger log = LoggerFactory.getLogger(PropertiesReader.class);
private PropertiesReader(String propertyFile) {
properties = new Properties();
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propertyFile);
properties.load(inputStream);
}
catch (IOException e) {
log.error(propertyFile + " was not found in classpath");
}
}
public String getValue(String key) {
return (String) properties.get(key);
}
}
So now
if we want to read a property from search.properties file
assertThat(PropertiesReader.SEARCH.getValue(“max.pages.to.display”)
if we want to read a property from app.properties file
assertThat(PropertiesReader.APP.getValue(“debug_mode”)
JSR-303
JSR-303
The main idea behind JSR-303 is to have a common approach for validation at all places of the application in a simplistic way. The bean validation is built keeping in mind the validation process as a kind of meta information for a bean, so if you say that a property of bean should be not null or the content of a bean property should match to the format of e-mail or telephone. Such kind of information can be treated as meta-information of bean properties. One of the other motive for having JSR-303 into picture is to remove the boilerplate code introduced due to the need of bean validation at multiple places in the application, such as at UI level, while persisting a bean or performing some business operation.
JSR-303 provides bean validation using two ways, either you can configure validations using annotations on properties or using a XML validation descriptor. Annotations can be used as Meta-data for bean validation in case of some simple validations such as not null, e-mail, telephone number check. XML validation descriptor is used for some complex validations or context aware validation.
JSR-303 also defines API for Java Bean validation, so this API can be used to programmatically validate the bean .