001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.activemq.blob; 018 019import java.io.File; 020import java.io.FileInputStream; 021import java.io.IOException; 022import java.io.InputStream; 023import java.io.OutputStream; 024import java.net.HttpURLConnection; 025import java.net.MalformedURLException; 026import java.net.URL; 027 028import javax.jms.JMSException; 029 030import org.apache.activemq.command.ActiveMQBlobMessage; 031 032/** 033 * A default implementation of {@link BlobUploadStrategy} which uses the URL 034 * class to upload files or streams to a remote URL 035 */ 036public class DefaultBlobUploadStrategy extends DefaultStrategy implements BlobUploadStrategy { 037 038 public DefaultBlobUploadStrategy(BlobTransferPolicy transferPolicy) { 039 super(transferPolicy); 040 } 041 042 public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException { 043 try(FileInputStream fis = new FileInputStream(file)) { 044 return uploadStream(message, fis); 045 } 046 } 047 048 public URL uploadStream(ActiveMQBlobMessage message, InputStream fis) throws JMSException, IOException { 049 URL url = createMessageURL(message); 050 051 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 052 connection.setRequestMethod("PUT"); 053 connection.setDoOutput(true); 054 055 // use chunked mode or otherwise URLConnection loads everything into 056 // memory 057 // (chunked mode not supported before JRE 1.5) 058 connection.setChunkedStreamingMode(transferPolicy.getBufferSize()); 059 060 try(OutputStream os = connection.getOutputStream()) { 061 byte[] buf = new byte[transferPolicy.getBufferSize()]; 062 for (int c = fis.read(buf); c != -1; c = fis.read(buf)) { 063 os.write(buf, 0, c); 064 os.flush(); 065 } 066 } catch (IOException error) { 067 throw new IOException("PUT failed to: " + url, error); 068 } 069 070 if (!isSuccessfulCode(connection.getResponseCode())) { 071 throw new IOException("PUT to " + url + " was not successful: " + connection.getResponseCode() + " " 072 + connection.getResponseMessage()); 073 } 074 075 return url; 076 } 077 078 079}