1 17 package org.apache.activemq.blob; 18 19 import java.io.File ; 20 import java.io.FileInputStream ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.io.OutputStream ; 24 import java.net.HttpURLConnection ; 25 import java.net.MalformedURLException ; 26 import java.net.URL ; 27 28 import javax.jms.JMSException ; 29 30 import org.apache.activemq.command.ActiveMQBlobMessage; 31 32 36 public class DefaultBlobUploadStrategy implements BlobUploadStrategy { 37 private BlobTransferPolicy transferPolicy; 38 39 public DefaultBlobUploadStrategy(BlobTransferPolicy transferPolicy) { 40 this.transferPolicy = transferPolicy; 41 } 42 43 public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException , IOException { 44 return uploadStream(message, new FileInputStream (file)); 45 } 46 47 public URL uploadStream(ActiveMQBlobMessage message, InputStream fis) throws JMSException , IOException { 48 URL url = createUploadURL(message); 49 50 HttpURLConnection connection = (HttpURLConnection )url.openConnection(); 51 connection.setRequestMethod("PUT"); 52 connection.setDoOutput(true); 53 54 connection.setChunkedStreamingMode(transferPolicy.getBufferSize()); 57 58 OutputStream os = connection.getOutputStream(); 59 60 byte[] buf = new byte[transferPolicy.getBufferSize()]; 61 for (int c = fis.read(buf); c != -1; c = fis.read(buf)) { 62 os.write(buf, 0, c); 63 os.flush(); 64 } 65 os.close(); 66 fis.close(); 67 68 if (!isSuccessfulCode(connection.getResponseCode())) { 69 throw new IOException ("PUT was not successful: " 70 + connection.getResponseCode() + " " + connection.getResponseMessage()); 71 } 72 73 return url; 74 } 75 76 public void deleteFile(ActiveMQBlobMessage message) throws IOException , JMSException { 77 URL url = createUploadURL(message); 78 79 HttpURLConnection connection = (HttpURLConnection )url.openConnection(); 80 connection.setRequestMethod("DELETE"); 81 connection.connect(); 82 connection.disconnect(); 83 84 if (!isSuccessfulCode(connection.getResponseCode())) { 85 throw new IOException ("DELETE was not successful: " 86 + connection.getResponseCode() + " " + connection.getResponseMessage()); 87 } 88 } 89 90 private boolean isSuccessfulCode(int responseCode) { 91 return responseCode >= 200 && responseCode < 300; } 93 94 protected URL createUploadURL(ActiveMQBlobMessage message) throws JMSException , MalformedURLException { 95 return new URL (transferPolicy.getUploadUrl() + message.getMessageId().toString()); 96 } 97 } 98 | Popular Tags |