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.URL; 026 027import javax.jms.JMSException; 028 029import org.apache.activemq.command.ActiveMQBlobMessage; 030 031/** 032 * A default implementation of {@link BlobUploadStrategy} which uses the URL 033 * class to upload files or streams to a remote URL 034 */ 035public class DefaultBlobUploadStrategy extends DefaultStrategy implements BlobUploadStrategy { 036 037 public DefaultBlobUploadStrategy(BlobTransferPolicy transferPolicy) { 038 super(transferPolicy); 039 } 040 041 public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException { 042 try(FileInputStream fis = new FileInputStream(file)) { 043 return uploadStream(message, fis); 044 } 045 } 046 047 public URL uploadStream(ActiveMQBlobMessage message, InputStream fis) throws JMSException, IOException { 048 URL url = createMessageURL(message); 049 050 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 051 connection.setRequestMethod("PUT"); 052 connection.setDoOutput(true); 053 054 // use chunked mode or otherwise URLConnection loads everything into 055 // memory 056 // (chunked mode not supported before JRE 1.5) 057 connection.setChunkedStreamingMode(transferPolicy.getBufferSize()); 058 059 try(OutputStream os = connection.getOutputStream()) { 060 byte[] buf = new byte[transferPolicy.getBufferSize()]; 061 for (int c = fis.read(buf); c != -1; c = fis.read(buf)) { 062 os.write(buf, 0, c); 063 os.flush(); 064 } 065 } catch (IOException error) { 066 throw new IOException("PUT failed to: " + url, error); 067 } 068 069 if (!isSuccessfulCode(connection.getResponseCode())) { 070 throw new IOException("PUT to " + url + " was not successful: " + connection.getResponseCode() + " " 071 + connection.getResponseMessage()); 072 } 073 074 return url; 075 } 076 077 078}