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.FilterInputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.net.MalformedURLException;
023
024import javax.jms.JMSException;
025
026import org.apache.activemq.command.ActiveMQBlobMessage;
027import org.apache.commons.net.ftp.FTPClient;
028
029/**
030 * A FTP implementation for {@link BlobDownloadStrategy}.
031 */
032public class FTPBlobDownloadStrategy extends FTPStrategy implements BlobDownloadStrategy {
033
034    public FTPBlobDownloadStrategy(BlobTransferPolicy transferPolicy) throws MalformedURLException {
035        super(transferPolicy);
036    }
037
038    public InputStream getInputStream(ActiveMQBlobMessage message) throws IOException, JMSException {
039        url = message.getURL();
040        final FTPClient ftp = createFTP();
041        String path = url.getPath();
042        String workingDir = path.substring(0, path.lastIndexOf("/"));
043        String file = path.substring(path.lastIndexOf("/") + 1);
044        ftp.changeWorkingDirectory(workingDir);
045        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
046
047        InputStream input = new FilterInputStream(ftp.retrieveFileStream(file)) {
048
049            public void close() throws IOException {
050                in.close();
051                ftp.quit();
052                ftp.disconnect();
053            }
054        };
055
056        return input;
057    }
058
059    public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException {
060        url = message.getURL();
061        final FTPClient ftp = createFTP();
062
063        String path = url.getPath();
064        try {
065            if (!ftp.deleteFile(path)) {
066                throw new JMSException("Delete file failed: " + ftp.getReplyString());
067            }
068        } finally {
069            ftp.quit();
070            ftp.disconnect();
071        }
072
073    }
074
075}