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 */
017 package org.apache.activemq.blob;
018
019 import java.io.File;
020 import java.io.FileInputStream;
021 import java.io.IOException;
022 import java.io.InputStream;
023 import java.io.OutputStream;
024 import java.net.HttpURLConnection;
025 import java.net.MalformedURLException;
026 import java.net.URL;
027
028 import javax.jms.JMSException;
029
030 import 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 */
036 public 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 return uploadStream(message, new FileInputStream(file));
044 }
045
046 public URL uploadStream(ActiveMQBlobMessage message, InputStream fis) throws JMSException, IOException {
047 URL url = createMessageURL(message);
048
049 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
050 connection.setRequestMethod("PUT");
051 connection.setDoOutput(true);
052
053 // use chunked mode or otherwise URLConnection loads everything into
054 // memory
055 // (chunked mode not supported before JRE 1.5)
056 connection.setChunkedStreamingMode(transferPolicy.getBufferSize());
057
058 OutputStream os = connection.getOutputStream();
059
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 os.close();
066 fis.close();
067
068 if (!isSuccessfulCode(connection.getResponseCode())) {
069 throw new IOException("PUT was not successful: " + connection.getResponseCode() + " "
070 + connection.getResponseMessage());
071 }
072
073 return url;
074 }
075
076
077 }