1 10 11 package org.mule.providers.file; 12 13 import java.io.File ; 14 15 import org.apache.commons.lang.ObjectUtils; 16 import org.mule.MuleException; 17 import org.mule.config.i18n.Message; 18 import org.mule.config.i18n.Messages; 19 import org.mule.providers.AbstractMessageAdapter; 20 import org.mule.providers.file.transformers.FileToByteArray; 21 import org.mule.umo.MessagingException; 22 import org.mule.umo.provider.MessageTypeNotSupportedException; 23 24 30 public class FileMessageAdapter extends AbstractMessageAdapter 31 { 32 35 private static final long serialVersionUID = 4127485947547548996L; 36 37 private static final FileToByteArray transformer = new FileToByteArray(); 38 39 private File file = null; 40 private byte[] contents = null; 41 42 public FileMessageAdapter(Object message) throws MessagingException 43 { 44 super(); 45 46 if (message instanceof File ) 47 { 48 this.setMessage((File )message); 49 } 50 else 51 { 52 throw new MessageTypeNotSupportedException(message, this.getClass()); 53 } 54 } 55 56 61 public Object getPayload() 62 { 63 return file; 64 } 65 66 71 public byte[] getPayloadAsBytes() throws Exception 72 { 73 synchronized (this) 74 { 75 if (contents == null) 76 { 77 try 78 { 79 this.contents = (byte[])transformer.transform(file); 83 } 84 catch (Exception noPayloadException) 85 { 86 throw new MuleException(new Message(Messages.FAILED_TO_READ_PAYLOAD), noPayloadException); 87 } 88 } 89 return contents; 90 } 91 } 92 93 101 public String getPayloadAsString(String encoding) throws Exception 102 { 103 synchronized (this) 104 { 105 return new String (this.getPayloadAsBytes(), encoding); 106 } 107 } 108 109 114 protected void setMessage(File message) throws MessagingException 115 { 116 boolean fileIsValid; 117 Exception fileInvalidException; 118 119 try 120 { 121 fileIsValid = (message != null && message.isFile()); 122 fileInvalidException = null; 123 } 124 catch (Exception ex) 125 { 126 fileInvalidException = ex; 128 fileIsValid = false; 129 } 130 131 if (!fileIsValid) 132 { 133 Object exceptionArg; 134 135 if (fileInvalidException != null) 136 { 137 exceptionArg = fileInvalidException; 138 } 139 else 140 { 141 exceptionArg = ObjectUtils.toString(message, "null"); 142 } 143 144 Message msg = new Message(Messages.FILE_X_DOES_NOT_EXIST, ObjectUtils.toString(message, "null")); 145 146 throw new MessagingException(msg, exceptionArg); 147 } 148 149 this.file = message; 150 this.contents = null; 151 this.setProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, this.file.getName()); 152 this.setProperty(FileConnector.PROPERTY_DIRECTORY, this.file.getParent()); 153 } 154 155 public String getUniqueId() 156 { 157 return file.getAbsolutePath(); 158 } 159 160 } 161 | Popular Tags |