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 try(FileInputStream fis = new FileInputStream(file)) { 043 return uploadStream(message, fis); 044 } 045 } 046 047 @Override 048 public URL uploadStream(ActiveMQBlobMessage message, InputStream in) 049 throws JMSException, IOException { 050 051 FTPClient ftp = createFTP(); 052 try { 053 String path = url.getPath(); 054 String workingDir = path.substring(0, path.lastIndexOf("/")); 055 String filename = message.getMessageId().toString().replaceAll(":", "_"); 056 ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 057 058 String url; 059 if(!ftp.changeWorkingDirectory(workingDir)) { 060 url = this.url.toString().replaceFirst(this.url.getPath(), "")+"/"; 061 } else { 062 url = this.url.toString(); 063 } 064 065 if (!ftp.storeFile(filename, in)) { 066 throw new JMSException("FTP store failed: " + ftp.getReplyString()); 067 } 068 return new URL(url + filename); 069 } finally { 070 ftp.quit(); 071 ftp.disconnect(); 072 } 073 074 } 075 076}