2.3.2.3. Init Parameters

You see your service has a configuration file, but you wonder how the file can gain access to its configuration. Imagine that you are asked to implement two different calculation methods: fast and exact.

You create one init parameter containing the calculation methods. For the exact method, you wish to configure more details for the service. Let's enhance the word service configuration file:


  <component>
    <key>com.laverdad.services.ArticleStatsService</key>
    <type>com.laverdad.services.ArticleStatsServiceImpl</type>
    <init-params>
      <value-param>
        <name>calc-method</name>
        <description>calculation method: fast, exact</description>
        <value>fast</value>
      </value-param>
      <properties-param>
        <name>details-for-exact-method</name>
        <description>details for exact phrase counting</description>
        <property name="language" value="English" />
        <property name="variant" value="us" />
      </properties-param>
    </init-params>
  </component>

Note

When configuring your service, you are totally free. You can provide as many value-param, property-param, and properties as you wish, and you can give them any names or values. You only must respect the xml structure.

Now let's see how our service can read this configuration. The implementation of the calcSentences() method serves just as a simple example. It's up to your imagination to implement the exact method.

public class ArticleStatsServiceImpl implements ArticleStatsService {


  private String calcMethod = "fast";
  private String variant = "French";
  private String language = "France";
  
  public ArticleStatsServiceImpl(InitParams initParams) {
    super();
    calcMethod = initParams.getValueParam("calc-method").getValue();
    PropertiesParam detailsForExactMethod = initParams.getPropertiesParam("details-for-exact-method");
    if ( detailsForExactMethod != null) {
      language = detailsForExactMethod.getProperty("language");
      variant = detailsForExactMethod.getProperty("variant");
    }
  }
  
  public int calcSentences(String article) {
    if (calcMethod == "fast") {
      // just count the number of periods "." 
      int res = 0;
      int period = article.indexOf('.');
      while (period != -1) {
        res++;
        article = article.substring(period+1);
        period = article.indexOf('.');
      }      
      return  res;
    } 
    throw new RuntimeException("Not implemented");
    }
}

You see you just have to declare a parameter of org.exoplatform.container.xml.InitParams in your constructor. The container provides an InitParams object that correspond to the xml tree of init-param.

Copyright ©2012. All rights reserved. eXo Platform SAS