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.net.MalformedURLException; 024import java.net.URL; 025 026import javax.jms.JMSException; 027 028import org.apache.activemq.command.ActiveMQBlobMessage; 029import org.apache.commons.net.ftp.FTPClient; 030 031/** 032 * A FTP implementation of {@link BlobUploadStrategy}. 033 */ 034public class FTPBlobUploadStrategy extends FTPStrategy implements BlobUploadStrategy { 035 036 public FTPBlobUploadStrategy(BlobTransferPolicy transferPolicy) throws MalformedURLException { 037 super(transferPolicy); 038 } 039 040 @Override 041 public URL uploadFile(ActiveMQBlobMessage message, File file) throws JMSException, IOException { 042 return uploadStream(message, new FileInputStream(file)); 043 } 044 045 @Override 046 public URL uploadStream(ActiveMQBlobMessage message, InputStream in) 047 throws JMSException, IOException { 048 049 FTPClient ftp = createFTP(); 050 try { 051 String path = url.getPath(); 052 String workingDir = path.substring(0, path.lastIndexOf("/")); 053 String filename = message.getMessageId().toString().replaceAll(":", "_"); 054 ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 055 056 String url; 057 if(!ftp.changeWorkingDirectory(workingDir)) { 058 url = this.url.toString().replaceFirst(this.url.getPath(), "")+"/"; 059 } else { 060 url = this.url.toString(); 061 } 062 063 if (!ftp.storeFile(filename, in)) { 064 throw new JMSException("FTP store failed: " + ftp.getReplyString()); 065 } 066 return new URL(url + filename); 067 } finally { 068 ftp.quit(); 069 ftp.disconnect(); 070 } 071 072 } 073 074}