View Javadoc

1   /*
2    * $Id: FileMessageDispatcher.java 7963 2007-08-21 08:53:15Z dirk.olmes $
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.providers.file;
12  
13  import org.mule.MuleException;
14  import org.mule.MuleManager;
15  import org.mule.impl.MuleMessage;
16  import org.mule.providers.AbstractMessageDispatcher;
17  import org.mule.providers.file.filters.FilenameWildcardFilter;
18  import org.mule.providers.file.i18n.FileMessages;
19  import org.mule.umo.UMOEvent;
20  import org.mule.umo.UMOException;
21  import org.mule.umo.UMOMessage;
22  import org.mule.umo.endpoint.UMOImmutableEndpoint;
23  import org.mule.util.FileUtils;
24  
25  import java.io.File;
26  import java.io.FileOutputStream;
27  import java.io.FilenameFilter;
28  import java.net.URLDecoder;
29  
30  /**
31   * <code>FileMessageDispatcher</code> is used to read/write files to the filesystem
32   */
33  public class FileMessageDispatcher extends AbstractMessageDispatcher
34  {
35      private final FileConnector connector;
36  
37      public FileMessageDispatcher(UMOImmutableEndpoint endpoint)
38      {
39          super(endpoint);
40          this.connector = (FileConnector) endpoint.getConnector();
41      }
42  
43      /*
44       * (non-Javadoc)
45       * 
46       * @see org.mule.umo.provider.UMOConnectorSession#dispatch(org.mule.umo.UMOEvent)
47       */
48      protected void doDispatch(UMOEvent event) throws Exception
49      {
50          Object data = event.getTransformedMessage();
51          // Wrap the transformed message before passing it to the filename parser
52          UMOMessage message = new MuleMessage(data, event.getMessage());
53  
54          byte[] buf;
55          if (data instanceof byte[])
56          {
57              buf = (byte[]) data;
58          }
59          else
60          {
61              buf = data.toString().getBytes(event.getEncoding());
62          }
63  
64          FileOutputStream fos = (FileOutputStream) connector.getOutputStream(event.getEndpoint(), message);
65          if (event.getMessage().getStringProperty(FileConnector.PROPERTY_FILENAME, null) == null)
66          {
67              event.getMessage().setStringProperty(FileConnector.PROPERTY_FILENAME,
68                  message.getStringProperty(FileConnector.PROPERTY_FILENAME, ""));
69          }
70          try
71          {
72              fos.write(buf);
73          }
74          finally
75          {
76              fos.close();
77          }
78      }
79      
80      /**
81       * Will attempt to do a receive from a directory, if the endpointUri resolves to
82       * a file name the file will be returned, otherwise the first file in the
83       * directory according to the filename filter configured on the connector.
84       *
85       * @param timeout this is ignored when doing a receive on this dispatcher
86       * @return a message containing file contents or null if there was notthing to
87       *         receive
88       * @throws Exception
89       */
90  
91      protected UMOMessage doReceive(long timeout) throws Exception
92      {
93          File file = FileUtils.newFile(endpoint.getEndpointURI().getAddress());
94          File result = null;
95          FilenameFilter filenameFilter = null;
96          String filter = (String) endpoint.getProperty("filter");
97          if (filter != null)
98          {
99              filter = URLDecoder.decode(filter, MuleManager.getConfiguration().getEncoding());
100             filenameFilter = new FilenameWildcardFilter(filter);
101         }
102         if (file.exists())
103         {
104             if (file.isFile())
105             {
106                 result = file;
107             }
108             else if (file.isDirectory())
109             {
110                 result = getNextFile(endpoint.getEndpointURI().getAddress(), filenameFilter);
111             }
112             if (result != null)
113             {
114                 boolean checkFileAge = connector.getCheckFileAge();
115                 if (checkFileAge)
116                 {
117                     long fileAge = connector.getFileAge();
118                     long lastMod = result.lastModified();
119                     long now = System.currentTimeMillis();
120                     long thisFileAge = now - lastMod;
121                     if (thisFileAge < fileAge)
122                     {
123                         if (logger.isDebugEnabled()) {
124                             logger.debug("The file has not aged enough yet, will return nothing for: " +
125                                          result.getCanonicalPath());
126                         }
127                         return null;
128                     }
129                 }
130 
131                 MuleMessage message = new MuleMessage(connector.getMessageAdapter(result));
132                 File destinationFile = null;
133                 if (connector.getMoveToDirectory() != null)
134                 {
135                     destinationFile = FileUtils.newFile(connector.getMoveToDirectory(), result
136                         .getName());
137                     if (!result.renameTo(destinationFile))
138                     {
139                         logger.error("Failed to move file: " + result.getAbsolutePath()
140                                      + " to " + destinationFile.getAbsolutePath());
141                     }
142                 }
143                 
144                 if (connector.isAutoDelete())
145                 {
146                     // no moveTo directory
147                     if (destinationFile == null)
148                     {
149                         // delete source
150                         if (!result.delete())
151                         {
152                             throw new MuleException(
153                                 FileMessages.failedToDeleteFile(result.getAbsolutePath()));
154                         }
155                     }
156 
157                     // nothing to do here since moveFile() should have deleted
158                     // the source file for us
159                 }
160                 
161                 return message;
162             }
163         }
164         return null;
165     }
166 
167     private File getNextFile(String dir, FilenameFilter filter) throws UMOException
168     {
169         File[] files;
170         File file = FileUtils.newFile(dir);
171         File result = null;
172         try
173         {
174             if (file.exists())
175             {
176                 if (file.isFile())
177                 {
178                     result = file;
179                 }
180                 else if (file.isDirectory())
181                 {
182                     if (filter != null)
183                     {
184                         files = file.listFiles(filter);
185                     }
186                     else
187                     {
188                         files = file.listFiles();
189                     }
190                     if (files.length > 0)
191                     {
192                         result = files[0];
193                     }
194                 }
195             }
196             return result;
197         }
198         catch (Exception e)
199         {
200             throw new MuleException(FileMessages.errorWhileListingFiles(), e);
201         }
202     }
203 
204     /*
205      * (non-Javadoc)
206      * 
207      * @see org.mule.umo.provider.UMOConnectorSession#send(org.mule.umo.UMOEvent)
208      */
209     protected UMOMessage doSend(UMOEvent event) throws Exception
210     {
211         doDispatch(event);
212         return event.getMessage();
213     }
214 
215     protected void doDispose()
216     {
217         // no op
218     }
219 
220     protected void doConnect() throws Exception
221     {
222         // no op
223     }
224 
225     protected void doDisconnect() throws Exception
226     {
227         // no op
228     }
229 
230 }