View Javadoc

1   /*
2    * $Id: JXPathExpressionEvaluator.java 12273 2008-07-10 13:25:32Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.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.module.xml.expression;
12  
13  import org.mule.api.transport.MessageAdapter;
14  import org.mule.module.xml.util.XMLUtils;
15  import org.mule.util.expression.ExpressionEvaluator;
16  
17  import org.apache.commons.jxpath.JXPathContext;
18  import org.apache.commons.logging.Log;
19  import org.apache.commons.logging.LogFactory;
20  import org.dom4j.Document;
21  
22  /**
23   * Will extract properties based on Xpath expressions. Will work on Xml/Dom and beans
24   */
25  public class JXPathExpressionEvaluator implements ExpressionEvaluator
26  {
27      public static final String NAME = "jxpath";
28      /**
29       * logger used by this class
30       */
31      protected transient Log logger = LogFactory.getLog(getClass());
32  
33      public Object evaluate(String name, Object message)
34      {
35  
36          Object result = null;
37          Object payload = message;
38          if (message instanceof MessageAdapter)
39          {
40              payload = ((MessageAdapter) message).getPayload();
41          }
42  
43          Document dom4jDoc;
44          try
45          {
46              dom4jDoc = XMLUtils.toDocument(payload);
47          }
48          catch (Exception e)
49          {
50              logger.error(e);
51              return null;
52          }
53          
54          // Payload is XML
55          if (dom4jDoc != null)
56          {
57              result = dom4jDoc.valueOf(name);
58          }
59          // Payload is a Java object
60          else
61          {
62              JXPathContext context = JXPathContext.newContext(payload);
63              try
64              {
65                  result = context.getValue(name);
66              }
67              catch (Exception e)
68              {
69                  // ignore
70              }
71          }
72          return result;
73      }
74  
75      /** {@inheritDoc} */
76      public String getName()
77      {
78          return NAME;
79      }
80  
81      /** {@inheritDoc} */
82      public void setName(String name)
83      {
84          throw new UnsupportedOperationException("setName");
85      }
86  }