View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.component.simple;
8   
9   import org.mule.api.MuleEventContext;
10  import org.mule.api.lifecycle.Callable;
11  import org.mule.api.lifecycle.Initialisable;
12  import org.mule.api.lifecycle.InitialisationException;
13  import org.mule.util.IOUtils;
14  
15  import java.io.IOException;
16  
17  /**
18   * A service that will return a static data object as a result. This is useful for
19   * testing with expected results. The data returned can be read from a file or set as
20   * a property on this service.
21   */
22  public class StaticComponent implements Callable, Initialisable
23  {
24  
25      private Object data;
26      private String dataFile;
27      private String prefix;
28      private String postfix;
29  
30      public void initialise() throws InitialisationException
31      {
32          if (dataFile != null)
33          {
34              try
35              {
36                  data = IOUtils.getResourceAsString(dataFile, getClass());
37              }
38              catch (IOException e)
39              {
40                  throw new InitialisationException(e, this);
41              }
42          }
43      }
44  
45      public Object getData()
46      {
47          return data;
48      }
49  
50      public void setData(Object data)
51      {
52          this.data = data;
53      }
54  
55      public String getDataFile()
56      {
57          return dataFile;
58      }
59  
60      public void setDataFile(String dataFile)
61      {
62          this.dataFile = dataFile;
63      }
64  
65      public String getPrefix()
66      {
67          return prefix;
68      }
69  
70      public void setPrefix(String prefix)
71      {
72          this.prefix = prefix;
73      }
74  
75      public String getPostfix()
76      {
77          return postfix;
78      }
79  
80      public void setPostfix(String postfix)
81      {
82          this.postfix = postfix;
83      }
84  
85      public Object onCall(MuleEventContext eventContext) throws Exception
86      {
87          if (data != null)
88          {
89              return data;
90          }
91  
92          String eventData = eventContext.transformMessageToString();
93  
94          if (prefix != null)
95          {
96              eventData = prefix + eventData;
97          }
98  
99          if (postfix != null)
100         {
101             eventData += postfix;
102         }
103 
104         return eventData;
105     }
106 }