Powered By Blogger

Sunday, July 31, 2011

Embed youtube video in HTML

 The following code will embed a you tube video to your html page. The attributes, value and src of param with name movie and embed tags respectively holds the url to the video, which is being embedded. The last segment of the url is the video ID (which is used to identify a video). The ID in the following example is rxUm-2x-2dM. 

<object width="425" height="350">
             <param name="movie" value="http://www.youtube.com/v/rxUm-2x-2dM"/>
             <param name="wmode" value="transparent" />
             <param name="allowFullScreen" value="true" />
             <embed src="http://www.youtube.com/v/rxUm-2x-2dM"
                      type="application/x-shockwave-flash"
                      wmode="transparent" width="425" height="350"
                      allowFullScreen="true">
              </embed>
</object>

Furthermore video options such as height, width, mode, full screen can be specified, as shown in the example.  Details about video options can be found at http://code.google.com/apis/youtube/player_parameters.html.

thanks,
Shyarmal.

Wednesday, July 27, 2011

Quartz 2.0 with Spring

I was entrusted with writing a scheduler, which is to run at a fixed time daily and it was decided to use quartz for this purpose. First the task was done using spring integration classes for quartz. But unfortunately, problems arose. Quartz 2.x versions have been refactored and no longer can be used with spring integration support. Some of the classes of older versions of quartz have been made interfaces in version 2.0.

Since I couldn't find a comprehensive example of how to schedule a task using quartz 2.0, I decided to post this example, hoping it would be useful to someone.Initialization of the scheduler is done in the init() method and the actual task need to be done is written in the inner class, AdminJob.

The following code schedules a task, which will be run daily at a fixed time.
=====================================================

package com.shyarmal.admin.jobs;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AdminTask {

    private static NotificationSender notificationSender;
    private static Client client;
    private String cronExpression;
    private static final String JOB_NAME = "admin-job";
    private StdSchedulerFactory stdSchedulerFactory;
    private Scheduler scheduler;
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminTask.class);
  
    public void init() {
        try {
            LOGGER.info("initializing admin notify scheduler .... ");
            scheduler = stdSchedulerFactory.getScheduler();
            if(scheduler.checkExists(JobKey.jobKey(JOB_NAME))) {
                scheduler.deleteJob(JobKey.jobKey(JOB_NAME));
            }
            JobDetail job =  newJob(AdminJob.class).withIdentity(JOB_NAME).build();

            CronTrigger trigger = newTrigger()
                    .withIdentity("admin-notify", "priority")
                    .withSchedule(cronSchedule(cronExpression)).forJob(JOB_NAME)
                    .build();
          
            scheduler.scheduleJob(job, trigger);
            LOGGER.info("initialized admin notify scheduler .... ");
        } catch (Exception e) {
            LOGGER.warn("scheduler initialization failed .... ", e);
        }
    }
  
    public void destroy() {
        try {
            LOGGER.info("interrupting job ... ");
            scheduler.deleteJob(JobKey.jobKey(JOB_NAME));
        } catch (Exception e) {
            LOGGER.warn("couldn't interrupt job ... ", e);
        }
    }

  
    public static class AdminJob implements Job {

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
          
             List<Notification> notifications = notificationSender.create();
             if (!notifications.isEmpty()) {
                 LOGGER.info("Sending notification .... ");
                 if(!client.send(notifications.get(0))){
                     LOGGER.error("failed to send notification ... ");
                 }
             }
        }

    }

    public void setNotificationSender(NotificationSender notificationSender) {
        AdminTask.notificationSender = notificationSender;
    }

    public void setClient(Client client) {
        AdminTask.client = client;
    }

    public void setCronExpression(String cronExpression) {
        this.cronExpression = cronExpression;
    }

    public void setStdSchedulerFactory(StdSchedulerFactory stdSchedulerFactory) {
        this.stdSchedulerFactory = stdSchedulerFactory;
    }
  
}

=====================================================

What happens in init()

A scheduler is obtained from the standard sheduler factory (injected through spring) and if a job by the name, admin-job exists it will be removed. A new JobDetail is created with the job key, admin-job. Then a CronTrigger (with trigger key, admin-notify and group, priority) is created for the admin-job. The cron expression is configured. Then the job is scheduled.

What happens in destroy()

The job created is deleted here. This is not guaranteed to run since sometimes the system will not be shut down cleanly.

The inner class, AdminJob

 This is the job class used when creating the JobDetial instance. It should implement org.quartz.Job and override the method, execute(JobExecutionContext), which is called by the scheduler at the time scheduled. So the actual work to be carried out goes in here. An important thing to note is that this class has to be public and static (if not instantiation of it fails).

The reason for using an inner class rather than a separate class was to access the fields injected to the outer class (AdminTask) to be directly accessible. If not the corresponding fields will be needed to put in the JobDataMap of JobDetail and access via the JobExecutionContext instance passed to execute(JobExecutionContext). The major issue here is the contents of JobDataMap need to be serializable. 


The spring configuration of AdminTask and quartz standard scheduler factory are as follows. The cron expression can be configured through a properties file. When making the scheduler factory I have passed the property, org.quartz.jobStore.class to be org.quartz.simpl.RAMJobStore. This is to make my triggers run in the memory (RAM), so that they'll be destroyed when the system is turned off.
=====================================================

    <bean id="adminTask" class="com.shyarmal.admin.jobs.AdminTask"
        init-method="init"
        destroy-method="destroy"
        p:client-ref="client"
        p:notificationSender-ref="notificationSender"
        p:cronExpression="${prop.admin.task.cron.expr}"
        p:stdSchedulerFactory-ref="stdSchedulerFactory"/>

      
    <bean id="stdSchedulerFactory" class="org.quartz.impl.StdSchedulerFactory">
        <constructor-arg type="java.util.Properties" ref="quartzProperties"/>
    </bean>
  
    <util:properties id="quartzProperties">
        <prop key="org.quartz.jobStore.class">${prop.org.quartz.jobStore.class}</prop>
    </util:properties>

=====================================================
properties used in the properties file
=====================================================

prop.admin.task.cron.expr = 0 15 10 * * ? *
prop.org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

thanks,
Shyarmal.

Saturday, July 23, 2011

TestNg DataProvider Example

Data providers are used to feed data to a test method, often when a method is to be tested against different scenarios (or data sets), which are expected to give the same result.
This is an illustration of a data provider.

================================================================

@Test(dataProvider = "incorrect-data",
                   expectedExceptions = {InvalidInputException.class}, enabled = true)
public void testCreateWithIncorrectData(Byte bt, byte[] data) {
          timeStamp.create(bt.byteValue(), data);
}

@DataProvider(name = "incorrect-data")
public Object[][] incorrectData() {
          return new Object[][]{
                {new Byte((byte)1), new byte[]{(byte)0xF3, 0, -127, 100, 120, 0, 0}},
                {new Byte((byte)1), new byte[]{(byte)0xF1, 0, -127, 5, 0, 0, 0}},
                {new Byte((byte)3), new byte[]{(byte)0xF1, 0, -127, 5, 0, 0, 0}},
                {new Byte((byte)3) ,new byte[]{(byte)0xF3, 0, 60, 100, 120, 0, 0}}
        };
}

================================================================

The example above tests a creation of time stamps for incorrect data. The data provider (annotated with @DataProvider) provides data to the test method (annotated with @Test).

Annotations;

  • @Test: Methods annotated with this will be considered as a test method. The attribute dataProvider configures the data provider to the test case, expectedExceptions is to specify the exceptions expected to be thrown and enable is used to make the test method enabled or disabled.
  • @DataProvider: Methods annotated with this are data providers. A data provider should have a name which is given as the 'name' attribute in order to be used by a test method.

The method incorrectData() returns a two-dimensional object array of size, 4. Each of the four arrays has two elements, which are arguments to the test method (testCreateWithIncorrectData(Byte, byte[])). Data types of the elements of each secondary array should exactly match the parameters of the test method. Since there are four sets of data, the test method will be executed four times, in one run of the test case. All four runs of the method should throw InvalidInputException exception if the test case is to pass.

thanks,
Shyarmal.

Wednesday, July 20, 2011

Spring e-mail example

This is an illustration of how e-mails can be sent using spring framework.

Below is the class written to send e-mails. It's fields, mailSender and emailSubject are injected through spring (The spring configurations can be found at the end of the post). MailSender referred to here is an instance of org.springframework.mail.javamail.JavaMailSenderImpl, the class used to send e-mails in Spring.
In the method send of EmailClient an instance of SimpleMailMessage is created and required attributes such as recipient, sender, e-mail body content, subject and optional parameters like cc, bcc are set. MailSender class's 'send' method is used to send the email.

=========================================================
package com.shyarmal.messaging;

import com.shyarmal.messaging.domain.EmailMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class EmailClient {

    private MailSender mailSender;
    private String emailSubject;
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailClient.class);

    public void send(EmailMessage message) {
        try {
            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("email message [{}]", message);
            }
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(emailSubject);
            mailMessage.setText(message.getText());
            mailMessage.setFrom(message.getFrom());
            mailMessage.setTo(message.getTo());
            if(message.getCc() != null && !message.getCc().isEmpty()) {
                mailMessage.setCc(message.getCc());
            }
            mailSender.send(mailMessage);
            LOGGER.info("email was sent to {} successfully.", message.getTo());
        } catch(Exception e) {
            LOGGER.error(String.format("Message sending failed for [%s]", message), e);
        }
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setEmailSubject(String emailSubject) {
        this.emailSubject = emailSubject;
    }
   
}

=========================================================

The following class is merely a bean, which is used to hold the parameters of the message. It's feilds are self-explanatory.
=========================================================


package com.shyarmal.messaging.domain;


public class EmailMessage {

    private String to;
    private String from;
    private String text;
    private String cc;
    private String correlationId;

    public EmailMessage(String to, String from, String text) {
        this.to = to;
        this.from = from;
        this.text = text;
    }
   
    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    @Override
    public String toString() {
        return String.format("message: to[%s], from[%s], text[%s]",
                to, from, text);
    }

}

=========================================================

EmailClient can be used as follows.
=========================================================
String emailText = "This is my email body";
EmailMessage eMessage = new EmailMessage("abc@gmail.com", "xyz@gmail.com", emailText);
emailClient.send(eMessage) ; // suppose emailClient is an instance of EmailClient

=========================================================

Required properties of the mailSender are set through Spring as follows. The properties are obtained from a file, mailing.properties. It's contents are further down in the post.
=========================================================

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
    p:host="${mail.sender.host}"
    p:port="${mail.sender.port}"
    p:username="${mail.sender.username}"
    p:password="${mail.sender.password}"
    p:protocol="${mail.sender.protocol}"
    p:javaMailProperties-ref="mailProperties"/>

<bean id="emailClient" class="com.shyarmal.messaging.EmailClient"
    p:mailSender-ref="mailSender"
    p:emailSubject="${email.subject}"/>

<util:properties id="mailProperties">
        <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
        <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
        <prop key="mail.smtp.quitwait">${mail.smtp.quitwait}</prop>
</util:properties>

<context:property-placeholder location="classpath:mailing.properties"/>
=========================================================

mailing.properties contents 
=========================================================
email.subject = my email subject
mail.sender.host = smtp.gmail.com
mail.sender.port = 587
mail.sender.username =xxxxxxxx@xxxx.xxx
mail.sender.password = xxxxxx@xxxxx
mail.sender.protocol = smtp
mail.smtp.auth = true
mail.smtp.starttls.enable = true
mail.smtp.quitwait = false

thanks,
Shyarmal.

Tuesday, July 19, 2011

TestNg example with jMock and reflection

   In this example, we'll see how to use reflection and jMock to unit test the code. Further the  following source uses a scheduler to execute a continuously task in a fixed interval.

   I have posted the source class below which is done using the spring framework. It's init method is to be called at the start up, which intern calls the execute method. The initial delay and the interval of the scheduler is obtained from another module and I do not want to mock the implementations of that. My objective is to directly test the private method (execute) in my test case.

==================================================================

package xxx.xxx.xxxxxxxx;

import xxx.xxxxxx.xxxx.xxxx.Message;
import xxx.xxx.xxxxxxxx.xxxxx.CurrentStatus;
import xxx.xxx.xxxxxxxx.xxxx.xxxxx.MessageRepository;
import xxx.xxx.xxxx.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static xxx.xxxxxx.xxxxx.RSR.sConfig;
import static xxx.xxxxxx.xxx.KKB.gDDK;
import static xxx.xxxxxx.xxx.KKB.DIK;


public class MessageScheduler {

    private int interval;
    private int initialDelay;
    private Service serviceEndpoint;
    private ScheduledExecutorService executorService;
    private MessageRepository messageRepository;
   
    private static final String RECORD_ID = "_XX";

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageScheduler.class);

    public void init() {
        LOGGER.info("starting scheduler ....... ");
        interval = ((Long) sConfig().find(gDIK)).intValue();
        initialDelay = ((Long) sConfig().find(gDDK)).intValue();
        executeScheduler();
        LOGGER.info("started scheduler ....... ");
    }

    private void executeScheduler() {
        try {
            executorService.scheduleAtFixedRate(new Runnable() {

                @Override
                public void run() {
                    List<Map<String, Object>> messages = messageRepository.find(CurrentStatus.ALLOWED);
                    if(LOGGER.isDebugEnabled()) {
                        LOGGER.debug("number of messages to be sent: {}", messages.size());
                    }
                    for(Map<String, Object> msg : messages) {
                        Message message = new Message();
                        Object id = msg.remove(RECORD_ID);
                        message.putAll((Map) msg);
                        serviceEndpoint.sendService(message, null);
                        msg.put(RECORD_ID, id);
                        messageRepository.update(msg, CurrentStatus.SENT);
                    }
                }
            }, initialDelay, interval, TimeUnit.MINUTES);
        } catch(Exception e) {
            LOGGER.error("Message sending failed ... ", e);
        }
    }

    public void stop() {
        executorService.shutdown();
    }

    public void setExecutorService(ScheduledExecutorService executorService) {
        this.executorService = executorService;
    }

    public void setMessageRepository(
            MessageRepository messageRepository) {
        this.messageRepository =messageRepository;
    }

    public void setServiceEndpoint(Service serviceEndpoint) {
        this.serviceEndpoint = serviceEndpoint;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public void setInitialDelay(int initialDelay) {
        this.initialDelay = initialDelay;
    }
   
}


======================================================================================================================================

In the test case I have mocked the Service and MessageRepository classes. Why should we mock such classes? It's because we shouldn't be testing the implementation of dependent classes in a test case, which is intended to test a particular class. In other words, a failure in one or more of the dependent classes shouldn't result a failure in the test case.

To walk through the TestNg annotations used here;
  • @BeforeMethod: Runs before each test method. (configuration needed for the tests can be done here)
  • @Test: Test methods. Methods annotated with this will be considered as a test method.
  • @AfterMethod: Runs after each test method. (normally used to release any resource used for testing)
Mockery of the jMock framework is the class used to mock (or fake) classes in the test case. Expectations are defined for the testing. Expectations are the expected method invocations and the results (in case the methods return something) of the classes, which are mocked.

Below is the TestNg test class for MessageScheduler. The explanations of jMock and reflection usages will follow.
==================================================================

package xxx.xxx.xxxxxxxx;

import xxx.xxxxxx.xxxx.xxxx.Message;
import xxx.xxx.xxxxxxxx.xxxxx.CurrentStatus;
import xxx.xxx.xxxxxxxx.xxxx.xxxxx.MessageRepository;
import xxx.xxx.xxxx.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.concurrent.DeterministicScheduler;
import org.jmock.lib.legacy.ClassImposteriser;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


@ContextConfiguration(locations={"classpath : xxxx-xxxx.xml"})
public class GovernanceMessageSchedularTest {

    private MessageScheduler messageScheduler;
    private Mockery mockery;
    private MongoTemplate template;
    private DeterministicScheduler scheduler;
   
    @BeforeMethod
    public void setUp() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("xxxx-xxxx.xml");
        messageScheduler = (MessageScheduler) ac.getBean("messageScheduler");
        template = (MongoTemplate) ac.getBean("template");
        mockery = new Mockery() {
            {
                setImposteriser(ClassImposteriser.INSTANCE);
            }
        };
        final Service service = mockery.mock(Service.class);
        final MessageRepository messageRepository = mockery.mock(MessageRepository.class);
        scheduler = new DeterministicScheduler();
        Expectations expectations = new Expectations() {
            {
                exactly(2).of(service).sendService(with(any(Message.class)), with(aNull(HttpServletRequest.class)));
                oneOf(messageRepository).find(CurrentStatus.ALLOWED);
will(returnValue(getDummyList()));
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("_id", null);
                exactly(2).of(messageRepository).update(map, CurrentStatus.SENT);
            }

        };
        messageScheduler.setServiceEndpoint(service);
        messageScheduler.setMessageRepository(messageRepository);
        messageScheduler.setExecutorService(scheduler);
        messageScheduler.setInterval(1);
        mockery.checking(expectations);
    }
   
    @Test
    public void testSchedular() throws SecurityException, NoSuchMethodException,
                            IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
       
        Class<?> gms = MessageScheduler.getClass();
        Method executeSchedulerMethod =  gms.getDeclaredMethod("executeScheduler", new Class[]{});
        executeSchedulerMethod.setAccessible(true);
        executeSchedulerMethod.invoke(messageScheduler, new Object[]{});
        scheduler.tick(500, TimeUnit.MILLISECONDS);
        mockery.assertIsSatisfied();
    }
   
    private List<Map<String, Object>> getDummyList() {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        list.add(new HashMap<String, Object>());
        list.add(new HashMap<String, Object>());
        return list;
    }
   
    @AfterMethod
    public void tearDown() {
        messageScheduler = null;
    }
}
==================================================================

jMock usage break down

1. First step is to create an instance of Mockery;
mockery = new Mockery() {            {
                setImposteriser(ClassImposteriser.INSTANCE);
            }
        };
Here Imposteriser is set to ClassImposteriser in an initialization  block to enable mocking of classes. If not only interfaces will be mocked.

2. Required classes are mocked (initialized using mockery) next.

final Service servicem = mockery.mock(Service.class);
final MessageRepository messageRepository = mockery.mock(MessageRepository.class);

3. Then define expectations for the mockery. Expectations consists of method invocations and/or faked results of the mocked classes. The mocked methods are invoked inside the source class and will produce the results we fake.

Expectations expectations = new Expectations() {            {
                exactly(2).of(service).sendService(with(any(Message.class)), with(aNull(HttpServletRequest.class)));
                oneOf(messageRepository).find(CurrentStatus.ALLOWED);will(returnValue(getDummyList()));
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("_id", null);
                exactly(2).of(messageRepository).update(map, CurrentStatus.SENT);
            }

        };

In the above expectations we expect exactly 2 invocations of the method sendService of Service. The method will be passed any Message object and a null value as parameters.

exactly(2).of(service).sendService(with(any(Message.class)), with(aNull(HttpServletRequest.class)));

Further it contains an invocation of the method find with a parameter, ALLOWED of CurrentStatus, an enum. This invocation is expected only once and to return a list.

oneOf(messageRepository).find(CurrentStatus.ALLOWED);
will(returnValue(getDummyList()));

It also expects an invocation of update on messageRepository exactly twice with a given map and SENT of CurrentStatus as arguments.

4. Mocked methods are set to the instance with is being tested.

messageScheduler.setServiceEndpoint(service);
messageScheduler.setMessageRepository(messageRepository);

5. Then expectations are set to the mockery.


mockery.checking(expectations);

6. In the test case it can be tested if all the expectations  met. If not an assertion error will be thrown (test failure).

mockery.assertIsSatisfied();

7. The source class uses a ScheduledExecutorService. So all the invocations in the expectations will be done in separate threads. So the assertion will be failed, if this happens. jMock provides a DeterministicScheduler which implements the ScheduledExecutorService. We can use it to evade this problem.

scheduler = new DeterministicScheduler();
messageScheduler.setExecutorService(scheduler);


Further the schedulers interval is set in the set-up method to 1 minute.

we are able to move the time back and forth in the deterministic scheduler.
scheduler.tick(500, TimeUnit.MILLISECONDS);

So as per the test case when the scheduler passes 500 milliseconds, all the expectations of the mockery are expected to be satisfied.

Reflection usage break down

1. Get the class of the source.
Class<?> gms = MessageScheduler.getClass();

2. Get the private method declared as follows.
        Method executeSchedulerMethod = gms.getDeclaredMethod("executeScheduler", new Class[]{});

Here the method name is 'executeScheduler'. we pass an empty Class array since it does not take any arguments.

3. Make that method accessible.
        executeSchedulerMethod.setAccessible(true);

4. Invoke the method on the actual object (testing instance).
        executeSchedulerMethod.invoke(messageScheduler, new Object[]{});
Here an empty object array is passed as the second argument since the method does not take any arguments.

This way the private method on the source class can be accessed.


thanks,
Shyarmal.

Saturday, July 9, 2011

Injecting enums to a map - spring

      Assume an enum class MyEnum is to be used as keys of a java.util.Map and injected in the spring configuration file. This can be done as follows;

package src.shyarmal.eg;

public enum MyEnum {
          A, B, C, D
}

The above enum can be injected to a Map in spring;

<util:map id="myMap" key-type="src.shyarmal.eg.MyEnum">
      <entry key="A" value="value a" />
      <entry key="B" value="value b" />
      <entry key="C" value="value c" />
      <entry key="D" value="value d" />

</util:map>

This map can be injected to a class.

package src.shyarmal.eg;

public class MyClass {

     private Map<MyEnum, String> myMap;

     public void doIt() {
          //do something  ....  
    }
  
    public void setMyMap(Map<MyEnum, String> myMap) {
         this.myMap = myMap;    
   }
}

Spring configuration of MyClass.

<bean id="myClass" class="src.shyarmal.eg.MyClass">
     <property name="myMap" ref="myMap">
</bean>


thanks,
Shyarmal