View Javadoc

1   /*
2    * $Id: MapLookup.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transformer.simple;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.config.i18n.MessageFactory;
15  import org.mule.transformer.AbstractTransformer;
16  import org.mule.transformer.types.DataTypeFactory;
17  
18  import java.util.Map;
19  
20  /**
21   * <code>MapLookup</code> looks up and returns an object from a Map based on a key.
22   */
23  
24  public class MapLookup extends AbstractTransformer
25  {
26  
27      protected volatile Object key;
28  
29      public MapLookup()
30      {
31          registerSourceType(DataTypeFactory.create(Map.class));
32          setReturnDataType(DataTypeFactory.OBJECT);
33      }
34  
35      @Override
36      public Object doTransform(Object src, String encoding) throws TransformerException
37      {
38          if (src instanceof Map)
39          {
40              if (key != null)
41              {
42                  return ((Map) src).get(key);
43              }
44              else
45              {
46                  throw new TransformerException(MessageFactory
47                          .createStaticMessage("Property 'key' must be set in order to use this transformer."));
48              }
49          }
50          else
51          {
52              throw new TransformerException(MessageFactory
53                      .createStaticMessage("Message to transform must be of type java.util.Map"));
54          }
55      }
56  
57      public Object getKey()
58      {
59          return key;
60      }
61  
62      public void setKey(Object key)
63      {
64          this.key = key;
65      }
66  
67  }