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.IOException;
020import java.net.ConnectException;
021import java.net.MalformedURLException;
022import java.net.URL;
023
024import javax.jms.JMSException;
025
026import org.apache.activemq.command.ActiveMQBlobMessage;
027import org.apache.commons.net.ftp.FTPClient;
028
029public class FTPStrategy {
030
031    protected BlobTransferPolicy transferPolicy;
032    protected URL url;
033    protected String ftpUser = "";
034    protected String ftpPass = "";
035
036    public FTPStrategy(BlobTransferPolicy transferPolicy) throws MalformedURLException {
037        this.transferPolicy = transferPolicy;
038        this.url = new URL(this.transferPolicy.getUploadUrl());
039    }
040    
041    protected void setUserInformation(String userInfo) {
042        if(userInfo != null) {
043            String[] userPass = userInfo.split(":");
044            if(userPass.length > 0) this.ftpUser = userPass[0];
045            if(userPass.length > 1) this.ftpPass = userPass[1];
046        } else {
047            this.ftpUser = "anonymous";
048            this.ftpPass = "anonymous";
049        }
050    }
051    
052    protected FTPClient createFTP() throws IOException, JMSException {
053        String connectUrl = url.getHost();
054        setUserInformation(url.getUserInfo());
055        int port = url.getPort() < 1 ? 21 : url.getPort();
056        
057        FTPClient ftp = new FTPClient();
058        try {
059            ftp.connect(connectUrl, port);
060        } catch(ConnectException e) {
061            throw new JMSException("Problem connecting the FTP-server");
062        }
063        if(!ftp.login(ftpUser, ftpPass)) {
064            ftp.quit();
065            ftp.disconnect();
066            throw new JMSException("Cant Authentificate to FTP-Server");
067        }
068        return ftp;
069    }
070    
071}