Showing posts with label pattern. Show all posts
Showing posts with label pattern. Show all posts

Wednesday, July 25, 2012

Spring Profile pattern , part 4

Phase 3: using the pattern

As you can recall, in previous steps we defined an interface for configuration data.
Now we will use the interface in a class which needs different data per environment.

Please note that this example is the key differentiator from the example given in  the Spring blog, since now we don't need to create a class for each profile, since in this case we use the same method across profiles and only the data changes.


Step 3.1 - example for using the pattern
@Configuration
@EnableTransactionManagement
//DB connection configuration class 
//(don't tell me you're still using xml... ;-)
public class PersistenceConfig {

 @Autowired
 private SystemStrings systemStrings; //Spring will wire by active profile

 @Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactoryNg(){
  LocalContainerEntityManagerFactoryBean factoryBean
  = new LocalContainerEntityManagerFactoryBean();
  factoryBean.setDataSource( dataSource() );
  factoryBean.setPersistenceUnitName("my_pu");       
  JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){
   {
    // JPA properties
    this.setDatabase( Database.MYSQL);
this.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
    this.setShowSql(systemStrings.getShowSqlMngHibernate());//is set per environemnt..           
   
   }
  };       
  factoryBean.setJpaVendorAdapter( vendorAdapter );
  factoryBean.setJpaProperties( additionalProperties() );

  return factoryBean;
 }
//...
@Bean
 public ComboPooledDataSource dataSource(){
  ComboPooledDataSource poolDataSource = new ComboPooledDataSource();
  try {
   poolDataSource.setDriverClass( systemStrings.getDriverClassNameMngHibernate() );
  } catch (PropertyVetoException e) {
   e.printStackTrace();
  }       
                 //is set per environemnt..
  poolDataSource.setJdbcUrl(systemStrings.getJdbcUrl());
  poolDataSource.setUser( systemStrings.getDBUsername() );
  poolDataSource.setPassword( systemStrings.getDBPassword() );
  //.. more properties...       
  return poolDataSource;
 }
}

I would appreciate comments and improvements.
Enjoy!

part 1, part 2 , part 3, part 4

Spring Profile pattern , part 3

Phase 2: implementing the profile pattern
This phase utilizes the infra we built before and implements the profile pattern.



Step 2.1 - create a properties interface
Create an interface for the configuration data you have.
In our case, the interface will provide access to the four configuration data  items.
so it would look something like:

public interface SystemStrings {

String getJdbcUrl();
String getDBUsername();
String getDBPassword();
Boolean getHibernateShowSQL();
//..... 
Step 2.2 - create a class for each profile
Example for a development profile:
@Dev //Notice the dev annotation
@Component("systemStrings")
public class SystemStringsDevImpl extends AbstractSystemStrings implements SystemStrings{
      
 public SystemStringsDevImpl() throws IOException {
                //indication on the relevant properties file
  super("/properties/my_company_dev.properties");
 } 
}
Example for a production profile:
@Prouction //Notice the production annotation
@Component("systemStrings")
public class SystemStringsProductionImpl extends AbstractSystemStrings implements SystemStrings{
      
 public SystemStringsProductionImpl() throws IOException {
                //indication on the relevant properties file
  super("/properties/my_company_production.properties");
 } 
}

The two classes above are where the binding between the properties file and the related environment occur.

You've probably noticed that the classes extend an abstract class. This technique is useful so we won't need to define each getter for each Profile, this would not be manageable in the long run, and really, there is no point of doing it.

The sweet and honey lies in the next step, where the abstract class is defined.

Step 2.3 - create an abstract file which holds the entire data

public abstract class AbstractSystemStrings implements SystemStrings{

 //Variables as in configuration properties file
private String jdbcUrl;
private String dBUsername;
private String dBPassword;
private boolean hibernateShowSQL;

public AbstractSystemStrings(String activePropertiesFile) throws IOException {
  //option to override project configuration from externalFile
  loadConfigurationFromExternalFile();//optional..
                //load relevant properties
  loadProjectConfigurationPerEnvironment(activePropertiesFile);  
 }

private void loadProjectConfigurationPerEnvironment(String activePropertiesFile) throws IOException {
  Resource[] resources = new ClassPathResource[ ]  {  new ClassPathResource( activePropertiesFile ) };
  Properties props = null;
  props = PropertiesLoaderUtils.loadProperties(resources[0]);
                jdbcUrl = props.getProperty("jdbc.url");
                dBUsername = props.getProperty("db.username"); 
                dBPassword = props.getProperty("db.password");
                hibernateShowSQL = new Boolean(props.getProperty("hibernate.show_sql"));  
}

//here should come the interface getters....



part 1, part 2 , part 3, part 4, next >>

Spring Profile pattern ,part 2

Spring Profile pattern -  phase 1: infra preparation


This phase will establish the initial infra for using Spring Profile and the configuration files.

Step 1.1  - create a properties file which contains all configuration data
Assuming you have a maven style project, create a file in src/main/resources/properties for each environment, e.g:
my_company_dev.properties
my_company_test.properties
my_company_production.properties

example for my_company_dev.properties content:

jdbc.url=jdbc:mysql://localhost:3306/my_project_db
db.username=dev1
db.password=dev1
hibernate.show_sql=true

example for my_company_production.properties content:


jdbc.url=jdbc:mysql://10.26.26.26:3306/my_project_db
db.username=prod1
db.password=fdasjkladsof8aualwnlulw344uwj9l34
hibernate.show_sql=false


Step 1.2  - create an annotation for each profile
In src.main.java.com.mycompany.annotation create annotation for each Profile, e.g :

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("DEV")
public @interface Dev {
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("PRODUCTION")
public @interface Production {
}

Create an enum for each profile:
public interface MyEnums {

public enum Profile{
DEV,
TEST,
PRODUCTION
}


Step 1.3  - make sure the profile is loaded during context loading
  • Define a system variable to indicate on which environment the code is running.
    In Tomcat, go to ${tomcat.di}/conf/catalina.properties and insert a line:
    profile=DEV  (according to your environment)
  • Define a class to set the active profile
    public class ConfigurableApplicationContextInitializer implements
      ApplicationContextInitializer {
    
     @Override
     public void initialize(ConfigurableApplicationContext applicationContext) {
          
      String profile = System.getProperty("profile");
        
      if (profile==null || profile.equalsIgnoreCase(Profile.DEV.name())){
       applicationContext.getEnvironment().setActiveProfiles(Profile.DEV.name());   
      }else if(profile.equalsIgnoreCase(Profile.PRODUCTION.name())){
       applicationContext.getEnvironment().setActiveProfiles(Profile.PRODUCTION.name()); 
      }else if(profile.equalsIgnoreCase(Profile.TEST.name())){
       applicationContext.getEnvironment().setActiveProfiles(Profile.TEST.name()); 
            }
     }
    }
    
  • Make sure the class is loaded during context loading
    in the project web.xml, insert the following:
    
         contextInitializerClasses
         com.matomy.conf.ConfigurableApplicationContextInitializer
     
    


part 1, part 2 , part 3, part 4 , next >>

Spring Profile pattern , part 1

Recently we were introduced with the concept of Spring Profiles.
This concept is an easy configuration differentiator  for different deployment environments.
The straight forward use case (which was presented) was to annotate the relevant classes so Spring would load the appropriate class according to the active profile.

However, this approach might not always serve the common use case... often, the configuration keys would be the same and only the values will change per environment.

In this post, I would like to present a pattern to support loading configuration data per environment, without the need to create/maintain multiple classes for each profile (i.e. for each environment).

Throughout the post I would take the DB connection configuration as a sample, assuming we have different DB definitions (e.g. username or connection URL) for each deployment environment.

The main idea is to use one class for loading the configuration (i.e.. one class for DB connection definition) and inject into it the appropriate instance which holds the correct profile configuration data.

For convenience and clarity, the process was divided into 3 phases:

Phase 1: infra preparation
Step 1.1  - create a properties file which contains all configuration data
Step 1.2  - create an annotation for each profile
step 1.3  - make sure the profile is loaded during context loading

Phase 2: implementing the profile pattern
Step 2.1 - create a properties interface
Step 2.2 - create a class for each profile
Step 2.3 - create an abstract file which holds the entire data

Phase 3: using the pattern
Step 3.1 - example for using the pattern

next part >>

Tuesday, January 24, 2012

RESTful standard resolved! - part I

Latly I'm trying to build a web application which will be exposed in a RESTfull manner.
There are some general guideline and hints about how to define it, but no explicit standard or accepted schema structure to use.

After reading some info on the web, I think I manage to crack the pattern :-)
I would like to share the rules and structure I formed and hopefully to get some feedback about it and improve it, so please don't hesitate to leave notes and point any pain point that structure has.

The high level pattern is:
http(s)://server.com/app-name/{version}/{domain}/{rest-convention}

Where {version} is the api version this interface work with and {domain} is an area you wish to define for any technical (e.g. security - allow certain users to access that domain) or business reason (e.g. gather functionality under same prefix).

The {rest-convention} denotes the set of REST API which is available under that domain.
It has the following convention:

  • singular-resourceX/
    • URL example: order/  (order is the singular resource X)
      • GET - will return a new order
      • POST - will create a new order. values are taken from the post content body.
  • singular-resourceX/{id} 
    • URL example: order/1 (order is the singular resource X)
      • GET - will return an order with the id 1
      • DELETE - will delete an order with the id 1
      • PUT - will update an order with the id 1.  Order values to update are taken from the post content body.

  • plural-resourceX/
    • URL example: orders/
      • GET - will return all orders
  • plural-resourceX/search
    • URL example: orders/search?name=123
      • GET - will return all orders that answer search criteria (QBE, no join) -order  name equal to 123
  • plural-resourceX/searchByXXX
    • URL example: orders/searchByItems?name=ipad
      • GET - will return all orders that answer the customized query - get all orders  that associated to items with name ipad
  • singular-resourceX/{id}/pluralY
    • URL example: order/1/items/ (order is the singular resource X, items is the plural resource Y)
      • GET - will return all items that associated to order #1
  •  singular-resourceX/{id}/singular-resourceY/
    • URL example: order/1/item/
      • GET - return a new item (transient) that is associated order #1
      • POST - create a new item and associate it to order  #1. Item values are taken from the post content body.
  •  singular-resourceX/{id}/singular-resourceY/{id}/singular-resourceZ/
    • URL example: order/1/item/2/package/
      • GET - return a new package (transient) that is associated to item 2 (i.e. how to pack the item) and is associated to order #1
      • POST - create a new package and associate it to item #2 & order #1. package values are taken from the post content body.

One basically can have further nesting as long as the above convention is maintained and no plural resource is defined after another plural resource.
There are further guidelines/notes to make things clear:
- When using plural resource, the returning instances will be those of the last plural resource used.
- When using singular resource the returning instance will be the last singular resource used.
- On search, the returning instances will be those of the last plural entity used.

Hopefully your insight will help me improve this structure and overcome issues which you might came across.

In next post, after this suggested structure will be improved, I will try to give technical examples how to implement it using Spring MVC 3.1


Friday, January 20, 2012

QBE pattern

When writing an enterprise system, there is a common pattern of a user who fill in a search form and get a corresponding result based on the given search parameters.

Handling this request manually in the backend is a bit tedious since for every search parameter, the developer need to check if the user insert a value and if so, concatenate the corresponding string into the WHERE clause in the SQL.

The Query By Example (QBE) pattern is a pattern that helps deal with the mentioned task.

It is implemented by ORM frameworks (such as Hibernate) and also avlaiable as part of possible to implement utilizing the the spec in JPA 2.0 (as seen in OpenJPA project)

The QBE implementation expect the model instance (the object which is annotated with @Entity).
That instance should have the form search values in it.
Than the implementation  framework does all the SQL wiring magic and save us the tedious work.
So at the end we just return the query result.

Lets discuss a case where a user want to query the Order object.

The Order class need to be annotated with @Entity


@Entity
public class Order{
..
}

Using a Hibernate implementation :
public List findByOrderElements(Order order) {

 Session session = getSession();

//Hibernate assembles the query with the given entity to query
 Example example = Example.create(order) //create Example object given the instance to query
     .enableLike(MatchMode.ANYWHERE) //optional parameters
     .excludeZeroes()
     .ignoreCase();

//Get the query result
 List result = session.createCriteria(Order.class)
     .add(example)
     .list();
        
 return result;
}


That's it...

Important note:
  • QBE will only work on one object (won't help in case the form input has properties of other related fields, i.e.  requires join)
  • Version properties, identifiers and associations are ignored (if QBE would consider the id than it would match only one instance...)

For even more advanced stuff regarding QBE pattern, please follow my next post.