Static IP address under Ubuntu 11.10

Monday, April 30, 2012 Posted by Suresh Payankannur 0 comments
Ubuntu 11.10 has changed the network startup process. The old way of configuring network settings in /etc/network/interfaces and /etc/resolv.conf do not work anymore. The new startup will rewrite the /etc/resolve.conf by erasing your name servers. Making no connectivity to outside world.

Looks like there are no other directives or configurations which instruct the new startup not to modify the /etc/resolv.conf. So the choice is to either use the new configuration or uninstall the Network Manager and use the old style configurations.

Using Network Manager Applet

Settings->Network->Your-Network-Connection->Configure->IPV4 Settings will bring up the following dialog. The static IP address and the rest of the configuration parameters can be specified here, including the gateway and DNS server.


Or manually modify the new Network Manager configuration file instead of using the GUI

The Network Manager saves the configuration in the file /etc/NetworkManager/system-connections directory. Open th the file using sudo permissions to edit it.



As you can see the [ipv4] section has the information provided in the GUI.

Uninstall Network Manager and use old style configuration

sudo apt-get remove network-manager network-manager-gnome
Change the /etc/resolv.conf to add the nameserver.
nameserver 192.168.72.2
Change the /etc/network/interfaces to add the static IP configuration
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.72.131
netmask 255.255.255.0
gateway 192.168.72.2
Then Restart the networking.
Labels: ,

Tracing runtime execution flow with Spring

Tuesday, April 17, 2012 Posted by Suresh Payankannur 1 comments
Spring has some little known built-in interceptor classes which can come in handy to enable method tracing at runtime. This will be useful to understand the system behavior if something goes wrong and one want to turn on tracing the flow of execution, even though there are not enough debug/trace information present in the code.

org.springframework.aop.interceptor package has some pre-built classes which can be easily configured to enable tracing and timing of method executions using AOP instrumentation.

  1. SimpleTraceInterceptor: Will do method level tracing.
  2. DebugInterceptor: Will provide the same information as SimpleTraceInterceptor with additional count indicating the number of times the method has been called.
  3. PerformanceMonitorInterceptor: Logs the method execution timings.
There are few other built in interceptors for Jamon based performance monitoring, throttling the number of concurrent calls to the method etc. These interceptors are very simple, but can come in handy in several situations. I would explain how to configure such an interceptor in a Spring setup.

Spring Configuration


  
  
    

    

  

  
    
  

  
    
  

  


useDyamicLogger will log the trace/debug meesages under the logger defined for the intercepted method. For example, with useDyanmicLogger=true, the logs will be under the logger com.mycompany.service.MyService. Otherwise, the log will be under org.springframework.aop.DebugInterceptor.

Another point to note is that if the interception needs to be done for actual classes (as opposed to interfaces), then CGLIB libraries should be in the classpath as explained in http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop-api.html#aop-pfb-proxy-types
Labels: , ,

Dynamic logging with Log4j & JMX

Posted by Suresh Payankannur 2 comments
Log4j is one of the widely used libraries in the java world. Unfortunately it is not very easy to configure dynamic logging with Log4j. If one wants to enable debugging without restarting the server, there are a couple of crude options:

  1. Use the configureAndWatch API to enable the Configurator class to watch for the changes to log4j configuration file. This API takes a time interval parameter. A separate thread is spawn to check any changes to the Log4j property file at this configured interval. If the log4j file has been changed, the configuration will be re-loaded. In this approach, to enable/disable logging, change the log4j configuration file.

    If you are using Spring Framework, there is a wrappter classes to make this easier. org.springframework.util.Log4jConfigurer and org.springframework.web.util.Log4jConfigListener can be used to enable the log4j watch dog for different environments.

    The downside of this approach is that the thread created to watch over the log4j configuration file will not get terminated even after the LogManager is shutdown. In short, even after the application is shutdown in a J2EE environment, the watch dog thread will keep running.

  2. Use the JMX support provided within the Log4j. There are two classes org.apache.log4j.jmx.LoggerDynamicMBean and org.apache.log4j.HierarchyDynamicMBean exposes Log4j over JMX. But the support is very rudimentary. It requires writing further wrappers to get the most out of these classes. For example, one still needs to write wrappers to add new loggers which are not defined in the startup configuration.
None of these approaches are really good. So having a customized solution is still a better choice. One simple approach would be to write a simple MXBean to expose key aspects of the Log4j over JMX. In a typical scenario, one would want to turn logging on or off for certain loggers at runtime. To support this, a simple wrapper class can be very easily implemented.

A management bean interface

public interface Log4jConfiguratorMXBean {
    /**
     * list of all the logger names and their levels
     */
    List<String> getLoggers();

    /**
     * Get the log level for a given logger
     */
    String getLogLevel(String logger);

    /**
     * Set the log level for a given logger
     */
    void setLogLevel(String logger, String level);
}



Implementation

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class Log4jConfigurator implements Log4jConfiguratorMXBean {
    public List<String> getLoggers() {
        List<String> list = new ArrayList<String>();
        for (Enumeration e = LogManager.getCurrentLoggers();
             e.hasMoreElements(); ) {

            Logger log = (Logger) e.nextElement();
            if (log.getLevel() != null) {
                list.add(log.getName() + " = " + log.getLevel().toString());
            }
        }
        return list;
    }

    public String getLogLevel(String logger) {
        String level = "unavailable";

        if (StringUtils.isNotBlank(logger)) {
            Logger log = Logger.getLogger(logger);

            if (log != null) {
                level = log.getLevel().toString();
            }
        }
        return level;
    }
    public void setLogLevel(String logger, String level) {
        if (StringUtils.isNotBlank(logger)  &&  StringUtils.isNotBlank(level)) {
            Logger log = Logger.getLogger(logger);

            if (log != null) {
                log.setLevel(Level.toLevel(level.toUpperCase()));
            }
        }
    }

}


Register with MBean Server using Spring

  
    
  

  
    
      
        
      
    
  

  

Now hooking up the server to JConsole or VisualVM will expose the log4j attributes and operations. If one wants to add a new logger simply use the operations tab to add a new logger and set the appropriate log level. For example, to turn on hibernate SQL logging, set the logger name to org.hibernate.SQL and level to DEBUG.
Labels: ,

GNU Emacs and Subversion 1.7

Posted by Suresh Payankannur 0 comments
My favorite emacs mode for Subversion has been psvn. It provides decent integration with SVN from GNU emacs and served me well over the years. After a break, recently I started using SVN for a new project and found that SVN 1.7 do not keep a .svn directory at each level. This is a good thing. But it broke the original psvn mode. The psvn mode expects to have the .svn directory to work. After reading this blog, I switched over to dsvn. But I found that dsvn do not have the same features as psvn. And some of the important features are missing. For example:

  • Marking all the changed files in the status buffer. In psvn ** will mark all the changed files. But when using dsvn, one has to go and manually mark each individual file
  • In the commit buffer, there is no list of files that will be included in the commit. In psvn, the commit buffer will show all the files that will be included in the commit with a comment (##) in the beginning of each line. But in dsvn, the commit buffer do not show any file list, one can only enter the comment for the commit.
After searching around, I found this link on how to fix psvn to work with SVN 1.7. Use the new psvn.new.el and it seems to fix the issue.

I am using GNU Emacs 23.1 and Cygwin distribution of SVN 1.7.2 on Windows 7

References

  1. http://benjisimon.blogspot.com/2011/10/gotcha-of-day-emacs-svn-support-breaks.html
  2. http://www.emacswiki.org/emacs/SubVersion
  3. http://www.eaflux.com/
  4. http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/emacs/dsvn.el

Labels: ,

MySQL and Spring Transactional Tests

Tuesday, April 10, 2012 Posted by Suresh Payankannur 0 comments
For years, I have been using the Transaction support provided by the Spring test framework to write transaction aware unit tests. In the early days, it was by extending AbstractTransactionalSpringContextTests, which was replaced later with the introduction of Test Contexts. Now a days, just by annotating the class with TransactionConfiguration will trigger the transaction listeners to manage the class level or method level transactions. Where @Transaction annotation is used either at the class or method level.

Recently I was doing a new project using JPA, Hibernate, Spring and MySQL and building a generic unit test framework for it. The standard way I have been configuring MySQL with Hibernate was by using org.hibernate.dialect.MySQLDialect. But this was giving strange problems when running transactional unit test cases. The @Rollback(true) annotation was not working at all. At the end of the tests case, what ever database changes are made, they were committed to the database, as if the Rollback annotation do not have any effect at all. I was creating the schema, including tables using Hibernate's schema script creation APIs.

After searching for a solution, finally I found that in the later versions of Hibernate, there are additional dialects for MySQL. There are two more dialects added, MySQLInnoDBDialect and MySQL5InnoDBDialect. So the old usage with org.hibernate.dialect.MySQLDialect will create ISAM tables, which are not transactional. When the dialect was switched to one of InnoDB dialects, the CREATE TABLE scripts emit additional ENGINE=InnoDB clause to the DDLs. And the transactions were rolled back properly at the end of the test case.

Spring Configuration


  

    
    
    
    
    
    
    
    
  

  
    

    
      
        TestModel
      
    

    
      
        ${testdb.hibernate.dialect}
      
    
  

  
    
  

Property File

jdbc.testdb.username     = user
jdbc.testdb.password     = pass
jdbc.testdb.url          = jdbc:mysql://localhost/testdb
jdbc.testdb.driver       = com.mysql.jdbc.Driver
testdb.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

Test Class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-config.xml"})
@TransactionConfiguration(transactionManager="txManager", defaultRollback=false)
public class DaoTest {

    @Before
    @BeforeTransaction
    public void setup() {
        dbCreator.createSchema();
    }

    @Test
    @Transactional
    @Rollback(true)
    public void testSave() {
        TestModel model = createNewModel();

        dao.save(model);
    }

Labels: , ,

Maven and Test Config directory

Posted by Suresh Payankannur 0 comments
As per Maven, the main configuration files are picked up from the standard, default directory src/main/config. But there is no corresponding directory for the test configurations. For example, property files, spring xml configurations etc. that are needed for only unit testing.

This necessitates these directories to be configured in the pom.xml


...

    
      
        
        true
        ${basedir}/src/test/config
        
          **/*.properties
          **/*.xml
        
      
      
        /resources
        ${basedir}/src/test/resources
        
          **/*
        
      
    
...  

Labels:

Spring & Hibernate 4

Posted by Suresh Payankannur 0 comments
Recently I was trying to use Hibernate, JPA annotations and Spring Framework for a new project and trying to use H4 support in the org.springframework.orm.hibernate4 package. A couple of issues caused me some grief:

  • LocalSessionFactoryBean do not have any way to set a LobHandler as were in the previous hibernate3 version. Then I came across this comment from Juergen as part of https://jira.springsource.org/browse/SPR-9022

    We generally rely on the native Hibernate 4 ways of doing things more than before (with Hibernate 3).

    So for LOB access, we recommend native Hibernate types (e.g. org.hibernate.type.MaterializedClobType) instead of the former user types that came with Spring's Hibernate 3 support. With Hibernate 4 and modern JDBC drivers (e.g. Oracle 10g or even a JDBC 4 driver), you should not need Spring's LobHandler mechanism at all anymore.

    In short, please try to replace your Spring user types with native Hibernate CLOB types. See the Hibernate documentation for details on their support for CLOB access.

    Good info. I still need to test the data access code to ensure that the LOBs are correctly handled.

  • I have been setting up the Unit test cases to create/drop database schema using the create/drop DatabaseSchema APIs of the LocalSessionFactoryBean. But in H4, these APIs are removed. Need to find a new way to get this done, may be going directly using the Hibernate APIs. But it makes it a little inconvenient and requires extra framework to handle this in a generic way
Labels: ,