org.apache.ftpserver.FtpServer - java examples

Here are the examples of the java api org.apache.ftpserver.FtpServer taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

64 Examples 7

19 View Complete Implementation : FTPService.java
Copyright GNU General Public License v3.0
Author : PowerExplorer
public clreplaced FTPService extends Service implements Runnable {

    public static final int DEFAULT_PORT = 2222;

    public static final String DEFAULT_USERNAME = "";

    // default timeout, in sec
    public static final int DEFAULT_TIMEOUT = 600;

    public static final boolean DEFAULT_SECURE = false;

    public static final String PORT_PREFERENCE_KEY = "ftpPort";

    public static final String KEY_PREFERENCE_PATH = "ftp_path";

    public static final String KEY_PREFERENCE_USERNAME = "ftp_username";

    public static final String KEY_PREFERENCE_PreplacedWORD = "ftp_preplacedword_encrypted";

    public static final String KEY_PREFERENCE_TIMEOUT = "ftp_timeout";

    public static final String KEY_PREFERENCE_SECURE = "ftp_secure";

    public static final String DEFAULT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

    public static final String INITIALS_HOST_FTP = "ftp://";

    public static final String INITIALS_HOST_SFTP = "sftp://";

    private static final String TAG = FTPService.clreplaced.getSimpleName();

    private static final String WIFI_AP_ADDRESS = "192.168.1.1";

    // Service will (global) broadcast when server start/stop
    static public final String ACTION_STARTED = "net.gnu.explorer.services.ftpservice.FTPReceiver.FTPSERVER_STARTED";

    static public final String ACTION_STOPPED = "net.gnu.explorer.services.ftpservice.FTPReceiver.FTPSERVER_STOPPED";

    static public final String ACTION_FAILEDTOSTART = "net.gnu.explorer.services.ftpservice.FTPReceiver.FTPSERVER_FAILEDTOSTART";

    // RequestStartStopReceiver listens for these actions to start/stop this server
    static public final String ACTION_START_FTPSERVER = "net.gnu.explorer.services.ftpservice.FTPReceiver.ACTION_START_FTPSERVER";

    static public final String ACTION_STOP_FTPSERVER = "net.gnu.explorer.services.ftpservice.FTPReceiver.ACTION_STOP_FTPSERVER";

    private String username, preplacedword;

    private boolean isPreplacedwordProtected = false;

    private FtpServer server;

    protected static Thread serverThread = null;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int attempts = 10;
        while (serverThread != null) {
            if (attempts > 0) {
                attempts--;
                sleepIgnoreInterupt(1000);
            } else {
                return START_STICKY;
            }
        }
        serverThread = new Thread(this);
        serverThread.start();
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void run() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        FtpServerFactory serverFactory = new FtpServerFactory();
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        String usernamePreference = preferences.getString(KEY_PREFERENCE_USERNAME, DEFAULT_USERNAME);
        if (!usernamePreference.equals(DEFAULT_USERNAME)) {
            username = usernamePreference;
            try {
                preplacedword = CryptUtil.decryptPreplacedword(getApplicationContext(), preferences.getString(KEY_PREFERENCE_PreplacedWORD, ""));
                isPreplacedwordProtected = true;
            } catch (CryptException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
                // can't decrypt the preplacedword saved in preferences, remove the preference altogether
                // and start an anonymous connection instead
                preferences.edit().putString(FTPService.KEY_PREFERENCE_PreplacedWORD, "").apply();
                isPreplacedwordProtected = false;
            }
        }
        BaseUser user = new BaseUser();
        if (!isPreplacedwordProtected) {
            user.setName("anonymous");
        } else {
            user.setName(username);
            user.setPreplacedword(preplacedword);
        }
        user.setHomeDirectory(preferences.getString(KEY_PREFERENCE_PATH, DEFAULT_PATH));
        List<Authority> list = new ArrayList<>();
        list.add(new WritePermission());
        user.setAuthorities(list);
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            e.printStackTrace();
        }
        ListenerFactory fac = new ListenerFactory();
        if (preferences.getBoolean(KEY_PREFERENCE_SECURE, DEFAULT_SECURE)) {
            SslConfigurationFactory sslConfigurationFactory = new SslConfigurationFactory();
            File file;
            try {
                InputStream stream = getResources().openRawResource(R.raw.key);
                file = File.createTempFile("keystore.bks", "");
                FileOutputStream outputStream = new FileOutputStream(file);
                FileUtil.is2OS(stream, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
                file = null;
            }
            if (file != null) {
                sslConfigurationFactory.setKeystoreFile(file);
                sslConfigurationFactory.setKeystorePreplacedword("vishal007");
                fac.setSslConfiguration(sslConfigurationFactory.createSslConfiguration());
                fac.setImplicitSsl(true);
            } else {
                // no keystore found
                preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply();
            }
        }
        fac.setPort(getPort(preferences));
        fac.setIdleTimeout(preferences.getInt(KEY_PREFERENCE_TIMEOUT, DEFAULT_TIMEOUT));
        serverFactory.addListener("default", fac.createListener());
        try {
            server = serverFactory.createServer();
            server.start();
            sendBroadcast(new Intent(FTPService.ACTION_STARTED));
        } catch (Exception e) {
            sendBroadcast(new Intent(FTPService.ACTION_FAILEDTOSTART));
        }
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy() Stopping server");
        if (serverThread == null) {
            Log.w(TAG, "Stopping with null serverThread");
            return;
        }
        serverThread.interrupt();
        try {
            // wait 10 sec for server thread to finish
            serverThread.join(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (serverThread.isAlive()) {
            Log.w(TAG, "Server thread failed to exit");
        } else {
            Log.d(TAG, "serverThread join()ed ok");
            serverThread = null;
        }
        if (server != null) {
            server.stop();
            sendBroadcast(new Intent(FTPService.ACTION_STOPPED));
        }
        Log.d(TAG, "FTPServerService.onDestroy() finished");
    }

    // Restart the service if the app is closed from the recent list
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent restartService = new Intent(getApplicationContext(), this.getClreplaced());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
    }

    public static boolean isRunning() {
        // return true if and only if a server Thread is running
        if (serverThread == null) {
            Log.d(TAG, "Server is not running (null serverThread)");
            return false;
        }
        if (!serverThread.isAlive()) {
            Log.d(TAG, "serverThread non-null but !isAlive()");
        } else {
            Log.d(TAG, "Server is alive");
        }
        return true;
    }

    public static void sleepIgnoreInterupt(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException ignored) {
            ignored.printStackTrace();
        }
    }

    public static boolean isConnectedToLocalNetwork(Context context) {
        boolean connected = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        connected = ni != null && ni.isConnected() && (ni.getType() & (ConnectivityManager.TYPE_WIFI | ConnectivityManager.TYPE_ETHERNET)) != 0;
        if (!connected) {
            Log.d(TAG, "isConnectedToLocalNetwork: see if it is an USB AP");
            try {
                for (NetworkInterface netInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                    if (netInterface.getDisplayName().startsWith("rndis")) {
                        connected = true;
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return connected;
    }

    public static boolean isConnectedToWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnected() && ni.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean isEnabledWifiHotspot(Context context) {
        boolean enabled = false;
        Log.d(TAG, "isEnabledWifiHotspot: see if it is an WIFI AP");
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        try {
            Method method = wm.getClreplaced().getDeclaredMethod("isWifiApEnabled");
            enabled = (Boolean) method.invoke(wm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return enabled;
    }

    public static InetAddress getLocalInetAddress(Context context) {
        if (!isConnectedToLocalNetwork(context) && !isEnabledWifiHotspot(context)) {
            Log.e(TAG, "getLocalInetAddress called and no connection");
            return null;
        }
        if (isConnectedToWifi(context)) {
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            int ipAddress = wm.getConnectionInfo().getIpAddress();
            if (ipAddress == 0)
                return null;
            return intToInet(ipAddress);
        }
        try {
            Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces();
            while (netinterfaces.hasMoreElements()) {
                NetworkInterface netinterface = netinterfaces.nextElement();
                Enumeration<InetAddress> addresses = netinterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (isEnabledWifiHotspot(context) && WIFI_AP_ADDRESS.equals(address.getHostAddress()))
                        return address;
                    // this is the condition that sometimes gives problems
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress())
                        return address;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InetAddress intToInet(int value) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            bytes[i] = byteOfInt(value, i);
        }
        try {
            return InetAddress.getByAddress(bytes);
        } catch (UnknownHostException e) {
            // This only happens if the byte array has a bad length
            return null;
        }
    }

    public static byte byteOfInt(int value, int which) {
        int shift = which * 8;
        return (byte) (value >> shift);
    }

    public static int getPort(SharedPreferences preferences) {
        return preferences.getInt(PORT_PREFERENCE_KEY, DEFAULT_PORT);
    }

    public static boolean isPortAvailable(int port) {
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                /* should not be thrown */
                }
            }
        }
        return false;
    }
}

19 View Complete Implementation : FTPServer.java
Copyright Apache License 2.0
Author : Top-Q
/**
 * SystemObject which wraps Apache embedded FTP server.<br>
 * {@link http://incubator.apache.org/ftpserver/}<br>
 * <br>
 * <u>FTPServer implementation details</u><br>
 * The functionality of this system object includes:<br>
 * 1. Setters & getters for FTP server configuration.
 *    For example SUT please see {@linkplain ftpserver.xml}<br>
 * 2. Creation of default user. Default user name, defaultUserPreplacedword and root folder
 *    can be configured using SUT file. Otherwise default user's user name
 *    is "aqua", defaultUserPreplacedword "aqua" and root folder is current_folder/aquaftp21.<br>
 * 3. The FTPServer SystemObject checks whether
 *    the FTP server port is occupied if so, it replacedumes that another FTP server is
 *    already running; it logs a message to the reports system and continues.<br>
 *
 * <u><b>Note:</u></b> In a machine which has more then one network interface and one of the network interfaces
 *       is not available to expected client, there might be a need to replacedign explicitly the IP on which
 *       the server listens for FTP requests.
 *       In this case use the com.aqua.filetransfer.ftp.ftpserver=myip in the jsystem.properties file.<br>
 *
 * @author Golan Derazon
 */
public clreplaced FTPServer extends SystemObjectImpl {

    private FtpServer server;

    private int port = 21;

    private boolean isRunning = false;

    /**
     * This is the name of the host
     * as seen outside the sub-net.
     * Not sure is is needed here.
     */
    private String externalName;

    private String defaultUserName = "aqua";

    private String defaultUserPreplacedword = "aqua";

    private String defaultUserHomeDirectory;

    private String propertiesPath = "res/conf/ftpd.properties";

    /**
     * Initializes FTPServer object.
     */
    public void init() throws Exception {
        super.init();
        updateExternalName();
        Configuration config = getConfiguration();
        // create FTP config
        IFtpConfig ftpConfig = new FtpConfigImpl(config);
        // create the server object and start it
        server = new FtpServer(ftpConfig);
        initializeDefaultUser();
        if (isBound()) {
            report.report("Another FTP server is already active.");
        }
    }

    /**
     * Starts FTP server.<br>
     * If this server is already running, the method logs a message
     * and returns true.<br>
     * If FTP port is occupied the method replacedumes another
     * FTP server is running, it logs a message and returns false
     * otherwise starts server and returns true.
     */
    public boolean startServer() throws Exception {
        if (isRunning()) {
            report.report("FTP server already running. Ignoring startServer operation");
            return true;
        }
        if (isBound()) {
            report.report("Another FTP server is already active. Ignoring startServer operation");
            return false;
        }
        server.start();
        isRunning = true;
        return true;
    }

    /**
     * Returns true if <b>this</b> server is active
     * otherwise returns false.<br>
     */
    public boolean isRunning() throws Exception {
        return isRunning;
    }

    /**
     * Stops FTP server.
     */
    public void stopServer() throws Exception {
        server.stop();
        isRunning = false;
    }

    /**
     * Returns FTP server home directory.
     */
    public File getServerRootDirectory() throws Exception {
        return new File(server.getFtpConfig().getUserManager().getUserByName(getDefaultUserName()).getHomeDirectory());
    }

    private Configuration getConfiguration() throws Exception {
        InputStream stream = getClreplaced().getClreplacedLoader().getResourcereplacedtream(getPropertiesPath());
        if (stream == null) {
            stream = new FileInputStream(getPropertiesPath());
        }
        String bindName = getBindName();
        if (bindName != null) {
            report.report("FTP Server is listening on " + bindName + " port: " + getPort() + " ip address is " + InetAddress.getByName(bindName));
        } else {
            report.report("FTP Server is listening on all ips. port: " + getPort());
        }
        try {
            Properties props = new Properties();
            props.load(stream);
            props.setProperty("config.socket-factory.port", "" + port);
            if (bindName != null) {
                props.setProperty("config.socket-factory.address", bindName);
                props.setProperty("config.data-connection.active.local-address", bindName);
                props.setProperty("config.data-connection.preplacedive.address", bindName);
            }
            PropertiesConfiguration configuration = new PropertiesConfiguration(props);
            return configuration;
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     * Returns the IP on which the FTP server should listen.
     */
    private String getBindName() throws Exception {
        String configuredIp = JSystemProperties.getInstance().getPreference("com.aqua.filetransfer.ftp.ftpserver");
        if (configuredIp == null || "".equals(configuredIp)) {
            return null;
        } else {
            return configuredIp;
        }
    }

    private void updateExternalName() throws Exception {
        String externalName = getExternalName();
        if (externalName == null) {
            externalName = getBindName();
        }
        if (externalName == null) {
            externalName = getLocalMachineHostName();
        }
        setExternalName(externalName);
    }

    private String getLocalMachineHostName() throws Exception {
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     */
    private void initializeDefaultUser() throws Exception {
        BaseUser aquaUser = new BaseUser();
        aquaUser.setEnabled(true);
        aquaUser.setName(defaultUserName);
        aquaUser.setPreplacedword(defaultUserPreplacedword);
        aquaUser.setWritePermission(true);
        File defaultUserRoot;
        if (getDefaultUserHomeDirectory() == null) {
            defaultUserRoot = new File("aquaftp" + getPort());
        } else {
            defaultUserRoot = new File(getDefaultUserHomeDirectory());
        }
        if (!defaultUserRoot.exists() && !defaultUserRoot.mkdirs()) {
            throw new Exception("Failed creating default user root folder: " + defaultUserRoot.getAbsolutePath());
        }
        aquaUser.setHomeDirectory(defaultUserRoot.getAbsolutePath());
        setDefaultUserHomeDirectory(defaultUserRoot.getAbsolutePath());
        server.getFtpConfig().getUserManager().save(aquaUser);
    }

    /**
     * Checks whether FTP's port is already bound by other
     * process.
     */
    private boolean isBound() throws Exception {
        String addressToCheck = getBindName();
        if (addressToCheck != null) {
            return NetUtils.isBound(addressToCheck, getPort());
        } else {
            return NetUtils.isBound(getPort());
        }
    }

    /**
     * ************************************************************************
     *
     *   Setters & getters
     *
     * ************************************************************************
     */
    public String getDefaultUserPreplacedword() {
        return defaultUserPreplacedword;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getDefaultUserName() {
        return defaultUserName;
    }

    public String getExternalName() {
        return externalName;
    }

    public void setExternalName(String externalName) {
        this.externalName = externalName;
    }

    public String getDefaultUserHomeDirectory() {
        return defaultUserHomeDirectory;
    }

    public void setDefaultUserHomeDirectory(String rootFolder) {
        this.defaultUserHomeDirectory = rootFolder;
    }

    public void setDefaultUserName(String defaultUserName) {
        this.defaultUserName = defaultUserName;
    }

    public void setDefaultUserPreplacedword(String defaultUserPreplacedword) {
        this.defaultUserPreplacedword = defaultUserPreplacedword;
    }

    /**
     * ********************************************************************
     *
     * *********************************************************************
     */
    public static void main(String[] args) throws Exception {
        FTPServer server = new FTPServer();
        server.init();
        server.startServer();
        synchronized (FTPServer.clreplaced) {
            FTPServer.clreplaced.wait();
        }
        server.stopServer();
    }

    public String getPropertiesPath() {
        return propertiesPath;
    }

    public void setPropertiesPath(String propertiesPath) {
        this.propertiesPath = propertiesPath;
    }
}

19 View Complete Implementation : ConnectionsService.java
Copyright Apache License 2.0
Author : gigabytedevelopers
public clreplaced ConnectionsService extends NetworkServerService {

    private FtpServer ftpServer;

    @Override
    protected NetworkServiceHandler createServiceHandler(Looper serviceLooper, NetworkServerService service) {
        return new NetworkServiceHandler(serviceLooper, service);
    }

    @Override
    public Object getServer() {
        return ftpServer;
    }

    @Override
    public boolean launchServer() {
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(ConnectionUtils.getAvailablePortForFTP());
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.addListener("default", listenerFactory.createListener());
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(getNetworkConnection().isAnonymousLogin());
        connectionConfigFactory.setMaxLoginFailures(5);
        connectionConfigFactory.setLoginFailureDelay(2000);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        BaseUser user = new BaseUser();
        user.setName(getNetworkConnection().getUserName());
        user.setPreplacedword(getNetworkConnection().getPreplacedword());
        user.setHomeDirectory(getNetworkConnection().getPath());
        List<Authority> list = new ArrayList<>();
        list.add(new WritePermission());
        list.add(new TransferRatePermission(0, 0));
        list.add(new ConcurrentLoginPermission(10, 10));
        user.setAuthorities(list);
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            Crashlytics.logException(e);
        }
        // do start server
        try {
            ftpServer = serverFactory.createServer();
            ftpServer.start();
            return true;
        } catch (Exception e) {
            ftpServer = null;
            handleServerStartError(e);
        }
        return false;
    }

    @Override
    public void stopServer() {
        ftpServer.stop();
        ftpServer = null;
    }
}

19 View Complete Implementation : CommandLine.java
Copyright Apache License 2.0
Author : apache
/**
 * Add shutdown hook.
 */
private void addShutdownHook(final FtpServer engine) {
    // create shutdown hook
    Runnable shutdownHook = new Runnable() {

        public void run() {
            System.out.println("Stopping server...");
            engine.stop();
        }
    };
    // add shutdown hook
    Runtime runtime = Runtime.getRuntime();
    runtime.addShutdownHook(new Thread(shutdownHook));
}

19 View Complete Implementation : FtpBuildProcessAdapterTest.java
Copyright Apache License 2.0
Author : JetBrains
/**
 * Created by Nikita.Skvortsov
 * Date: 10/3/12, 4:22 PM
 */
public clreplaced FtpBuildProcessAdapterTest extends BaseDeployerTest {

    private FtpServer myServer;

    private File myRemoteDir;

    private int testPort;

    private final String myUsername = "myUsername";

    private final String myPreplacedword = "myPreplacedword";

    private List<ArtifactsCollection> myArtifactsCollections;

    private BuildRunnerContext myContext;

    private final Map<String, String> myRunnerParameters = new HashMap<String, String>();

    private final Map<String, String> mySharedConfigParameters = new HashMap<String, String>();

    private List<String> myResultingLog;

    @BeforeMethod
    @Override
    public void setUp() throws Exception {
        super.setUp();
        myResultingLog = new LinkedList<String>();
        myRunnerParameters.put(FTPRunnerConstants.PARAM_FTP_MODE, "PreplacedIVE");
        myArtifactsCollections = new ArrayList<ArtifactsCollection>();
        myRemoteDir = createTempDir();
        final FtpServerFactory serverFactory = new FtpServerFactory();
        final ListenerFactory factory = new ListenerFactory();
        testPort = NetworkUtil.getFreePort(DEPLOYER_DEFAULT_PORT);
        factory.setPort(testPort);
        DataConnectionConfigurationFactory dataConnectionConfigurationFactory = new DataConnectionConfigurationFactory();
        dataConnectionConfigurationFactory.setActiveEnabled(false);
        factory.setDataConnectionConfiguration(dataConnectionConfigurationFactory.createDataConnectionConfiguration());
        final SslConfigurationFactory ssl = new SslConfigurationFactory();
        ssl.setKeystoreFile(getTestResource("ftpserver.jks"));
        ssl.setKeystorePreplacedword("preplacedword");
        factory.setSslConfiguration(ssl.createSslConfiguration());
        serverFactory.addListener("default", factory.createListener());
        myServer = serverFactory.createServer();
        final PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(createTempFile());
        userManagerFactory.setPreplacedwordEncryptor(new ClearTextPreplacedwordEncryptor());
        // init user manager
        final UserManager userManager = userManagerFactory.createUserManager();
        serverFactory.setUserManager(userManager);
        // add user
        final BaseUser user = new BaseUser();
        user.setName(myUsername);
        user.setPreplacedword(myPreplacedword);
        user.setHomeDirectory(myRemoteDir.getCanonicalPath());
        // give write permissions
        final List<Authority> authorities = new ArrayList<Authority>();
        final Authority auth = new WritePermission();
        authorities.add(auth);
        user.setAuthorities(authorities);
        userManager.save(user);
        // start the server
        myServer.start();
        Mockery mockeryCtx = new Mockery();
        myContext = mockeryCtx.mock(BuildRunnerContext.clreplaced);
        final AgentRunningBuild build = mockeryCtx.mock(AgentRunningBuild.clreplaced);
        final BuildProgressLogger logger = new NullBuildProgressLogger() {

            @Override
            public void message(String message) {
                myResultingLog.add(message);
            }
        };
        final File workingDir = createTempDir();
        mockeryCtx.checking(new Expectations() {

            {
                allowing(myContext).getWorkingDirectory();
                will(returnValue(workingDir));
                allowing(myContext).getBuild();
                will(returnValue(build));
                allowing(myContext).getRunnerParameters();
                will(returnValue(myRunnerParameters));
                allowing(build).getBuildLogger();
                will(returnValue(logger));
                allowing(build).getSharedConfigParameters();
                will(returnValue(mySharedConfigParameters));
            }
        });
    }

    @AfterMethod
    @Override
    public void tearDown() throws Exception {
        myServer.stop();
        super.tearDown();
    }

    @Test
    public void testSimpleTransfer() throws Exception {
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2", "dest3", "dest4", "dest5", "dest6", "dest7", "dest8", "dest9", "dest10", "dest11", "dest12", "dest13", "dest14", "dest15", "dest16", "dest17", "dest18", "dest19", "dest20", "dest21"));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(myRemoteDir, myArtifactsCollections);
        replacedertTrue(myResultingLog.contains("< and continued >"));
    }

    @Test
    public void testTransferInActiveMode() throws Exception {
        myRunnerParameters.put(FTPRunnerConstants.PARAM_FTP_MODE, "ACTIVE");
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2"));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort);
        process.start();
        new WaitFor(5000) {

            @Override
            protected boolean condition() {
                return process.isFinished();
            }
        };
        replacedertTrue("Failed to finish test in time", process.isFinished());
        replacedertEquals(BuildFinishedStatus.FINISHED_FAILED, process.waitFor());
    }

    @Test
    public void testTransferToRelativePath() throws Exception {
        final String subPath = "test_path/subdir";
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2"));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort + "/" + subPath);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(new File(myRemoteDir, subPath), myArtifactsCollections);
    }

    @Test
    public void testTransferToRelativeSubPath() throws Exception {
        final String subPath = "test_path/subdir";
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1/subdest1", "dest2/subdest2"));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort + "/" + subPath);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(new File(myRemoteDir, subPath), myArtifactsCollections);
    }

    @Test
    public void testTransferToEmptyPath() throws Exception {
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), ""));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(myRemoteDir, myArtifactsCollections);
    }

    @Test
    public void testTransferToDot() throws Exception {
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "."));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(myRemoteDir, myArtifactsCollections);
    }

    @Test
    public void testTransferToExistingPath() throws Exception {
        final String uploadDestination = "some/path";
        final String artifactDestination = "dest1/sub";
        final File existingPath = new File(myRemoteDir, uploadDestination);
        replacedertTrue(existingPath.mkdirs());
        final File existingDestination = new File(existingPath, artifactDestination);
        replacedertTrue(existingDestination.mkdirs());
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), artifactDestination, "dest2"));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort + "/" + uploadDestination);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(existingPath, myArtifactsCollections);
    }

    @Test
    public void testTransferUTF8BOM() throws Exception {
        myRunnerParameters.put(FTPRunnerConstants.PARAM_TRANSFER_MODE, FTPRunnerConstants.TRANSFER_MODE_BINARY);
        File sourceXml = new File("src/test/resources/data.xml");
        if (!sourceXml.exists()) {
            sourceXml = new File("deploy-runner-agent/src/test/resources/data.xml");
        }
        Map<File, String> map = new HashMap<File, String>();
        map.put(sourceXml, "");
        myArtifactsCollections.add(new ArtifactsCollection("", "", map));
        final BuildProcess process = getProcess("127.0.0.1:" + testPort);
        DeployTestUtils.runProcess(process, 5000);
        File[] files = myRemoteDir.listFiles();
        replacedertNotNull(files);
        replacedertEquals(files[0].length(), sourceXml.length());
    }

    @Test
    public void testSecureConnection() throws Exception {
        // Following code can help to test real certificates
        // System.setProperty("javax.net.ssl.trustStore", getTestResource("ftpserver.jks").getAbsolutePath());
        // System.setProperty("javax.net.ssl.trustStorePreplacedword", "preplacedword");
        myRunnerParameters.put(FTPRunnerConstants.PARAM_SSL_MODE, "2");
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2"));
        final BuildProcess process = getProcess("localhost:" + testPort);
        DeployTestUtils.runProcess(process, 5000);
        DeployTestUtils.replacedertCollectionsTransferred(myRemoteDir, myArtifactsCollections);
    }

    @Test
    public void testNotAuthorized() throws Exception {
        myArtifactsCollections.add(DeployTestUtils.buildArtifactsCollection(createTempFilesFactory(), "dest1", "dest2"));
        final BuildProcess process = new FtpBuildProcessAdapter(myContext, "127.0.0.1:" + testPort, myUsername, "wrongpreplacedword", myArtifactsCollections);
        process.start();
        new WaitFor(5000) {

            @Override
            protected boolean condition() {
                return process.isFinished();
            }
        };
        replacedertTrue("Failed to finish test in time", process.isFinished());
        replacedertEquals(process.waitFor(), BuildFinishedStatus.FINISHED_FAILED);
        replacedertEquals(FileUtil.listFiles(myRemoteDir).length, 0);
    }

    private BuildProcess getProcess(String target) {
        return new FtpBuildProcessAdapter(myContext, target, myUsername, myPreplacedword, myArtifactsCollections);
    }
}

19 View Complete Implementation : FTPServer.java
Copyright GNU General Public License v3.0
Author : dubasdey
/**
 * The Clreplaced FTPServer.
 */
public clreplaced FTPServer {

    /**
     * The port.
     */
    private int port;

    /**
     * The user manager.
     */
    private InMemoryUserManager userManager;

    /**
     * The server.
     */
    private FtpServer server;

    /**
     * Instantiates a new FTP server.
     */
    public FTPServer() {
        port = 21;
        userManager = new InMemoryUserManager();
    }

    /**
     * Sets the port.
     *
     * @param port the new port
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Sets the user.
     *
     * @param login the login
     * @param preplacedword the preplacedword
     * @param home the home
     */
    public void setUser(String login, char[] preplacedword, String home) {
        BaseUser user = new BaseUser();
        user.setName(login);
        if (preplacedword != null && preplacedword.length > 0) {
            user.setPreplacedword(new String(preplacedword));
        }
        user.setHomeDirectory(home);
        user.setEnabled(true);
        userManager.setUser(user);
    }

    /**
     * Stop.
     */
    public void stop() {
        if (server != null && !server.isStopped()) {
            server.stop();
            server = null;
        }
    }

    /**
     * Start.
     */
    public boolean start() {
        stop();
        ConnectionConfigFactory configFactory = new ConnectionConfigFactory();
        configFactory.setAnonymousLoginEnabled(false);
        configFactory.setMaxAnonymousLogins(0);
        configFactory.setMaxLoginFailures(5);
        configFactory.setLoginFailureDelay(30);
        configFactory.setMaxThreads(10);
        configFactory.setMaxLogins(10);
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        factory.setIdleTimeout(60);
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.addListener("default", factory.createListener());
        serverFactory.setUserManager(userManager);
        serverFactory.setConnectionConfig(configFactory.createConnectionConfig());
        server = serverFactory.createServer();
        try {
            server.start();
        } catch (FtpException ex) {
            System.err.println(ex.getMessage());
            return false;
        }
        return true;
    }
}

19 View Complete Implementation : FtpTestSupport.java
Copyright Apache License 2.0
Author : spring-cloud
/**
 * Provides an embedded FTP Server for test cases.
 *
 * @author Artem Bilan
 * @author Gary Russell
 * @author David Turanski
 */
public clreplaced FtpTestSupport extends RemoteFileTestSupport {

    private static volatile FtpServer server;

    public String getTargetLocalDirectoryName() {
        return targetLocalDirectory.getAbsolutePath() + File.separator;
    }

    @BeforeClreplaced
    public static void createServer() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.setUserManager(new TestUserManager(remoteTemporaryFolder.getRoot().getAbsolutePath()));
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());
        server = serverFactory.createServer();
        server.start();
    }

    @AfterClreplaced
    public static void stopServer() throws Exception {
        server.stop();
    }

    @Override
    protected String prefix() {
        return "ftp";
    }

    private static clreplaced TestUserManager implements UserManager {

        private final BaseUser testUser;

        private TestUserManager(String homeDirectory) {
            this.testUser = new BaseUser();
            this.testUser.setAuthorities(Arrays.asList(new ConcurrentLoginPermission(1024, 1024), new WritePermission(), new TransferRatePermission(1024, 1024)));
            this.testUser.setHomeDirectory(homeDirectory);
            this.testUser.setName("TEST_USER");
        }

        @Override
        public User getUserByName(String s) throws FtpException {
            return this.testUser;
        }

        @Override
        public String[] getAllUserNames() throws FtpException {
            return new String[] { "TEST_USER" };
        }

        @Override
        public void delete(String s) throws FtpException {
        }

        @Override
        public void save(User user) throws FtpException {
        }

        @Override
        public boolean doesExist(String s) throws FtpException {
            return true;
        }

        @Override
        public User authenticate(Authentication authentication) throws AuthenticationFailedException {
            return this.testUser;
        }

        @Override
        public String getAdminName() throws FtpException {
            return "admin";
        }

        @Override
        public boolean isAdmin(String s) throws FtpException {
            return s.equals("admin");
        }
    }
}

19 View Complete Implementation : MainActivity.java
Copyright Apache License 2.0
Author : arno-Lu
/*参考http://blog.csdn.net/yudajun/article/details/8803356*/
/*需要将user.properties中最后两行代表最大上传于下载速度设置为比较大,不然无法传输大文件*/
public clreplaced MainActivity extends AppCompatActivity {

    private FtpServer mFtpServer;

    private String ftpConfigDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftpConfig/";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.tvText);
        String info = "请通过浏览器或者我的电脑访问以下地址\n" + "ftp://" + getLocalIpAddress() + ":2221\n";
        tv.setText(info);
        File f = new File(ftpConfigDir);
        if (!f.exists())
            f.mkdir();
        copyResourceFile(R.raw.users, ftpConfigDir + "users.properties");
        Config1();
    }

    public String getLocalIpAddress() {
        String strIP = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        strIP = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("msg", ex.toString());
        }
        return strIP;
    }

    private void copyResourceFile(int rid, String targetFile) {
        InputStream fin = ((Context) this).getResources().openRawResource(rid);
        FileOutputStream fos = null;
        int length;
        try {
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            while ((length = fin.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void Config1() {
        // Now, let's configure the port on which the default listener waits for connections.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        String[] str = { "mkdir", ftpConfigDir };
        try {
            Process ps = Runtime.getRuntime().exec(str);
            try {
                ps.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // "/sdcard/users.properties";
        String filename = ftpConfigDir + "users.properties";
        File files = new File(filename);
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // set the port of the listener
        factory.setPort(2221);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    void Config2() {
        // Now, let's make it possible for a client to use FTPS (FTP over SSL) for the default listener.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        // set the port of the listener
        factory.setPort(2221);
        // define SSL configuration
        SslConfigurationFactory ssl = new SslConfigurationFactory();
        ssl.setKeystoreFile(new File(ftpConfigDir + "ftpserver.jks"));
        ssl.setKeystorePreplacedword("preplacedword");
        // set the SSL configuration for the listener
        factory.setSslConfiguration(ssl.createSslConfiguration());
        factory.setImplicitSsl(true);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(ftpConfigDir + "users.properties"));
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mFtpServer) {
            mFtpServer.stop();
            mFtpServer = null;
        }
    }
}

19 View Complete Implementation : ConnectionsService.java
Copyright Apache License 2.0
Author : gigabytedevelopers
public clreplaced ConnectionsService extends NetworkServerService {

    private FtpServer ftpServer;

    @Override
    protected NetworkServiceHandler createServiceHandler(Looper serviceLooper, NetworkServerService service) {
        return new NetworkServiceHandler(serviceLooper, service);
    }

    @Override
    public Object getServer() {
        return ftpServer;
    }

    @Override
    public boolean launchServer() {
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(ConnectionUtils.getAvailablePortForFTP());
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.addListener("default", listenerFactory.createListener());
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(getNetworkConnection().isAnonymousLogin());
        connectionConfigFactory.setMaxLoginFailures(5);
        connectionConfigFactory.setLoginFailureDelay(2000);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        BaseUser user = new BaseUser();
        user.setName(getNetworkConnection().getUserName());
        user.setPreplacedword(getNetworkConnection().getPreplacedword());
        user.setHomeDirectory(getNetworkConnection().getPath());
        List<Authority> list = new ArrayList<>();
        list.add(new WritePermission());
        list.add(new TransferRatePermission(0, 0));
        list.add(new ConcurrentLoginPermission(10, 10));
        user.setAuthorities(list);
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            CrashReportingManager.logException(e);
        }
        // do start server
        try {
            ftpServer = serverFactory.createServer();
            ftpServer.start();
            return true;
        } catch (Exception e) {
            ftpServer = null;
            handleServerStartError(e);
        }
        return false;
    }

    @Override
    public void stopServer() {
        ftpServer.stop();
        ftpServer = null;
    }
}

19 View Complete Implementation : FtpLoaderTest.java
Copyright Apache License 2.0
Author : OpenBEL
/**
 * {@link FtpLoaderTest} tests the {@link FTPProtocolHandler}.
 *
 * @author Anthony Bargnesi {@code <[email protected]>}
 */
public clreplaced FtpLoaderTest extends AbstractProtocolTest {

    /**
     * Defines the test ftp username as {@value}.
     */
    private static final String TEST_USERNAME = "ftptest";

    /**
     * Defines the test ftp preplacedword as {@value}.
     */
    private static final String TEST_PreplacedWORD = "ftptest";

    /**
     * Defines the test ftp root as the "user.dir" system property.
     */
    private static final String TEST_USER_FTP_ROOT = System.getProperty("user.dir");

    /**
     * Defines the location file where the file will be saved.
     */
    private File localDestinationFile;

    /**
     * Defines the ftp server used as a test ftp daemon.
     */
    private FtpServer ftpServer;

    /**
     * Defines the port the test ftp server will run on.
     */
    private int port;

    /**
     * Set up the ftp test by choosing a random ftp server port.
     */
    @Before
    public void setupTest() {
        port = ephemeralPort();
    }

    /**
     * Tear down the test by stopping the ftp server.
     */
    @After
    public void teardownTest() {
        stopFtpServer();
    }

    /**
     * Test the successful retrieval of a file via ftp inline authentication.
     */
    @Test
    public void testFTPInlineAuthentication() {
        try {
            startRestrictedFtpServer();
        } catch (FtpException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
        try {
            localDestinationFile = new FTPProtocolHandler().downloadResource("ftp://ftptest:ftptest@localhost:" + port + "/" + TEST_FILE_PATH, "test.belns");
            tempFiles.add(localDestinationFile);
            testFile(localDestinationFile);
        } catch (ResourceDownloadError e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
    }

    /**
     * Test the successful retrieval of a file via prompted preplacedword
     * authentication.
     */
    @Test
    public void testFTPPromptedPreplacedwordAuthentication() {
        try {
            startRestrictedFtpServer();
        } catch (FtpException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
        try {
            ByteArrayInputStream pwdStringInputStream = new ByteArrayInputStream("ftptest".getBytes("US-ASCII"));
            localDestinationFile = new FTPProtocolHandler(pwdStringInputStream).downloadResource("ftp://ftptest@localhost:" + port + "/" + TEST_FILE_PATH, "test.belns");
            tempFiles.add(localDestinationFile);
            testFile(localDestinationFile);
        } catch (ResourceDownloadError e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
    }

    /**
     * Test the successful retrieval of a file using an anonymous ftp
     * account.
     */
    @Test
    public void testFTPAnonymousAuthenticationAllowed() {
        try {
            startUnrestrictedFtpServer();
        } catch (FtpException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
        try {
            localDestinationFile = new FTPProtocolHandler().downloadResource("ftp://localhost:" + port + "/" + TEST_FILE_PATH, "test.belns");
            tempFiles.add(localDestinationFile);
            testFile(localDestinationFile);
        } catch (ResourceDownloadError e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
    }

    /**
     * Test the expectation that we will receive a
     * {@link ResourceDownloadError} if the ftp server does not allow
     * anonymous account access.
     *
     * @throws ResourceDownloadError - Thrown if the ftp connection
     * could not be made because anonymous accounts are restricted.  This
     * is expected to be thrown and it is a testcase failure if it is not.
     */
    @Test(expected = ResourceDownloadError.clreplaced)
    public void testFTPAnonymousAuthenticationDenied() throws ResourceDownloadError {
        try {
            startRestrictedFtpServer();
        } catch (FtpException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
        localDestinationFile = new FTPProtocolHandler().downloadResource("ftp://localhost:" + port + "/" + TEST_FILE_PATH, "test.belns");
        tempFiles.add(localDestinationFile);
        try {
            testFile(localDestinationFile);
        } catch (IOException e) {
            e.printStackTrace();
            replacedert.fail(e.getMessage());
        }
    }

    /**
     * Start up the ftp daemon without anonymous account access.
     *
     * @throws FtpException - Thrown if an error occurred starting the
     * restricted ftp daemon.
     */
    protected void startRestrictedFtpServer() throws FtpException {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(false);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        serverFactory.setUserManager(new TestUserManagerFactory().createUserManager());
        startFtpServer(serverFactory);
    }

    /**
     * Start up the ftp daemon with anonymous account access.
     *
     * @throws FtpException - Thrown if an error occurred starting the
     * unrestricted ftp daemon.
     */
    protected void startUnrestrictedFtpServer() throws FtpException {
        FtpServerFactory serverFactory = new FtpServerFactory();
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        serverFactory.setUserManager(new TestUserManagerFactory().createUserManager());
        startFtpServer(serverFactory);
    }

    /**
     * Start the ftp server.
     *
     * @param ftpServerFactory {@link FtpServerFactory}, the factory used
     * to configure the server with
     * @throws FtpException - Thrown if an error occurred starting the ftp
     * server.
     */
    protected void startFtpServer(FtpServerFactory ftpServerFactory) throws FtpException {
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        ftpServerFactory.addListener("default", factory.createListener());
        ftpServer = ftpServerFactory.createServer();
        ftpServer.start();
    }

    /**
     * Stop the ftp server.
     */
    protected void stopFtpServer() {
        if (ftpServer != null && !ftpServer.isStopped()) {
            ftpServer.stop();
        }
    }

    /**
     * TestUserManagerFactory defines a mock {@link UserManagerFactory} to
     * provide the ftp server admin account.
     *
     * @author Anthony Bargnesi {@code <[email protected]>}
     */
    private static clreplaced TestUserManagerFactory implements UserManagerFactory {

        /**
         * {@inheritDoc}
         */
        @Override
        public UserManager createUserManager() {
            return new TestUserManager("admin", new ClearTextPreplacedwordEncryptor());
        }
    }

    /**
     * TestUserManager defines a mock {@link AbstractUserManager} to establish
     * valid users for the ftp server.
     *
     * @author Anthony Bargnesi {@code <[email protected]>}
     */
    private static clreplaced TestUserManager extends AbstractUserManager {

        private BaseUser testUser;

        private BaseUser anonUser;

        /**
         * Creates the TestUserManager with the {@code adminName} and the
         * {@code preplacedwordEncryptor}.
         *
         * @param adminName {@link String}, the admin name
         * @param preplacedwordEncryptor {@link PreplacedwordEncryptor}, the preplacedword
         * encryptor to use
         */
        public TestUserManager(String adminName, PreplacedwordEncryptor preplacedwordEncryptor) {
            super(adminName, preplacedwordEncryptor);
            testUser = new BaseUser();
            testUser.setAuthorities(Arrays.asList(new Authority[] { new ConcurrentLoginPermission(1, 1) }));
            testUser.setEnabled(true);
            testUser.setHomeDirectory(TEST_USER_FTP_ROOT);
            testUser.setMaxIdleTime(10000);
            testUser.setName(TEST_USERNAME);
            testUser.setPreplacedword(TEST_PreplacedWORD);
            anonUser = new BaseUser(testUser);
            anonUser.setName("anonymous");
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public User getUserByName(String username) throws FtpException {
            if (TEST_USERNAME.equals(username)) {
                return testUser;
            } else if (anonUser.getName().equals(username)) {
                return anonUser;
            }
            return null;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public String[] getAllUserNames() throws FtpException {
            return new String[] { TEST_USERNAME, anonUser.getName() };
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void delete(String username) throws FtpException {
        // no opt
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void save(User user) throws FtpException {
            // no opt
            System.out.println("save");
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean doesExist(String username) throws FtpException {
            return (TEST_USERNAME.equals(username) || anonUser.getName().equals(username)) ? true : false;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public User authenticate(Authentication authentication) throws AuthenticationFailedException {
            if (UsernamePreplacedwordAuthentication.clreplaced.isreplacedignableFrom(authentication.getClreplaced())) {
                UsernamePreplacedwordAuthentication upAuth = (UsernamePreplacedwordAuthentication) authentication;
                if (TEST_USERNAME.equals(upAuth.getUsername()) && TEST_PreplacedWORD.equals(upAuth.getPreplacedword())) {
                    return testUser;
                }
                if (anonUser.getName().equals(upAuth.getUsername())) {
                    return anonUser;
                }
            } else if (AnonymousAuthentication.clreplaced.isreplacedignableFrom(authentication.getClreplaced())) {
                return anonUser;
            }
            return null;
        }
    }
}

19 View Complete Implementation : FtpServerBean.java
Copyright Apache License 2.0
Author : camelinaction
/**
 * @version $Revision: 24 $
 */
public clreplaced FtpServerBean {

    protected static FtpServer ftpServer;

    private static int port = 21000;

    public static void startServer() throws Exception {
        System.out.println("Starting FTP Server...");
        initFtpServer();
        ftpServer.start();
        System.out.println("Starting FTP Server done.");
    }

    public static void shutdownServer() throws Exception {
        System.out.println("Stopping FTP Server...");
        try {
            ftpServer.stop();
            ftpServer = null;
        } catch (Exception e) {
        // ignore while shutting down as we could be polling during shutdown
        // and get errors when the ftp server is stopping. This is only an issue
        // since we host the ftp server embedded in the same jvm for unit testing
        }
        System.out.println("Stopping FTP Server done.");
    }

    public static void initFtpServer() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        // setup user management to read our users.properties and use clear text preplacedwords
        URL url = ObjectHelper.loadResourceAsURL("users.properties");
        UserManager uman = new PropertiesUserManager(new ClearTextPreplacedwordEncryptor(), url, "admin");
        serverFactory.setUserManager(uman);
        NativeFileSystemFactory fsf = new NativeFileSystemFactory();
        fsf.setCreateHome(true);
        serverFactory.setFileSystem(fsf);
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());
        ftpServer = serverFactory.createServer();
    }
}

19 View Complete Implementation : FTPServerStartup.java
Copyright Apache License 2.0
Author : jppf-grid
/**
 * This clreplaced is a driver startup clreplaced wrapper that starts an instance of the Apache Mina FTPServer at driver startup time.
 * <p>The server configuration is done via the mechanism provided by Mina FTPServer, the ftpd.xml file.
 * The location of this file is specified in the JPPF configuration via <code>jppf.file.server.config = my/path/ftpd.xml</code>.
 * @see <a href="http://mina.apache.org/ftpserver">Apache Mina FTPServer</a>
 * @author Laurent Cohen
 */
public clreplaced FTPServerStartup implements JPPFDriverStartupSPI {

    /**
     * Logger for this clreplaced.
     */
    private static Logger log = LoggerFactory.getLogger(FTPServerStartup.clreplaced);

    /**
     * The underlying embedded FTP server.
     */
    private FtpServer server;

    /**
     * Start the FTP server and add a JVM shutdown hook to stop it.
     */
    @Override
    public void run() {
        try {
            final Runnable hook = new Runnable() {

                @Override
                public void run() {
                    stop();
                }
            };
            Runtime.getRuntime().addShutdownHook(new Thread(hook));
            start();
        } catch (final Exception e) {
            log.error("FTP server initialization failed", e);
            // display the error message on the driver's shell console
            System.err.println("FTP server initialization failed: " + e.getMessage());
        }
    }

    /**
     * Start the FTP server using the configuration file whose path is specified in the driver's configuration.
     * @throws Exception if an error occurs while reading the configuration.
     */
    public void start() throws Exception {
        final String configPath = JPPFConfiguration.getProperties().getString("jppf.file.server.config", "config/ftpd.xml");
        server = new CommandLineExt(configPath).createServer();
        server.start();
    }

    /**
     * Stop the FTP server. This method is called from a JVM shutdown hook.
     */
    public void stop() {
        try {
            if ((server != null) && !server.isStopped())
                server.stop();
        } catch (final Throwable t) {
            t.printStackTrace();
        }
    }

    /**
     * Get the underlying embedded FTP server.
     * @return an <code>FtpServer</code> instance.
     */
    public FtpServer getServer() {
        return server;
    }
}

19 View Complete Implementation : FtpServerLifecycle.java
Copyright Apache License 2.0
Author : apache
/*
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public clreplaced FtpServerLifecycle {

    private FtpServer server;

    public FtpServer getServer() {
        return server;
    }

    public void setServer(FtpServer server) {
        this.server = server;
    }

    public void init() throws Exception {
        server.start();
        System.out.println("Server started");
    }

    public void destroy() throws Exception {
        server.stop();
        System.out.println("Server stopped");
    }
}

19 View Complete Implementation : FtpsServer.java
Copyright Apache License 2.0
Author : pentaho
/**
 * @author Andrey Khayrutdinov
 */
public clreplaced FtpsServer {

    public static final String SERVER_BASE_DIR = "src/it/resources/org/pentaho/di/job/entries/ftpsget";

    public static final String SERVER_KEYSTORE = SERVER_BASE_DIR + "/ftpserver.jks";

    public static final String SERVER_USERS = SERVER_BASE_DIR + "/users.properties";

    public static final String USER_HOME_DIR = SERVER_BASE_DIR + "/dir";

    public static final String SAMPLE_FILE = "file.txt";

    public static final String ADMIN = "admin";

    public static final String PreplacedWORD = "preplacedword";

    public static final int DEFAULT_PORT = 8009;

    public static FtpsServer createDefaultServer() throws Exception {
        return new FtpsServer(DEFAULT_PORT, ADMIN, PreplacedWORD, true);
    }

    public static FtpsServer createFtpServer() throws Exception {
        return new FtpsServer(DEFAULT_PORT, ADMIN, PreplacedWORD, false);
    }

    private final FtpServer server;

    public FtpsServer(int port, String username, String preplacedword, boolean implicitSsl) throws Exception {
        this.server = createServer(port, username, preplacedword, implicitSsl);
    }

    /*
   * Adopted from https://mina.apache.org/ftpserver-project/embedding_ftpserver.html
   */
    private FtpServer createServer(int port, String username, String preplacedword, boolean implicitSsl) throws Exception {
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        if (implicitSsl) {
            SslConfigurationFactory ssl = new SslConfigurationFactory();
            ssl.setKeystoreFile(new File(SERVER_KEYSTORE));
            ssl.setKeystorePreplacedword(PreplacedWORD);
            // set the SSL configuration for the listener
            factory.setSslConfiguration(ssl.createSslConfiguration());
            factory.setImplicitSsl(true);
        }
        FtpServerFactory serverFactory = new FtpServerFactory();
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(SERVER_USERS));
        UserManager userManager = userManagerFactory.createUserManager();
        if (!userManager.doesExist(username)) {
            BaseUser user = new BaseUser();
            user.setName(username);
            user.setPreplacedword(preplacedword);
            user.setEnabled(true);
            user.setHomeDirectory(USER_HOME_DIR);
            user.setAuthorities(Collections.<Authority>singletonList(new WritePermission()));
            userManager.save(user);
        }
        serverFactory.setUserManager(userManager);
        return serverFactory.createServer();
    }

    public void start() throws Exception {
        server.start();
    }

    public void stop() throws Exception {
        if (server != null) {
            server.stop();
        }
    }
}

19 View Complete Implementation : FTPService.java
Copyright Apache License 2.0
Author : Modificator
public clreplaced FTPService extends Service implements Runnable {

    public static final int DEFAULT_PORT = 2333;

    public static final String PORT_PREFERENCE_KEY = "ftpPort";

    // Service will (global) broadcast when server start/stop
    public static final String ACTION_STARTED = "cn.modificator.launcher.ftpservice.FTPReceiver.FTPSERVER_STARTED";

    public static final String ACTION_STOPPED = "cn.modificator.launcher.ftpservice.FTPReceiver.FTPSERVER_STOPPED";

    public static final String ACTION_FAILEDTOSTART = "cn.modificator.launcher.ftpservice.FTPReceiver.FTPSERVER_FAILEDTOSTART";

    // RequestStartStopReceiver listens for these actions to start/stop this server
    public static final String ACTION_START_FTPSERVER = "cn.modificator.launcher.ftpservice.FTPReceiver.ACTION_START_FTPSERVER";

    public static final String ACTION_STOP_FTPSERVER = "cn.modificator.launcher.ftpservice.FTPReceiver.ACTION_STOP_FTPSERVER";

    public static int getDefaultPortFromPreferences(SharedPreferences preferences) {
        try {
            return preferences.getInt(PORT_PREFERENCE_KEY, DEFAULT_PORT);
        } catch (ClreplacedCastException ex) {
            Log.e("FtpService", "Default port preference is not an int. Resetting to default.");
            changeFTPServerPort(preferences, DEFAULT_PORT);
            return DEFAULT_PORT;
        }
    }

    public static void changeFTPServerPort(SharedPreferences preferences, int port) {
        preferences.edit().putInt(PORT_PREFERENCE_KEY, port).apply();
    }

    private static final String TAG = FTPService.clreplaced.getSimpleName();

    /**
     * TODO: 25/10/16 This is ugly
     */
    private static int port = 2333;

    private String username, preplacedword;

    private boolean isPreplacedwordProtected = false;

    protected boolean shouldExit = false;

    private FtpServer server;

    protected static Thread serverThread = null;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        shouldExit = false;
        int attempts = 10;
        while (serverThread != null) {
            if (attempts > 0) {
                attempts--;
                FTPService.sleepIgnoreInterupt(1000);
            } else {
                return START_STICKY;
            }
        }
        if (intent != null && intent.getStringExtra("username") != null && intent.getStringExtra("preplacedword") != null) {
            username = intent.getStringExtra("username");
            preplacedword = intent.getStringExtra("preplacedword");
            isPreplacedwordProtected = true;
        }
        serverThread = new Thread(this);
        serverThread.start();
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void run() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        FtpServerFactory serverFactory = new FtpServerFactory();
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        BaseUser user = new BaseUser();
        if (!isPreplacedwordProtected) {
            user.setName("anonymous");
        } else {
            user.setName(username);
            user.setPreplacedword(preplacedword);
        }
        user.setHomeDirectory(path);
        List<Authority> list = new ArrayList<>();
        list.add(new WritePermission());
        user.setAuthorities(list);
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            e.printStackTrace();
        }
        ListenerFactory fac = new ListenerFactory();
        port = getDefaultPortFromPreferences(preferences);
        fac.setPort(port);
        serverFactory.addListener("default", fac.createListener());
        try {
            server = serverFactory.createServer();
            server.start();
            sendBroadcast(new Intent(FTPService.ACTION_STARTED));
        } catch (Exception e) {
            sendBroadcast(new Intent(FTPService.ACTION_FAILEDTOSTART));
        }
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy() Stopping server");
        shouldExit = true;
        if (serverThread == null) {
            Log.w(TAG, "Stopping with null serverThread");
            return;
        }
        serverThread.interrupt();
        try {
            // wait 10 sec for server thread to finish
            serverThread.join(10000);
        } catch (InterruptedException e) {
        }
        if (serverThread.isAlive()) {
            Log.w(TAG, "Server thread failed to exit");
        } else {
            Log.d(TAG, "serverThread join()ed ok");
            serverThread = null;
        }
        if (server != null) {
            server.stop();
            sendBroadcast(new Intent(FTPService.ACTION_STOPPED));
        }
        Log.d(TAG, "FTPServerService.onDestroy() finished");
    }

    // Restart the service if the app is closed from the recent list
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent restartService = new Intent(getApplicationContext(), this.getClreplaced());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
    }

    public static boolean isRunning() {
        // return true if and only if a server Thread is running
        if (serverThread == null) {
            Log.d(TAG, "Server is not running (null serverThread)");
            return false;
        }
        if (!serverThread.isAlive()) {
            Log.d(TAG, "serverThread non-null but !isAlive()");
        } else {
            Log.d(TAG, "Server is alive");
        }
        return true;
    }

    public static void sleepIgnoreInterupt(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException ignored) {
        }
    }

    public static boolean isConnectedToLocalNetwork(Context context) {
        boolean connected = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        connected = ni != null && ni.isConnected() && (ni.getType() & (ConnectivityManager.TYPE_WIFI | ConnectivityManager.TYPE_ETHERNET)) != 0;
        if (!connected) {
            Log.d(TAG, "isConnectedToLocalNetwork: see if it is an WIFI AP");
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            try {
                Method method = wm.getClreplaced().getDeclaredMethod("isWifiApEnabled");
                connected = (Boolean) method.invoke(wm);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!connected) {
            Log.d(TAG, "isConnectedToLocalNetwork: see if it is an USB AP");
            try {
                for (NetworkInterface netInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                    if (netInterface.getDisplayName().startsWith("rndis")) {
                        connected = true;
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return connected;
    }

    public static boolean isConnectedToWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnected() && ni.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static InetAddress getLocalInetAddress(Context context) {
        if (!isConnectedToLocalNetwork(context)) {
            Log.e(TAG, "getLocalInetAddress called and no connection");
            return null;
        }
        if (isConnectedToWifi(context)) {
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            int ipAddress = wm.getConnectionInfo().getIpAddress();
            if (ipAddress == 0)
                return null;
            return intToInet(ipAddress);
        }
        try {
            Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces();
            while (netinterfaces.hasMoreElements()) {
                NetworkInterface netinterface = netinterfaces.nextElement();
                Enumeration<InetAddress> adresses = netinterface.getInetAddresses();
                while (adresses.hasMoreElements()) {
                    InetAddress address = adresses.nextElement();
                    // this is the condition that sometimes gives problems
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress())
                        return address;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InetAddress intToInet(int value) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            bytes[i] = byteOfInt(value, i);
        }
        try {
            return InetAddress.getByAddress(bytes);
        } catch (UnknownHostException e) {
            // This only happens if the byte array has a bad length
            return null;
        }
    }

    public static byte byteOfInt(int value, int which) {
        int shift = which * 8;
        return (byte) (value >> shift);
    }

    public static int getPort() {
        return port;
    }

    public static boolean isPortAvailable(int port) {
        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                /* should not be thrown */
                }
            }
        }
        return false;
    }
}

19 View Complete Implementation : FtpsServer.java
Copyright Apache License 2.0
Author : project-hop
/**
 * @author Andrey Khayrutdinov
 */
public clreplaced FtpsServer {

    public static final String SERVER_BASE_DIR = "src/it/resources/org.apache.hop/job/entries/ftpsget";

    public static final String SERVER_KEYSTORE = SERVER_BASE_DIR + "/ftpserver.jks";

    public static final String SERVER_USERS = SERVER_BASE_DIR + "/users.properties";

    public static final String USER_HOME_DIR = SERVER_BASE_DIR + "/dir";

    public static final String SAMPLE_FILE = "file.txt";

    public static final String ADMIN = "admin";

    public static final String PreplacedWORD = "preplacedword";

    public static final int DEFAULT_PORT = 8009;

    public static FtpsServer createDefaultServer() throws Exception {
        return new FtpsServer(DEFAULT_PORT, ADMIN, PreplacedWORD, true);
    }

    public static FtpsServer createFtpServer() throws Exception {
        return new FtpsServer(DEFAULT_PORT, ADMIN, PreplacedWORD, false);
    }

    private final FtpServer server;

    public FtpsServer(int port, String username, String preplacedword, boolean implicitSsl) throws Exception {
        this.server = createServer(port, username, preplacedword, implicitSsl);
    }

    /*
   * Adopted from https://mina.apache.org/ftpserver-project/embedding_ftpserver.html
   */
    private FtpServer createServer(int port, String username, String preplacedword, boolean implicitSsl) throws Exception {
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        if (implicitSsl) {
            SslConfigurationFactory ssl = new SslConfigurationFactory();
            ssl.setKeystoreFile(new File(SERVER_KEYSTORE));
            ssl.setKeystorePreplacedword(PreplacedWORD);
            // set the SSL configuration for the listener
            factory.setSslConfiguration(ssl.createSslConfiguration());
            factory.setImplicitSsl(true);
        }
        FtpServerFactory serverFactory = new FtpServerFactory();
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(SERVER_USERS));
        UserManager userManager = userManagerFactory.createUserManager();
        if (!userManager.doesExist(username)) {
            BaseUser user = new BaseUser();
            user.setName(username);
            user.setPreplacedword(preplacedword);
            user.setEnabled(true);
            user.setHomeDirectory(USER_HOME_DIR);
            user.setAuthorities(Collections.<Authority>singletonList(new WritePermission()));
            userManager.save(user);
        }
        serverFactory.setUserManager(userManager);
        return serverFactory.createServer();
    }

    public void start() throws Exception {
        server.start();
    }

    public void stop() throws Exception {
        if (server != null) {
            server.stop();
        }
    }
}

19 View Complete Implementation : GeoBatchServer.java
Copyright GNU General Public License v3.0
Author : geosolutions-it
/**
 * @param ftpServer
 *            the ftpServer to set
 */
public void setFtpServer(FtpServer ftpServer) {
    this.ftpServer = ftpServer;
}

19 View Complete Implementation : FtpService.java
Copyright GNU General Public License v3.0
Author : TeamAmaze
public clreplaced FtpService extends Service implements Runnable {

    public static final int DEFAULT_PORT = 2211;

    public static final String DEFAULT_USERNAME = "";

    // default timeout, in sec
    public static final int DEFAULT_TIMEOUT = 600;

    public static final boolean DEFAULT_SECURE = true;

    public static final String PORT_PREFERENCE_KEY = "ftpPort";

    public static final String KEY_PREFERENCE_PATH = "ftp_path";

    public static final String KEY_PREFERENCE_USERNAME = "ftp_username";

    public static final String KEY_PREFERENCE_PreplacedWORD = "ftp_preplacedword_encrypted";

    public static final String KEY_PREFERENCE_TIMEOUT = "ftp_timeout";

    public static final String KEY_PREFERENCE_SECURE = "ftp_secure";

    public static final String DEFAULT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

    public static final String INITIALS_HOST_FTP = "ftp://";

    public static final String INITIALS_HOST_SFTP = "ftps://";

    private static final String WIFI_AP_ADDRESS_PREFIX = "192.168.43.";

    private static final char[] KEYSTORE_PreplacedWORD = "vishal007".toCharArray();

    // Service will broadcast via event bus when server start/stop
    public enum FtpReceiverActions {

        STARTED, STARTED_FROM_TILE, STOPPED, FAILED_TO_START
    }

    // RequestStartStopReceiver listens for these actions to start/stop this server
    static public final String ACTION_START_FTPSERVER = "com.amaze.filemanager.services.ftpservice.FTPReceiver.ACTION_START_FTPSERVER";

    static public final String ACTION_STOP_FTPSERVER = "com.amaze.filemanager.services.ftpservice.FTPReceiver.ACTION_STOP_FTPSERVER";

    // attribute of action_started, used by notification
    static public final String TAG_STARTED_BY_TILE = "started_by_tile";

    private String username, preplacedword;

    private boolean isPreplacedwordProtected = false;

    private FtpServer server;

    protected static Thread serverThread = null;

    private boolean isStartedByTile = false;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isStartedByTile = intent.getBooleanExtra(TAG_STARTED_BY_TILE, false);
        int attempts = 10;
        while (serverThread != null) {
            if (attempts > 0) {
                attempts--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            } else {
                return START_STICKY;
            }
        }
        serverThread = new Thread(this);
        serverThread.start();
        Notification notification = FtpNotification.startNotification(getApplicationContext(), isStartedByTile);
        startForeground(NotificationConstants.FTP_ID, notification);
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void run() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        FtpServerFactory serverFactory = new FtpServerFactory();
        ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        String usernamePreference = preferences.getString(KEY_PREFERENCE_USERNAME, DEFAULT_USERNAME);
        if (!usernamePreference.equals(DEFAULT_USERNAME)) {
            username = usernamePreference;
            try {
                preplacedword = CryptUtil.decryptPreplacedword(getApplicationContext(), preferences.getString(KEY_PREFERENCE_PreplacedWORD, ""));
                isPreplacedwordProtected = true;
            } catch (GeneralSecurityException | IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
                // can't decrypt the preplacedword saved in preferences, remove the preference altogether
                // and start an anonymous connection instead
                preferences.edit().putString(FtpService.KEY_PREFERENCE_PreplacedWORD, "").apply();
                isPreplacedwordProtected = false;
            }
        }
        BaseUser user = new BaseUser();
        if (!isPreplacedwordProtected) {
            user.setName("anonymous");
        } else {
            user.setName(username);
            user.setPreplacedword(preplacedword);
        }
        user.setHomeDirectory(preferences.getString(KEY_PREFERENCE_PATH, DEFAULT_PATH));
        List<Authority> list = new ArrayList<>();
        list.add(new WritePermission());
        user.setAuthorities(list);
        try {
            serverFactory.getUserManager().save(user);
        } catch (FtpException e) {
            e.printStackTrace();
        }
        ListenerFactory fac = new ListenerFactory();
        if (preferences.getBoolean(KEY_PREFERENCE_SECURE, DEFAULT_SECURE)) {
            try {
                KeyStore keyStore = KeyStore.getInstance("BKS", "BC");
                keyStore.load(getResources().openRawResource(R.raw.key), KEYSTORE_PreplacedWORD);
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyManagerFactory.init(keyStore, KEYSTORE_PreplacedWORD);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(keyStore);
                fac.setSslConfiguration(new DefaultSslConfiguration(keyManagerFactory, trustManagerFactory, ClientAuth.WANT, "TLS", null, "ftpserver"));
                fac.setImplicitSsl(true);
            } catch (GeneralSecurityException | IOException e) {
                preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply();
            }
        }
        fac.setPort(getPort(preferences));
        fac.setIdleTimeout(preferences.getInt(KEY_PREFERENCE_TIMEOUT, DEFAULT_TIMEOUT));
        serverFactory.addListener("default", fac.createListener());
        try {
            server = serverFactory.createServer();
            server.start();
            EventBus.getDefault().post(isStartedByTile ? FtpReceiverActions.STARTED_FROM_TILE : FtpReceiverActions.STARTED);
        } catch (Exception e) {
            EventBus.getDefault().post(FtpReceiverActions.FAILED_TO_START);
        }
    }

    @Override
    public void onDestroy() {
        if (serverThread == null) {
            return;
        }
        serverThread.interrupt();
        try {
            // wait 10 sec for server thread to finish
            serverThread.join(10000);
        } catch (InterruptedException e) {
        }
        if (!serverThread.isAlive()) {
            serverThread = null;
        }
        if (server != null) {
            server.stop();
            EventBus.getDefault().post(FtpReceiverActions.STOPPED);
        }
    }

    // Restart the service if the app is closed from the recent list
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent restartService = new Intent(getApplicationContext(), this.getClreplaced());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI);
    }

    public static boolean isRunning() {
        return serverThread != null;
    }

    public static boolean isConnectedToLocalNetwork(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        boolean connected = ni != null && ni.isConnected() && (ni.getType() & (ConnectivityManager.TYPE_WIFI | ConnectivityManager.TYPE_ETHERNET)) != 0;
        if (!connected) {
            try {
                for (NetworkInterface netInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                    if (netInterface.getDisplayName().startsWith("rndis")) {
                        connected = true;
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return connected;
    }

    public static boolean isConnectedToWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnected() && ni.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean isEnabledWifiHotspot(Context context) {
        WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        Boolean enabled = callIsWifiApEnabled(wm);
        return enabled != null ? enabled : false;
    }

    public static InetAddress getLocalInetAddress(Context context) {
        if (!isConnectedToLocalNetwork(context) && !isEnabledWifiHotspot(context)) {
            return null;
        }
        if (isConnectedToWifi(context)) {
            WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            int ipAddress = wm.getConnectionInfo().getIpAddress();
            if (ipAddress == 0)
                return null;
            return intToInet(ipAddress);
        }
        try {
            Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces();
            while (netinterfaces.hasMoreElements()) {
                NetworkInterface netinterface = netinterfaces.nextElement();
                Enumeration<InetAddress> addresses = netinterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address == null) {
                        continue;
                    }
                    if (address.getHostAddress().startsWith(WIFI_AP_ADDRESS_PREFIX) && isEnabledWifiHotspot(context))
                        return address;
                    // this is the condition that sometimes gives problems
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !isEnabledWifiHotspot(context))
                        return address;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InetAddress intToInet(int value) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            bytes[i] = byteOfInt(value, i);
        }
        try {
            return InetAddress.getByAddress(bytes);
        } catch (UnknownHostException e) {
            // This only happens if the byte array has a bad length
            return null;
        }
    }

    public static byte byteOfInt(int value, int which) {
        int shift = which * 8;
        return (byte) (value >> shift);
    }

    public static int getPort(SharedPreferences preferences) {
        return preferences.getInt(PORT_PREFERENCE_KEY, DEFAULT_PORT);
    }

    @Nullable
    private static Boolean callIsWifiApEnabled(@NonNull WifiManager wifiManager) {
        Boolean r = null;
        try {
            Method method = wifiManager.getClreplaced().getDeclaredMethod("isWifiApEnabled");
            r = (Boolean) method.invoke(wifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return r;
    }
}

19 View Complete Implementation : FTPServerService.java
Copyright GNU Affero General Public License v3.0
Author : aikuma
/**
 * The embedded FTP server service
 *
 * @author	Sangyeop Lee	<[email protected]>
 */
public clreplaced FTPServerService extends IntentService {

    private static final String TAG = FTPServerService.clreplaced.getCanonicalName();

    /**
     * Broadcast message signature
     */
    public final static String SERVER_RESULT = "org.lp20.aikuma.server.result";

    /**
     * Key of data in the broadcast message
     */
    public final static String SERVER_STATUS = "server_status";

    /**
     * A list of keys used to start FTPServerService
     * (Keys of actions in an incoming intent)
     */
    public static final String ACTION_KEY = "id";

    /**
     */
    public static final String SERVER_ADDR_KEY = "serverAddress";

    private static FtpServer server;

    /**
     * Constructor for IntentService subclreplacedes
     */
    public FTPServerService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String id = intent.getStringExtra(ACTION_KEY);
        Log.i(TAG, "receive: " + id + ", server: " + (server == null));
        if (id.equals("server")) {
            if (server != null) {
                return;
            }
            /*
			if(server != null) {
				Log.i(TAG, "server.suspend?" + server.isSuspended());
				if(server.isSuspended()) {
					Log.i(TAG, "server resume");
					server.resume();
				}
				return;
			}*/
            FtpServerFactory serverFactory = new FtpServerFactory();
            ListenerFactory listenerFactory = new ListenerFactory();
            listenerFactory.setPort(8888);
            PropertiesUserManagerFactory userFactory = new PropertiesUserManagerFactory();
            // userFactory.setFile(new File(FileIO.getAppRootPath(), "server.properties"));
            userFactory.setPreplacedwordEncryptor(new SaltedPreplacedwordEncryptor());
            UserManager userManager = userFactory.createUserManager();
            BaseUser user = new BaseUser();
            ServerCredentials credential = null;
            try {
                credential = ServerCredentials.read();
            } catch (IOException e1) {
                Log.e(TAG, "credential error: " + e1.getMessage());
            }
            if (credential == null) {
                user.setName("admin");
                user.setPreplacedword("admin");
            } else {
                user.setName(credential.getUsername());
                user.setPreplacedword(credential.getPreplacedword());
            }
            user.setHomeDirectory(Environment.getExternalStorageDirectory().getAbsolutePath());
            List<Authority> authorities = new ArrayList<Authority>();
            authorities.add(new WritePermission());
            user.setAuthorities(authorities);
            try {
                userManager.save(user);
            } catch (FtpException e1) {
                Log.e(TAG, "user save error: " + e1.getMessage());
            }
            serverFactory.addListener("default", listenerFactory.createListener());
            serverFactory.setUserManager(userManager);
            server = serverFactory.createServer();
            try {
                server.start();
                Log.i(TAG, "server started: ");
                broadcastStatus("start");
            } catch (FtpException e) {
                Log.e(TAG, "server start error: " + e.getMessage());
            }
        } else if (id.equals("stop")) {
            if (server != null && !server.isStopped()) {
                server.stop();
                server = null;
            }
        } else {
            String serverIP = intent.getStringExtra(SERVER_ADDR_KEY);
        }
    }

    private void broadcastStatus(String status) {
        Intent intent = new Intent(this.SERVER_RESULT);
        intent.putExtra(this.SERVER_STATUS, status);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

19 View Complete Implementation : FtpIntegrationTest.java
Copyright Apache License 2.0
Author : wildfly-extras
@CamelAware
@RunWith(Arquillian.clreplaced)
public clreplaced FtpIntegrationTest {

    private static final String FILE_BASEDIR = "basedir.txt";

    private static final Path FTP_ROOT_DIR = Paths.get(System.getProperty("jboss.server.data.dir") + "/ftp");

    private static final Path USERS_FILE = Paths.get(System.getProperty("jboss.server.config.dir") + "/users.properties");

    private static final int PORT = AvailablePortFinder.getNextAvailable();

    private FtpServer ftpServer;

    @Deployment
    public static WebArchive createdeployment() throws IOException {
        File[] libraryDependencies = Maven.configureResolverViaPlugin().resolve("org.apache.ftpserver:ftpserver-core").withTransitivity().asFile();
        final WebArchive archive = ShrinkWrap.create(WebArchive.clreplaced, "camel-ftp-tests.war");
        archive.addAsResource(new Stringreplacedet(System.getProperty("basedir")), FILE_BASEDIR);
        archive.addClreplacedes(AvailablePortFinder.clreplaced, TestUtils.clreplaced, FileUtils.clreplaced);
        archive.addAsLibraries(libraryDependencies);
        return archive;
    }

    @Before
    public void startFtpServer() throws Exception {
        FileUtils.deleteDirectory(resolvePath(FTP_ROOT_DIR));
        File usersFile = USERS_FILE.toFile();
        usersFile.createNewFile();
        NativeFileSystemFactory fsf = new NativeFileSystemFactory();
        fsf.setCreateHome(true);
        PropertiesUserManagerFactory pumf = new PropertiesUserManagerFactory();
        pumf.setAdminName("admin");
        pumf.setPreplacedwordEncryptor(new ClearTextPreplacedwordEncryptor());
        pumf.setFile(usersFile);
        UserManager userMgr = pumf.createUserManager();
        BaseUser user = new BaseUser();
        user.setName("admin");
        user.setPreplacedword("admin");
        user.setHomeDirectory(FTP_ROOT_DIR.toString());
        List<Authority> authorities = new ArrayList<>();
        WritePermission writePermission = new WritePermission();
        writePermission.authorize(new WriteRequest());
        authorities.add(writePermission);
        user.setAuthorities(authorities);
        userMgr.save(user);
        ListenerFactory factory1 = new ListenerFactory();
        factory1.setPort(PORT);
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.setUserManager(userMgr);
        serverFactory.setFileSystem(fsf);
        serverFactory.setConnectionConfig(new ConnectionConfigFactory().createConnectionConfig());
        serverFactory.addListener("default", factory1.createListener());
        FtpServerFactory factory = serverFactory;
        ftpServer = factory.createServer();
        ftpServer.start();
    }

    @After
    public void stopFtpServer() throws Exception {
        if (ftpServer != null) {
            try {
                ftpServer.stop();
                ftpServer = null;
            } catch (Exception e) {
            // ignore while shutting down as we could be polling during shutdown
            // and get errors when the ftp server is stopping. This is only an issue
            // since we host the ftp server embedded in the same jvm for unit testing
            }
        }
    }

    @Test
    public void testSendFile() throws Exception {
        File testFile = resolvePath(FTP_ROOT_DIR).resolve("foo/test.txt").toFile();
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.start();
        try {
            Endpoint endpoint = camelctx.getEndpoint("ftp://localhost:" + PORT + "/foo?username=admin&preplacedword=admin");
            replacedert.replacedertFalse(testFile.exists());
            camelctx.createProducerTemplate().sendBodyAndHeader(endpoint, "Hello", "CamelFileName", "test.txt");
            replacedert.replacedertTrue(testFile.exists());
        } finally {
            camelctx.close();
        }
    }

    @Test
    public void testComponentLoads() throws Exception {
        try (CamelContext camelctx = new DefaultCamelContext()) {
            Endpoint endpoint = camelctx.getEndpoint("ftp://localhost/foo");
            replacedert.replacedertNotNull(endpoint);
            replacedert.replacedertEquals(endpoint.getClreplaced().getName(), "org.apache.camel.component.file.remote.FtpEndpoint");
        }
    }

    private Path resolvePath(Path other) throws IOException {
        return Paths.get(TestUtils.getResourceValue(getClreplaced(), "/" + FILE_BASEDIR)).resolve(other);
    }
}

19 View Complete Implementation : FtpServerBean.java
Copyright Apache License 2.0
Author : camelinaction
public clreplaced FtpServerBean {

    protected static FtpServer ftpServer;

    private static int port = 21000;

    public static void startServer() throws Exception {
        System.out.println("Starting FTP Server...");
        initFtpServer();
        ftpServer.start();
        System.out.println("Starting FTP Server done.");
    }

    public static void shutdownServer() throws Exception {
        System.out.println("Stopping FTP Server...");
        try {
            ftpServer.stop();
            ftpServer = null;
        } catch (Exception e) {
        // ignore while shutting down as we could be polling during shutdown
        // and get errors when the ftp server is stopping. This is only an issue
        // since we host the ftp server embedded in the same jvm for unit testing
        }
        System.out.println("Stopping FTP Server done.");
    }

    public static void initFtpServer() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        // setup user management to read our users.properties and use clear text preplacedwords
        URL url = ObjectHelper.loadResourceAsURL("users.properties");
        UserManager uman = new PropertiesUserManager(new ClearTextPreplacedwordEncryptor(), url, "admin");
        serverFactory.setUserManager(uman);
        NativeFileSystemFactory fsf = new NativeFileSystemFactory();
        fsf.setCreateHome(true);
        serverFactory.setFileSystem(fsf);
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());
        ftpServer = serverFactory.createServer();
    }
}

19 View Complete Implementation : FtpServerBean.java
Copyright Apache License 2.0
Author : camelinaction
public clreplaced FtpServerBean {

    protected FtpServer ftpServer;

    private static int port = 21000;

    public void startServer() throws Exception {
        System.out.println("Starting FTP Server...");
        initFtpServer();
        ftpServer.start();
        System.out.println("Starting FTP Server done.");
    }

    public void shutdownServer() throws Exception {
        System.out.println("Stopping FTP Server...");
        try {
            ftpServer.stop();
            ftpServer = null;
        } catch (Exception e) {
        // ignore while shutting down as we could be polling during shutdown
        // and get errors when the ftp server is stopping. This is only an issue
        // since we host the ftp server embedded in the same jvm for unit testing
        }
        System.out.println("Stopping FTP Server done.");
    }

    public void initFtpServer() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        // setup user management to read our users.properties and use clear text preplacedwords
        URL url = ObjectHelper.loadResourceAsURL("users.properties");
        UserManager uman = new PropertiesUserManager(new ClearTextPreplacedwordEncryptor(), url, "admin");
        serverFactory.setUserManager(uman);
        NativeFileSystemFactory fsf = new NativeFileSystemFactory();
        fsf.setCreateHome(true);
        serverFactory.setFileSystem(fsf);
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());
        ftpServer = serverFactory.createServer();
    }
}

19 View Complete Implementation : FtpServerLifecycle.java
Copyright Apache License 2.0
Author : apache
public void setServer(FtpServer server) {
    this.server = server;
}

19 View Complete Implementation : CamelFtpBaseTest.java
Copyright Apache License 2.0
Author : kiegroup
public abstract clreplaced CamelFtpBaseTest extends AbstractBaseTest {

    protected final static String USER = "testUser";

    protected final static String PreplacedWD = "testPreplacedwd";

    protected final static String HOST = "localhost";

    protected final static Integer PORT = 2221;

    protected File ftpRoot;

    protected File testFile;

    protected FtpServer server;

    /**
     * Start the FTP server, create & clean home directory
     */
    @Before
    public void initialize() throws FtpException, IOException {
        File tempDir = new File(System.getProperty("java.io.tmpdir"));
        ftpRoot = new File(tempDir, "ftp");
        if (ftpRoot.exists()) {
            FileUtils.deleteDirectory(ftpRoot);
        }
        boolean created = ftpRoot.mkdir();
        if (!created) {
            throw new IllegalArgumentException("FTP root directory has not been created, " + "check system property java.io.tmpdir");
        }
        String fileName = "test_file_" + CamelFtpTest.clreplaced.getName() + "_" + UUID.randomUUID().toString();
        File testDir = new File(ftpRoot, "testDirectory");
        testFile = new File(testDir, fileName);
        server = configureFtpServer(new FtpServerBuilder());
        server.start();
    }

    @After
    public void clean() throws IOException {
        if (server != null && !server.isStopped()) {
            server.stop();
        }
    }

    protected abstract FtpServer configureFtpServer(FtpServerBuilder builder) throws FtpException;

    /**
     * Builder to ease the FTP server configuration.
     */
    protected clreplaced FtpServerBuilder {

        private FtpServerFactory ftpServerFactory;

        public FtpServerBuilder() {
            ftpServerFactory = new FtpServerFactory();
        }

        public FtpServerBuilder registerListener(final String listenerName, final Listener listener) {
            ftpServerFactory.addListener(listenerName, listener);
            return this;
        }

        public FtpServerBuilder registerDefaultListener(final Listener listener) {
            return registerListener("default", listener);
        }

        public FtpServerBuilder addUser(final String username, final String preplacedword, final File home, final boolean write) throws FtpException {
            UserFactory userFactory = new UserFactory();
            userFactory.setHomeDirectory(home.getAbsolutePath());
            userFactory.setName(username);
            userFactory.setPreplacedword(preplacedword);
            if (write) {
                List<Authority> authorities = new ArrayList<Authority>();
                Authority writePermission = new WritePermission();
                authorities.add(writePermission);
                userFactory.setAuthorities(authorities);
            }
            User user = userFactory.createUser();
            ftpServerFactory.getUserManager().save(user);
            return this;
        }

        public FtpServer build() {
            return ftpServerFactory.createServer();
        }

        public FtpServerFactory getFtpServerFactory() {
            return ftpServerFactory;
        }
    }
}

18 View Complete Implementation : CamelFTPBindingQuickstartTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
public clreplaced CamelFTPBindingQuickstartTest extends AbstractQuickstartTest {

    private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.ftp.binding";

    private static String featureName = "switchyard-quickstart-camel-ftp-binding";

    private static FtpServer ftpServer;

    private static SshServer sshd;

    @BeforeClreplaced
    public static void before() throws Exception {
        sshd = SshServer.setUpDefaultServer();
        sshd.setPort(2220);
        sshd.setKeyPairProvider(createTestKeyPairProvider("target/test-clreplacedes/quickstarts/camel-ftp-binding/hostkey.pem"));
        sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
        sshd.setCommandFactory(new ScpCommandFactory());
        sshd.setPreplacedwordAuthenticator(new BogusPreplacedwordAuthenticator());
        // sshd.setFileSystemFactory(new org.apache.sshd.common.file.nativefs.NativeFileSystemFactory());
        sshd.start();
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(2222);
        serverFactory.addListener("default", listenerFactory.createListener());
        ListenerFactory sslListenerFactory = new ListenerFactory();
        sslListenerFactory.setPort(2221);
        SslConfigurationFactory ssl = new SslConfigurationFactory();
        ssl.setKeystoreFile(getFile("target/test-clreplacedes/quickstarts/camel-ftp-binding/ftpserver.jks"));
        ssl.setKeystorePreplacedword("preplacedword");
        sslListenerFactory.setSslConfiguration(ssl.createSslConfiguration());
        // Setting it to true will not read the file
        sslListenerFactory.setImplicitSsl(false);
        serverFactory.addListener("ssl", sslListenerFactory.createListener());
        PropertiesUserManagerFactory managerFactory = new PropertiesUserManagerFactory();
        managerFactory.setPreplacedwordEncryptor(new ClearTextPreplacedwordEncryptor());
        managerFactory.setFile(getFile("target/test-clreplacedes/quickstarts/camel-ftp-binding/ftp-users.properties"));
        UserManager createUserManager = managerFactory.createUserManager();
        serverFactory.setUserManager(createUserManager);
        // This doesn't work due to clreplaced method signature mismatch
        // NativeFileSystemFactory fileSystemFactory = new NativeFileSystemFactory();
        // fileSystemFactory.setCreateHome(true);
        // serverFactory.setFileSystem(fileSystemFactory);
        File file = new File("target/ftp/ftps");
        file.mkdirs();
        file = new File("target/ftp/sftp");
        file.mkdirs();
        JSch sch = new JSch();
        Session session = sch.getSession("camel", "localhost", 2220);
        session.setUserInfo(new SimpleUserInfo("isMyFriend"));
        session.connect();
        ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
        c.connect();
        System.out.println("Home: " + c.getHome());
        c.chmod(777, ".");
        c.chmod(777, "target");
        c.chmod(777, "target/ftp");
        c.chmod(777, "target/ftp/sftp");
        c.disconnect();
        session.disconnect();
        ftpServer = serverFactory.createServer();
        ftpServer.start();
        startTestContainer(featureName, bundleName);
    }

    @AfterClreplaced
    public static void shutDown() throws Exception {
        if (ftpServer != null) {
            ftpServer.stop();
        }
        if (sshd != null) {
            sshd.stop();
        }
    }

    @Test
    public void testFeatures() throws Exception {
        // Ftp
        File srcFile = new File("target/ftp", "test.txt");
        FileUtils.write(srcFile, "The Phantom");
        for (int i = 0; i < 20; i++) {
            Thread.sleep(500);
            if (!srcFile.exists()) {
                break;
            }
        }
        // File should have been picked up
        replacedertFalse(srcFile.exists());
        File destFile = new File("target/ftp/done", "test.txt");
        replacedertTrue(destFile.exists());
        // Ftps
        srcFile = new File("target/ftp/ftps", "ftps-test.txt");
        FileUtils.write(srcFile, "The Ghost Who Walks");
        for (int i = 0; i < 20; i++) {
            Thread.sleep(500);
            if (!srcFile.exists()) {
                break;
            }
        }
        // File should have been picked up
        replacedertFalse(srcFile.exists());
        destFile = new File("target/ftp/ftps/done", "ftps-test.txt");
        replacedertTrue(destFile.exists());
        // Sftp
        srcFile = new File("target/ftp/sftp", "sftp-test.txt");
        FileUtils.write(srcFile, "Christopher Walker");
        for (int i = 0; i < 20; i++) {
            Thread.sleep(500);
            if (!srcFile.exists()) {
                break;
            }
        }
        // File should have been picked up
        replacedertFalse(srcFile.exists());
        destFile = new File("target/ftp/sftp/done", "sftp-test.txt");
        replacedertTrue(destFile.exists());
    }

    public static FileKeyPairProvider createTestKeyPairProvider(String resource) {
        return new FileKeyPairProvider(new String[] { getFile("target/test-clreplacedes/quickstarts/camel-ftp-binding/hostkey.pem").toString() });
    }

    public static int getFreePort() throws Exception {
        ServerSocket s = new ServerSocket(0);
        try {
            return s.getLocalPort();
        } finally {
            s.close();
        }
    }

    private static File getFile(String resource) {
        /*URL url = CamelFTPBindingQuickstartTest.clreplaced.getClreplacedLoader().getResource(resource);
        File f;
        try {
            f = new File(url.toURI());
        } catch(URISyntaxException e) {
            f = new File(url.getPath());
        }
        return f;*/
        File f = new File(resource);
        return f;
    }

    public static clreplaced BogusPreplacedwordAuthenticator implements PreplacedwordAuthenticator {

        public boolean authenticate(String username, String preplacedword, ServerSession session) {
            return ((username != null) && (preplacedword != null) && username.equals("camel") && preplacedword.equals("isMyFriend"));
        }
    }

    public static clreplaced SimpleUserInfo implements UserInfo, UIKeyboardInteractive {

        private final String preplacedword;

        public SimpleUserInfo(String preplacedword) {
            this.preplacedword = preplacedword;
        }

        public String getPreplacedphrase() {
            return null;
        }

        public String getPreplacedword() {
            return preplacedword;
        }

        public boolean promptPreplacedword(String message) {
            return true;
        }

        public boolean promptPreplacedphrase(String message) {
            return false;
        }

        public boolean promptYesNo(String message) {
            return true;
        }

        public void showMessage(String message) {
        }

        public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
            return new String[] { preplacedword };
        }
    }
}

18 View Complete Implementation : FTPManager.java
Copyright Apache License 2.0
Author : kevalpatel2106
/**
 * Created by Keval Patel on 06/05/17.
 *
 * @author 'https://github.com/kevalpatel2106'
 */
public clreplaced FTPManager {

    // The PORT_NUMBER number
    private static final int PORT_NUMBER = 53705;

    private static final String TAG = FTPManager.clreplaced.getSimpleName();

    private final Context mContext;

    private FtpServer mFtpServer;

    /**
     * Initialize the FTP server
     *
     * @param context instance of the caller.
     */
    @SuppressWarnings("ConstantConditions")
    public FTPManager(Context context) {
        mContext = context;
        // Copy the resources.
        copyResourceFile(context, R.raw.users, mContext.getExternalCacheDir().getAbsolutePath() + "/users.properties");
        copyResourceFile(context, R.raw.ftpserver, mContext.getExternalCacheDir().getAbsolutePath() + "/ftpserver.jks");
    }

    private String getLocalIpAddress() {
        String ipAddrrss = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                Enumeration<InetAddress> enumInetAddress = enumNetworkInterfaces.nextElement().getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();
                    if (inetAddress.isSiteLocalAddress()) {
                        ipAddrrss = ipAddrrss + inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipAddrrss;
    }

    /**
     * Copy all the resources from replacedets to local file storage.
     *
     * @param context    instance of the caller.
     * @param rid        replacedets id.
     * @param targetFile target file to copy.
     */
    private void copyResourceFile(Context context, int rid, String targetFile) {
        InputStream fin = context.getResources().openRawResource(rid);
        FileOutputStream fos = null;
        int length;
        try {
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            while ((length = fin.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Start the FTP server.
     */
    public void startServer() {
        // Set the user factory
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        String filename = mContext.getExternalCacheDir().getAbsolutePath() + "/users.properties";
        File files = new File(filename);
        userManagerFactory.setFile(files);
        // Set the server factory
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // Set the port number
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(PORT_NUMBER);
        try {
            serverFactory.addListener("default", factory.createListener());
            FtpServer server = serverFactory.createServer();
            mFtpServer = server;
            // Start the server
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "onCreate: FTP server started. IP address: " + getLocalIpAddress() + " and Port:" + PORT_NUMBER);
    }

    /**
     * Stop the FTP server.
     */
    public void stopServer() {
        if (null != mFtpServer) {
            mFtpServer.stop();
            mFtpServer = null;
        }
    }
}

18 View Complete Implementation : OctopusFTPServer.java
Copyright GNU General Public License v3.0
Author : octopus-platform
public clreplaced OctopusFTPServer {

    private static final Logger logger = LoggerFactory.getLogger(OctopusFTPServer.clreplaced);

    private static final String FTP_SERVER_HOST = "localhost";

    private static final int FTP_SERVER_PORT = 23231;

    FtpServer server;

    FtpServerFactory serverFactory = new FtpServerFactory();

    ListenerFactory factory = new ListenerFactory();

    ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();

    public void start(String octopusHome) {
        try {
            startServer(octopusHome);
        } catch (FtpException e) {
            logger.debug("Cannot start FTP Server");
        }
    }

    private void startServer(String octopusHome) throws FtpException {
        factory.setPort(FTP_SERVER_PORT);
        factory.setServerAddress(FTP_SERVER_HOST);
        configureAnonymousLogin(octopusHome);
        serverFactory.addListener("default", factory.createListener());
        server = serverFactory.createServer();
        server.start();
    }

    private void configureAnonymousLogin(String octopusHome) throws FtpException {
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        BaseUser user = configureAnonymousUser();
        Path path = Paths.get(octopusHome, "projects");
        String homeDirectory = path.toString();
        user.setHomeDirectory(homeDirectory);
        serverFactory.getUserManager().save(user);
    }

    private BaseUser configureAnonymousUser() {
        BaseUser user = new BaseUser();
        user.setName("anonymous");
        List<Authority> auths = new ArrayList<Authority>();
        Authority auth = new WritePermission();
        auths.add(auth);
        user.setAuthorities(auths);
        return user;
    }
}

18 View Complete Implementation : OctopusFTPServer.java
Copyright GNU Lesser General Public License v3.0
Author : octopus-platform
public clreplaced OctopusFTPServer {

    private static final Logger logger = LoggerFactory.getLogger(OctopusFTPServer.clreplaced);

    private static final String FTP_SERVER_HOST = "localhost";

    private static final int FTP_SERVER_PORT = 23231;

    FtpServer server;

    FtpServerFactory serverFactory = new FtpServerFactory();

    ListenerFactory factory = new ListenerFactory();

    ConnectionConfigFactory connectionConfigFactory = new ConnectionConfigFactory();

    public void start() throws FtpException {
        factory.setPort(FTP_SERVER_PORT);
        factory.setServerAddress(FTP_SERVER_HOST);
        configureAnonymousLogin();
        serverFactory.addListener("default", factory.createListener());
        server = serverFactory.createServer();
        server.start();
    }

    private void configureAnonymousLogin() throws FtpException {
        connectionConfigFactory.setAnonymousLoginEnabled(true);
        serverFactory.setConnectionConfig(connectionConfigFactory.createConnectionConfig());
        BaseUser user = configureAnonymousUser();
        String projectDirStr = OctopusEnvironment.PROJECTS_DIR.toString();
        user.setHomeDirectory(projectDirStr);
        serverFactory.getUserManager().save(user);
    }

    private BaseUser configureAnonymousUser() {
        BaseUser user = new BaseUser();
        user.setName("anonymous");
        List<Authority> auths = new ArrayList<Authority>();
        Authority auth = new WritePermission();
        auths.add(auth);
        user.setAuthorities(auths);
        return user;
    }
}

18 View Complete Implementation : DHuSFtpServerBean.java
Copyright GNU Affero General Public License v3.0
Author : SentinelDataHub
/**
 * @author
 */
public clreplaced DHuSFtpServerBean {

    private static final Logger LOGGER = LogManager.getLogger(DHuSFtpServerBean.clreplaced);

    FtpServer server = null;

    private int port;

    private boolean ftps;

    private String preplacedivePort;

    @Autowired
    private DHuSFtpServer ftpServer;

    public DHuSFtpServerBean() {
    }

    @PostConstruct
    public void start() throws FtpException {
        if (server == null)
            server = ftpServer.createFtpServer(port, preplacedivePort, ftps);
        if (server.isStopped()) {
            try {
                server.start();
            } catch (Exception e) {
                LOGGER.error("Cannot start ftp server: " + e.getMessage());
            }
        }
    }

    @PreDestroy
    public void stop() throws FtpException {
        if ((server != null) && !server.isStopped())
            server.stop();
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public boolean isFtps() {
        return ftps;
    }

    public void setFtps(boolean ftps) {
        this.ftps = ftps;
    }

    public String getPreplacedivePort() {
        return this.preplacedivePort;
    }

    public void setPreplacedivePort(String preplacedivePort) {
        this.preplacedivePort = preplacedivePort;
    }
}

18 View Complete Implementation : AbstractFTPTest.java
Copyright GNU General Public License v3.0
Author : iterate-ch
public clreplaced AbstractFTPTest {

    protected final PathCache cache = new PathCache(100);

    protected FTPSession session;

    private FtpServer server;

    private static final int PORT_NUMBER = ThreadLocalRandom.current().nextInt(2000, 3000);

    @After
    public void disconnect() {
        cache.clear();
    }

    @Before
    public void setup() throws Exception {
        final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new FTPProtocol())));
        final Profile profile = new ProfilePlistReader(factory).read(this.getClreplaced().getResourcereplacedtream("/FTP.cyberduckprofile"));
        final Host host = new Host(profile, "localhost", PORT_NUMBER, new Credentials("test", "test"));
        session = new FTPSession(host, new DefaultX509TrustManager(), new DefaultX509KeyManager()) {

            @Override
            public <T> T _getFeature(final Clreplaced<T> type) {
                final T f = AbstractFTPTest.this.getFeature(type);
                if (null == f) {
                    return super._getFeature(type);
                }
                return f;
            }
        };
        final LoginConnectionService login = new LoginConnectionService(new DisabledLoginCallback() {

            @Override
            public Credentials prompt(final Host bookmark, final String replacedle, final String reason, final LoginOptions options) {
                fail(reason);
                return null;
            }

            @Override
            public void warn(final Host bookmark, final String replacedle, final String message, final String continueButton, final String disconnectButton, final String preference) {
            // 
            }
        }, new DisabledHostKeyCallback(), new TestPreplacedwordStore(), new DisabledProgressListener());
        login.check(session, PathCache.empty(), new DisabledCancelCallback());
    }

    public static clreplaced TestPreplacedwordStore extends DisabledPreplacedwordStore {

        @Override
        public String getPreplacedword(Scheme scheme, int port, String hostname, String user) {
            return "n";
        }
    }

    protected <T> T getFeature(final Clreplaced<T> type) {
        return null;
    }

    @After
    public void stop() {
        server.stop();
    }

    @Before
    public void start() throws Exception {
        final FtpServerFactory serverFactory = new FtpServerFactory();
        final PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        final UserManager userManager = userManagerFactory.createUserManager();
        BaseUser user = new BaseUser();
        user.setName("test");
        user.setPreplacedword("test");
        user.setHomeDirectory(new TemporaryApplicationResourcesFinder().find().getAbsolute());
        List<Authority> authorities = new ArrayList<Authority>();
        authorities.add(new WritePermission());
        // authorities.add(new ConcurrentLoginPermission(2, Integer.MAX_VALUE));
        user.setAuthorities(authorities);
        userManager.save(user);
        serverFactory.setUserManager(userManager);
        final ListenerFactory factory = new ListenerFactory();
        factory.setPort(PORT_NUMBER);
        serverFactory.addListener("default", factory.createListener());
        server = serverFactory.createServer();
        server.start();
    }
}

18 View Complete Implementation : FTPTestSupport.java
Copyright Apache License 2.0
Author : apache
public abstract clreplaced FTPTestSupport extends EmbeddedBrokerTestSupport {

    protected static final String ftpServerListenerName = "default";

    protected Connection connection;

    protected FtpServer server;

    String userNamePreplaced = "activemq";

    Mockery context = null;

    String ftpUrl;

    int ftpPort;

    final File ftpHomeDirFile = new File("target/FTPBlobTest/ftptest");

    @Override
    protected void setUp() throws Exception {
        if (ftpHomeDirFile.getParentFile().exists()) {
            IOHelper.deleteFile(ftpHomeDirFile.getParentFile());
        }
        ftpHomeDirFile.mkdirs();
        ftpHomeDirFile.getParentFile().deleteOnExit();
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        UserManager userManager = userManagerFactory.createUserManager();
        BaseUser user = new BaseUser();
        user.setName("activemq");
        user.setPreplacedword("activemq");
        user.setHomeDirectory(ftpHomeDirFile.getParent());
        // authorize user
        List<Authority> auths = new ArrayList<>();
        Authority auth = new WritePermission();
        auths.add(auth);
        user.setAuthorities(auths);
        userManager.save(user);
        BaseUser guest = new BaseUser();
        guest.setName("guest");
        guest.setPreplacedword("guest");
        guest.setHomeDirectory(ftpHomeDirFile.getParent());
        userManager.save(guest);
        serverFactory.setUserManager(userManager);
        factory.setPort(0);
        serverFactory.addListener(ftpServerListenerName, factory.createListener());
        server = serverFactory.createServer();
        server.start();
        ftpPort = serverFactory.getListener(ftpServerListenerName).getPort();
        super.setUp();
    }

    public void setConnection() throws Exception {
        ftpUrl = "ftp://" + userNamePreplaced + ":" + userNamePreplaced + "@localhost:" + ftpPort + "/ftptest/";
        bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + ftpUrl;
        connectionFactory = createConnectionFactory();
        connection = createConnection();
        connection.start();
    }

    @Override
    protected void tearDown() throws Exception {
        if (connection != null) {
            connection.stop();
        }
        super.tearDown();
        if (server != null) {
            server.stop();
        }
        IOHelper.deleteFile(ftpHomeDirFile.getParentFile());
    }
}

18 View Complete Implementation : FtpTestResource.java
Copyright Apache License 2.0
Author : apache
public clreplaced FtpTestResource implements QuarkusTestResourceLifecycleManager {

    private static final Logger LOGGER = Logger.getLogger(FtpTestResource.clreplaced);

    private FtpServer ftpServer;

    private Path ftpRoot;

    private Path usrFile;

    @Override
    public Map<String, String> start() {
        try {
            final int port = AvailablePortFinder.getNextAvailable();
            ftpRoot = Files.createTempDirectory("ftp-");
            usrFile = Files.createTempFile("ftp-", ".properties");
            NativeFileSystemFactory fsf = new NativeFileSystemFactory();
            fsf.setCreateHome(true);
            PropertiesUserManagerFactory pumf = new PropertiesUserManagerFactory();
            pumf.setAdminName("admin");
            pumf.setPreplacedwordEncryptor(new ClearTextPreplacedwordEncryptor());
            pumf.setFile(usrFile.toFile());
            UserManager userMgr = pumf.createUserManager();
            BaseUser user = new BaseUser();
            user.setName("admin");
            user.setPreplacedword("admin");
            user.setHomeDirectory(ftpRoot.toString());
            List<Authority> authorities = new ArrayList<>();
            WritePermission writePermission = new WritePermission();
            writePermission.authorize(new WriteRequest());
            authorities.add(writePermission);
            user.setAuthorities(authorities);
            userMgr.save(user);
            ListenerFactory factory = new ListenerFactory();
            factory.setPort(port);
            FtpServerFactory serverFactory = new FtpServerFactory();
            serverFactory.setUserManager(userMgr);
            serverFactory.setFileSystem(fsf);
            serverFactory.setConnectionConfig(new ConnectionConfigFactory().createConnectionConfig());
            serverFactory.addListener("default", factory.createListener());
            FtpServerFactory ftpServerFactory = serverFactory;
            ftpServer = ftpServerFactory.createServer();
            ftpServer.start();
            return CollectionHelper.mapOf("camel.ftp.test-port", Integer.toString(port), "camel.ftp.test-root-dir", ftpRoot.toString(), "camel.ftp.test-user-file", usrFile.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void stop() {
        try {
            if (ftpServer != null) {
                ftpServer.stop();
            }
        } catch (Exception e) {
            LOGGER.warn("Failed to stop FTP server due to {}", e);
        }
        try {
            if (ftpRoot != null) {
                Files.walk(ftpRoot).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
            }
        } catch (Exception e) {
            LOGGER.warn("Failed delete ftp root: {}, {}", ftpRoot, e);
        }
        try {
            if (usrFile != null) {
                Files.deleteIfExists(usrFile);
            }
        } catch (Exception e) {
            LOGGER.warn("Failed delete usr file: {}, {}", usrFile, e);
        }
    }
}

18 View Complete Implementation : CommandLine.java
Copyright Apache License 2.0
Author : apache
/**
 * This method is the FtpServer starting point when running by using the
 * command line mode.
 *
 * @param args
 *            The first element of this array must specify the kind of
 *            configuration to be used to start the server.
 */
public static void main(String[] args) {
    CommandLine cli = new CommandLine();
    try {
        // get configuration
        FtpServer server = cli.getConfiguration(args);
        if (server == null) {
            return;
        }
        // start the server
        server.start();
        System.out.println("FtpServer started");
        // add shutdown hook if possible
        cli.addShutdownHook(server);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

18 View Complete Implementation : Daemon.java
Copyright Apache License 2.0
Author : apache
/**
 * Invokes FtpServer as a daemon, running in the background. Used for example
 * for the Windows service.
 *
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public clreplaced Daemon {

    private static final Logger LOG = LoggerFactory.getLogger(Daemon.clreplaced);

    private static FtpServer server;

    private static Object lock = new Object();

    /**
     * Main entry point for the daemon
     * @param args The arguments
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        try {
            if (server == null) {
                // get configuration
                server = getConfiguration(args);
                if (server == null) {
                    LOG.error("No configuration provided");
                    throw new FtpException("No configuration provided");
                }
            }
            String command = "start";
            if (args != null && args.length > 0) {
                command = args[0];
            }
            if (command.equals("start")) {
                LOG.info("Starting FTP server daemon");
                server.start();
                synchronized (lock) {
                    lock.wait();
                }
            } else if (command.equals("stop")) {
                synchronized (lock) {
                    lock.notify();
                }
                LOG.info("Stopping FTP server daemon");
                server.stop();
            }
        } catch (Throwable t) {
            LOG.error("Daemon error", t);
        }
    }

    /**
     * Get the configuration object.
     */
    private static FtpServer getConfiguration(String[] args) throws Exception {
        FtpServer server = null;
        if (args == null || args.length < 2) {
            LOG.info("Using default configuration....");
            server = new FtpServerFactory().createServer();
        } else if ((args.length == 2) && args[1].equals("-default")) {
            // supported for backwards compatibility, but not doreplacedented
            System.out.println("The -default switch is deprecated, please use --default instead");
            LOG.info("Using default configuration....");
            server = new FtpServerFactory().createServer();
        } else if ((args.length == 2) && args[1].equals("--default")) {
            LOG.info("Using default configuration....");
            server = new FtpServerFactory().createServer();
        } else if (args.length == 2) {
            LOG.info("Using xml configuration file " + args[1] + "...");
            FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(args[1]);
            if (ctx.containsBean("server")) {
                server = (FtpServer) ctx.getBean("server");
            } else {
                String[] beanNames = ctx.getBeanNamesForType(FtpServer.clreplaced);
                if (beanNames.length == 1) {
                    server = (FtpServer) ctx.getBean(beanNames[0]);
                } else if (beanNames.length > 1) {
                    System.out.println("Using the first server defined in the configuration, named " + beanNames[0]);
                    server = (FtpServer) ctx.getBean(beanNames[0]);
                } else {
                    System.err.println("XML configuration does not contain a server configuration");
                }
            }
        } else {
            throw new FtpException("Invalid configuration option");
        }
        return server;
    }
}

18 View Complete Implementation : MainActivity.java
Copyright Apache License 2.0
Author : arno-Lu
public clreplaced MainActivity extends Activity {

    private static final String TAG = "FtpServerService";

    // ����IP
    private static String hostip = "191.167.10.53";

    private static final int PORT = 2222;

    // sd��Ŀ¼
    @SuppressLint("SdCardPath")
    private static final String dirname = "/mnt/sdcard/ftp";

    // ftp�����������ļ�·��
    private static final String filename = dirname + "/users.properties";

    private FtpServer mFtpServer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ���������������ļ�
        try {
            creatDirsFiles();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ���������������ļ�
     */
    private void creatDirsFiles() throws IOException {
        File dir = new File(dirname);
        if (!dir.exists()) {
            dir.mkdir();
        }
        FileOutputStream fos = null;
        String tmp = getString(R.string.users);
        File sourceFile = new File(dirname + "/users.properties");
        fos = new FileOutputStream(sourceFile);
        fos.write(tmp.getBytes());
        if (fos != null) {
            fos.close();
        }
    }

    /**
     * ����FTP������
     * @param hostip ����ip
     */
    private void startFtpServer(String hostip) {
        FtpServerFactory serverFactory = new FtpServerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        File files = new File(filename);
        // ���������ļ�
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // ���ü���IP�Ͷ˿ں�
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(PORT);
        factory.setServerAddress(hostip);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        // start the server
        mFtpServer = serverFactory.createServer();
        try {
            mFtpServer.start();
            Log.d(TAG, "������FTP������  ip = " + hostip);
        } catch (FtpException e) {
            System.out.println(e);
        }
    }

    /**
     * �ر�FTP������
     */
    private void stopFtpServer() {
        if (mFtpServer != null) {
            mFtpServer.stop();
            mFtpServer = null;
            Log.d(TAG, "�ر���FTP������ ip = " + hostip);
        }
    }

    /**
     * ��ȡ����ip
     */
    private String getLocalIpAddress() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        if (isIPv4) {
                            return sAddr;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public void onStartServer(View view) {
        hostip = getLocalIpAddress();
        Log.d(TAG, "��ȡ����IP = " + hostip);
        startFtpServer(hostip);
    }
}

18 View Complete Implementation : SftpServerRule.java
Copyright Apache License 2.0
Author : google
private static FtpServer createSftpServer(String user, String preplaced, File home, int port) throws FtpException {
    FtpServer server = TestSftpServer.createSftpServer(user, preplaced, null, port, home);
    server.start();
    return server;
}

18 View Complete Implementation : SftpServerRule.java
Copyright Apache License 2.0
Author : google
/**
 * JUnit Rule for creating an in-process {@link TestSftpServer SFTP Server}.
 *
 * @see TestSftpServer
 */
public final clreplaced SftpServerRule extends ExternalResource {

    @Nullable
    private FtpServer server;

    /**
     * Starts an SFTP server on a randomly selected port.
     *
     * @return the port on which the server is listening
     */
    public int serve(String user, String preplaced, File home) throws FtpException {
        checkState(server == null, "You already have an SFTP server!");
        int port = NetworkUtils.pickUnusedPort();
        server = createSftpServer(user, preplaced, home, port);
        return port;
    }

    @Override
    protected void after() {
        if (server != null) {
            server.stop();
            server = null;
        }
    }

    private static FtpServer createSftpServer(String user, String preplaced, File home, int port) throws FtpException {
        FtpServer server = TestSftpServer.createSftpServer(user, preplaced, null, port, home);
        server.start();
        return server;
    }
}

17 View Complete Implementation : AntHarnessTest.java
Copyright Apache License 2.0
Author : Alexey1Gavrilov
/**
 * A test harness for running Ant targets.
 */
@RunWith(Parameterized.clreplaced)
public clreplaced AntHarnessTest {

    private static FtpServer ftpServer;

    private static int ftpPort;

    private static SshServer sshServer;

    private static int sshPort;

    @BeforeClreplaced
    public static void startFtpServer() throws FtpException {
        FtpServerFactory serverFactory = new FtpServerFactory();
        BaseUser user = new BaseUser();
        user.setName("ftp");
        user.setPreplacedword("secret");
        serverFactory.getUserManager().save(user);
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(0);
        Listener listener = factory.createListener();
        serverFactory.addListener("default", listener);
        ftpServer = serverFactory.createServer();
        ftpServer.start();
        ftpPort = listener.getPort();
    }

    @BeforeClreplaced
    public static void startSshServer() throws IOException {
        sshServer = SshServer.setUpDefaultServer();
        ServerSocket serverSocket = new ServerSocket(0);
        sshPort = serverSocket.getLocalPort();
        serverSocket.close();
        sshServer.setPort(sshPort);
        sshServer.setPreplacedwordAuthenticator(new PreplacedwordAuthenticator() {

            @Override
            public boolean authenticate(String username, String preplacedword, ServerSession session) {
                return "ssh".equals(username) && "secret".equals(preplacedword);
            }
        });
        sshServer.setShellFactory(new SshEchoCommandFactory());
        sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
        sshServer.start();
    }

    @AfterClreplaced
    public static void stopServers() throws FtpException, InterruptedException {
        ftpServer.stop();
        sshServer.stop();
    }

    private static File buildFile;

    private static void setupBuildFile() throws IOException {
        if (buildFile != null) {
            return;
        }
        buildFile = File.createTempFile("build", ".xml");
        buildFile.deleteOnExit();
        URL url = Resources.getResource("build-test.xml");
        Resources.copy(url, new FileOutputStream(buildFile));
    }

    @Parameters(name = "{0}")
    public static Iterable<Object[]> data() throws IOException {
        Project project = newProject();
        Function<String, Object[]> toTargetArray = new Function<String, Object[]>() {

            @Override
            public Object[] apply(String input) {
                return new Object[] { input };
            }
        };
        Iterable<String> filtered = Iterables.filter(new TreeSet<String>(project.getTargets().keySet()), new Predicate<String>() {

            @Override
            public boolean apply(String input) {
                return !input.isEmpty();
            }
        });
        return Iterables.transform(filtered, toTargetArray);
    }

    private static Project newProject() throws IOException {
        setupBuildFile();
        Project project = new Project();
        project.setUserProperty("ant.file", buildFile.getAbsolutePath());
        project.init();
        DefaultLogger listener = new DefaultLogger();
        listener.setErrorPrintStream(System.err);
        listener.setOutputPrintStream(System.out);
        listener.setMessageOutputLevel(Project.MSG_INFO);
        ProjectHelper helper = ProjectHelper.getProjectHelper();
        project.addReference("ant.projectHelper", helper);
        project.setProperty("ftp.port", String.valueOf(ftpPort));
        project.setProperty("ssh.port", String.valueOf(sshPort));
        helper.parse(project, buildFile);
        project.addBuildListener(listener);
        return project;
    }

    private final String target;

    public AntHarnessTest(String target) {
        this.target = target;
    }

    @Test
    public void runTarget() throws IOException {
        Project project = newProject();
        project.log("started: " + target);
        // prepare
        project.executeTarget("");
        boolean negative = target.endsWith("-negative");
        // run test
        try {
            project.executeTarget(target);
            if (negative) {
                fail("Negative test fails");
            }
        } catch (BuildException e) {
            e.printStackTrace();
            if (!negative) {
                fail("Positive test fails");
            }
        } finally {
            project.log("finished");
        }
    }
}

17 View Complete Implementation : FtpActivity.java
Copyright Apache License 2.0
Author : arno-Lu
public clreplaced FtpActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private FtpServer mFtpServer;

    private Button WiFiButton;

    private Button ApButton;

    private TextView ap_name;

    private TextView wifi_replacedle;

    private TextView tv;

    private SwipeRefreshLayout swipeRefreshLayout;

    private boolean flag = false;

    private String ftpConfigDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftpConfig/";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_replacedLE);
        setContentView(R.layout.activity_ftp);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
        toolbar.setreplacedle(R.string.pc_connect);
        toolbar.setreplacedleTextColor(getResources().getColor(R.color.replacedleColor));
        WiFiButton = (Button) findViewById(R.id.wifi_connect_id);
        ApButton = (Button) findViewById(R.id.ap_connect_id);
        ap_name = (TextView) findViewById(R.id.ap_name);
        wifi_replacedle = (TextView) findViewById(R.id.wifi_replacedle);
        tv = (TextView) findViewById(R.id.tvText);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.id_swip_ftp);
        ApButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = !flag;
                setWifiApEnabled(flag);
                if (flag == false) {
                    ap_name.setVisibility(View.GONE);
                    wifi_replacedle.setText(" 确保手机与电脑处于同一WiFi下:");
                    String info = "ftp://" + getLocalIpAddress() + ":2221\n";
                    tv.setText(info);
                }
            }
        });
        WiFiButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
        });
        swipeRefreshLayout.setOnRefreshListener(this);
        String info = "ftp://" + getLocalIpAddress() + ":2221\n";
        tv.setText(info);
        File f = new File(ftpConfigDir);
        if (!f.exists())
            f.mkdir();
        copyResourceFile(R.raw.users, ftpConfigDir + "users.properties");
        Config1();
    }

    public void onRefresh() {
        String info = "ftp://" + getLocalIpAddress() + ":2221\n";
        tv.setText(info);
        swipeRefreshLayout.setRefreshing(false);
    }

    public boolean setWifiApEnabled(boolean enabled) {
        WifiManager wifiManager = null;
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (enabled) {
            // disable WiFi in any case
            // wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi
            wifiManager.setWifiEnabled(false);
        }
        try {
            // 热点的配置类
            WifiConfiguration apConfig = new WifiConfiguration();
            // 配置热点的名称(可以在名字后面加点随机数什么的)
            apConfig.SSID = "用户名";
            // 配置热点的密码
            // 通过反射调用设置热点
            Method method = wifiManager.getClreplaced().getMethod("setWifiApEnabled", WifiConfiguration.clreplaced, Boolean.TYPE);
            ap_name.setText("用户名");
            ap_name.setVisibility(View.VISIBLE);
            wifi_replacedle.setText(" 连接电脑至本机热点:");
            // 返回热点打开状态
            return (Boolean) method.invoke(wifiManager, apConfig, enabled);
        } catch (Exception e) {
            return false;
        }
    }

    public String getLocalIpAddress() {
        String strIP = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        strIP = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("msg", ex.toString());
        }
        return strIP;
    }

    private void copyResourceFile(int rid, String targetFile) {
        InputStream fin = ((Context) this).getResources().openRawResource(rid);
        FileOutputStream fos = null;
        int length;
        try {
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            while ((length = fin.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void Config1() {
        // Now, let's configure the port on which the default listener waits for connections.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        String[] str = { "mkdir", ftpConfigDir };
        try {
            Process ps = Runtime.getRuntime().exec(str);
            try {
                ps.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // "/sdcard/users.properties";
        String filename = ftpConfigDir + "users.properties";
        File files = new File(filename);
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // set the port of the listener
        factory.setPort(2221);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    void Config2() {
        // Now, let's make it possible for a client to use FTPS (FTP over SSL) for the default listener.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        // set the port of the listener
        factory.setPort(2221);
        // define SSL configuration
        SslConfigurationFactory ssl = new SslConfigurationFactory();
        ssl.setKeystoreFile(new File(ftpConfigDir + "ftpserver.jks"));
        ssl.setKeystorePreplacedword("preplacedword");
        // set the SSL configuration for the listener
        factory.setSslConfiguration(ssl.createSslConfiguration());
        factory.setImplicitSsl(true);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(ftpConfigDir + "users.properties"));
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mFtpServer) {
            mFtpServer.stop();
            mFtpServer = null;
        }
    }
}

17 View Complete Implementation : FtpActivity.java
Copyright Apache License 2.0
Author : arno-Lu
public clreplaced FtpActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private FtpServer mFtpServer;

    private Button WiFiButton;

    private Button ApButton;

    private TextView ap_name;

    private TextView wifi_replacedle;

    private TextView tv;

    private SwipeRefreshLayout swipeRefreshLayout;

    private boolean flag = false;

    private String ftpConfigDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftpConfig/";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_replacedLE);
        setContentView(R.layout.activity_ftp);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
        toolbar.setreplacedle(R.string.pc_connect);
        toolbar.setreplacedleTextColor(getResources().getColor(R.color.replacedleColor));
        WiFiButton = (Button) findViewById(R.id.wifi_connect_id);
        ApButton = (Button) findViewById(R.id.ap_connect_id);
        ap_name = (TextView) findViewById(R.id.ap_name);
        wifi_replacedle = (TextView) findViewById(R.id.wifi_replacedle);
        tv = (TextView) findViewById(R.id.tvText);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.id_swip_ftp);
        ApButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = !flag;
                setWifiApEnabled(flag);
                if (!flag) {
                    ap_name.setVisibility(View.GONE);
                    wifi_replacedle.setText(" 确保手机与电脑处于同一WiFi下:");
                    String info = "ftp://" + getLocalIpAddress() + ":2221\n";
                    tv.setText(info);
                }
            }
        });
        WiFiButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
        });
        swipeRefreshLayout.setOnRefreshListener(this);
        String info = "ftp://" + getLocalIpAddress() + ":2221\n";
        tv.setText(info);
        File f = new File(ftpConfigDir);
        if (!f.exists())
            f.mkdir();
        copyResourceFile(R.raw.users, ftpConfigDir + "users.properties");
        Config1();
    }

    public void onRefresh() {
        String info = "ftp://" + getLocalIpAddress() + ":2221\n";
        tv.setText(info);
        swipeRefreshLayout.setRefreshing(false);
    }

    public boolean setWifiApEnabled(boolean enabled) {
        WifiManager wifiManager = null;
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (enabled) {
            // disable WiFi in any case
            // wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi
            wifiManager.setWifiEnabled(false);
        }
        try {
            // 热点的配置类
            WifiConfiguration apConfig = new WifiConfiguration();
            // 配置热点的名称(可以在名字后面加点随机数什么的)
            apConfig.SSID = "快传";
            final Myapplication Date = (Myapplication) getApplication();
            if (Date.getName().equals("")) {
                apConfig.SSID = Date.getName();
            }
            // 配置热点的密码
            // 通过反射调用设置热点
            Method method = wifiManager.getClreplaced().getMethod("setWifiApEnabled", WifiConfiguration.clreplaced, Boolean.TYPE);
            ap_name.setText("用户名");
            ap_name.setVisibility(View.VISIBLE);
            wifi_replacedle.setText(" 连接电脑至本机热点:");
            // 返回热点打开状态
            return (Boolean) method.invoke(wifiManager, apConfig, enabled);
        } catch (Exception e) {
            return false;
        }
    }

    public String getLocalIpAddress() {
        String strIP = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        strIP = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("msg", ex.toString());
        }
        return strIP;
    }

    private void copyResourceFile(int rid, String targetFile) {
        InputStream fin = ((Context) this).getResources().openRawResource(rid);
        FileOutputStream fos = null;
        int length;
        try {
            fos = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            while ((length = fin.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void Config1() {
        // Now, let's configure the port on which the default listener waits for connections.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        String[] str = { "mkdir", ftpConfigDir };
        try {
            Process ps = Runtime.getRuntime().exec(str);
            try {
                ps.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // "/sdcard/users.properties";
        String filename = ftpConfigDir + "users.properties";
        File files = new File(filename);
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // set the port of the listener
        factory.setPort(2221);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    void Config2() {
        // Now, let's make it possible for a client to use FTPS (FTP over SSL) for the default listener.
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();
        // set the port of the listener
        factory.setPort(2221);
        // define SSL configuration
        SslConfigurationFactory ssl = new SslConfigurationFactory();
        ssl.setKeystoreFile(new File(ftpConfigDir + "ftpserver.jks"));
        ssl.setKeystorePreplacedword("preplacedword");
        // set the SSL configuration for the listener
        factory.setSslConfiguration(ssl.createSslConfiguration());
        factory.setImplicitSsl(true);
        // replace the default listener
        serverFactory.addListener("default", factory.createListener());
        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(ftpConfigDir + "users.properties"));
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // start the server
        FtpServer server = serverFactory.createServer();
        this.mFtpServer = server;
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mFtpServer) {
            mFtpServer.stop();
            mFtpServer = null;
        }
    }
}

17 View Complete Implementation : FtpService.java
Copyright GNU General Public License v3.0
Author : structr
/**
 */
@ServiceDependency(SchemaService.clreplaced)
public clreplaced FtpService implements RunnableService {

    private static final Logger logger = LoggerFactory.getLogger(FtpService.clreplaced.getName());

    private boolean isRunning = false;

    private static int port;

    private FtpServer server;

    @Override
    public void startService() throws Exception {
        FtpServerFactory serverFactory = new FtpServerFactory();
        serverFactory.setUserManager(new StructrUserManager());
        serverFactory.setFileSystem(new StructrFileSystemFactory());
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(port);
        serverFactory.addListener("default", factory.createListener());
        logger.info("Starting FTP server on port {}", new Object[] { String.valueOf(port) });
        server = serverFactory.createServer();
        server.start();
        this.isRunning = true;
    }

    @Override
    public void stopService() {
        if (isRunning) {
            this.shutdown();
        }
    }

    @Override
    public boolean runOnStartup() {
        return true;
    }

    @Override
    public boolean isRunning() {
        return !server.isStopped();
    }

    @Override
    public void injectArguments(Command command) {
    }

    @Override
    public boolean initialize(final StructrServices services) throws ClreplacedNotFoundException, InstantiationException, IllegalAccessException {
        port = Settings.FtpPort.getValue();
        return true;
    }

    @Override
    public void initialized() {
    }

    @Override
    public void shutdown() {
        if (!server.isStopped()) {
            server.stop();
            this.isRunning = false;
        }
    }

    @Override
    public String getName() {
        return FtpServer.clreplaced.getSimpleName();
    }

    @Override
    public boolean isVital() {
        return false;
    }

    @Override
    public boolean waitAndRetry() {
        return false;
    }

    // ----- interface Feature -----
    @Override
    public String getModuleName() {
        return "file-access";
    }
}

16 View Complete Implementation : AddUser.java
Copyright Apache License 2.0
Author : apache
/**
 * Used to add users to the user manager for a particular FtpServer configuration
 *
 * @param args
 *            The first element of this array must specify the kind of
 *            configuration to be used to start the server.
 */
public static void main(String[] args) {
    AddUser addUser = new AddUser();
    try {
        // get configuration
        FtpServer server = addUser.getConfiguration(args);
        if (server == null) {
            return;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        UserManager um = ((DefaultFtpServer) server).getUserManager();
        BaseUser user = new BaseUser();
        System.out.println("Asking for details of the new user");
        System.out.println();
        String userName = askForString(in, "User name:", "User name is mandatory");
        if (userName == null) {
            return;
        }
        user.setName(userName);
        user.setPreplacedword(askForString(in, "Preplacedword:"));
        String home = askForString(in, "Home directory:", "Home directory is mandatory");
        if (home == null) {
            return;
        }
        user.setHomeDirectory(home);
        user.setEnabled(askForBoolean(in, "Enabled (Y/N):"));
        user.setMaxIdleTime(askForInt(in, "Max idle time in seconds (0 for none):"));
        List<Authority> authorities = new ArrayList<Authority>();
        if (askForBoolean(in, "Write permission (Y/N):")) {
            authorities.add(new WritePermission());
        }
        int maxLogins = askForInt(in, "Maximum number of concurrent logins (0 for no restriction)");
        int maxLoginsPerIp = askForInt(in, "Maximum number of concurrent logins per IP (0 for no restriction)");
        authorities.add(new ConcurrentLoginPermission(maxLogins, maxLoginsPerIp));
        int downloadRate = askForInt(in, "Maximum download rate (0 for no restriction)");
        int uploadRate = askForInt(in, "Maximum upload rate (0 for no restriction)");
        authorities.add(new TransferRatePermission(downloadRate, uploadRate));
        user.setAuthorities(authorities);
        um.save(user);
        if (um instanceof PropertiesUserManager) {
            File file = ((PropertiesUserManager) um).getFile();
            if (file != null) {
                System.out.println("User saved to file: " + file.getAbsolutePath());
            } else {
                System.err.println("User manager does not have a file configured, will not save user to file");
            }
        } else {
            System.out.println("User saved");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

16 View Complete Implementation : CommandLine.java
Copyright Apache License 2.0
Author : apache
/**
 * Get the configuration object.
 */
protected FtpServer getConfiguration(String[] args) throws Exception {
    FtpServer server = null;
    if (args.length == 0) {
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("-default")) {
        // supported for backwards compatibility, but not doreplacedented
        System.out.println("The -default switch is deprecated, please use --default instead");
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--default")) {
        System.out.println("Using default configuration");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 1) && args[0].equals("--help")) {
        usage();
    } else if ((args.length == 1) && args[0].equals("-?")) {
        usage();
    } else if (args.length == 1) {
        System.out.println("Using XML configuration file " + args[0] + "...");
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(args[0]);
        if (ctx.containsBean("server")) {
            server = (FtpServer) ctx.getBean("server");
        } else {
            String[] beanNames = ctx.getBeanNamesForType(FtpServer.clreplaced);
            if (beanNames.length == 1) {
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else if (beanNames.length > 1) {
                System.out.println("Using the first server defined in the configuration, named " + beanNames[0]);
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else {
                System.err.println("XML configuration does not contain a server configuration");
            }
        }
    } else {
        usage();
    }
    return server;
}

16 View Complete Implementation : Daemon.java
Copyright Apache License 2.0
Author : apache
/**
 * Get the configuration object.
 */
private static FtpServer getConfiguration(String[] args) throws Exception {
    FtpServer server = null;
    if (args == null || args.length < 2) {
        LOG.info("Using default configuration....");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 2) && args[1].equals("-default")) {
        // supported for backwards compatibility, but not doreplacedented
        System.out.println("The -default switch is deprecated, please use --default instead");
        LOG.info("Using default configuration....");
        server = new FtpServerFactory().createServer();
    } else if ((args.length == 2) && args[1].equals("--default")) {
        LOG.info("Using default configuration....");
        server = new FtpServerFactory().createServer();
    } else if (args.length == 2) {
        LOG.info("Using xml configuration file " + args[1] + "...");
        FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(args[1]);
        if (ctx.containsBean("server")) {
            server = (FtpServer) ctx.getBean("server");
        } else {
            String[] beanNames = ctx.getBeanNamesForType(FtpServer.clreplaced);
            if (beanNames.length == 1) {
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else if (beanNames.length > 1) {
                System.out.println("Using the first server defined in the configuration, named " + beanNames[0]);
                server = (FtpServer) ctx.getBean(beanNames[0]);
            } else {
                System.err.println("XML configuration does not contain a server configuration");
            }
        }
    } else {
        throw new FtpException("Invalid configuration option");
    }
    return server;
}

16 View Complete Implementation : FtpServerListener.java
Copyright Apache License 2.0
Author : apache
public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("Stopping FtpServer");
    FtpServer server = (FtpServer) sce.getServletContext().getAttribute(FTPSERVER_CONTEXT_NAME);
    if (server != null) {
        server.stop();
        sce.getServletContext().removeAttribute(FTPSERVER_CONTEXT_NAME);
        System.out.println("FtpServer stopped");
    } else {
        System.out.println("No running FtpServer found");
    }
}

16 View Complete Implementation : TestFTPFileSystem.java
Copyright Apache License 2.0
Author : facebookarchive
/**
 * Generates a bunch of random files and directories using clreplaced 'DFSTestUtil',
 * stores them on the FTP file system, copies them and check if all the files
 * were retrieved successfully without any data corruption
 */
public clreplaced TestFTPFileSystem extends TestCase {

    private Configuration defaultConf = new JobConf();

    private FtpServer server = null;

    private FileSystem localFs = null;

    private FileSystem ftpFs = null;

    private Path workDir = new Path(new Path(System.getProperty("test.build.data", "."), "data"), "TestFTPFileSystem");

    Path ftpServerRoot = new Path(workDir, "FTPServer");

    Path ftpServerConfig = null;

    private void startServer() {
        try {
            DefaultFtpServerContext context = new DefaultFtpServerContext(false);
            MinaListener listener = new MinaListener();
            // Set port to 0 for OS to give a free port
            listener.setPort(0);
            context.setListener("default", listener);
            // Create a test user.
            UserManager userManager = context.getUserManager();
            BaseUser adminUser = new BaseUser();
            adminUser.setName("admin");
            adminUser.setPreplacedword("admin");
            adminUser.setEnabled(true);
            adminUser.setAuthorities(new Authority[] { new WritePermission() });
            Path adminUserHome = new Path(ftpServerRoot, "user/admin");
            adminUser.setHomeDirectory(adminUserHome.toUri().getPath());
            adminUser.setMaxIdleTime(0);
            userManager.save(adminUser);
            // Initialize the server and start.
            server = new FtpServer(context);
            server.start();
        } catch (Exception e) {
            throw new RuntimeException("FTP server start-up failed", e);
        }
    }

    private void stopServer() {
        if (server != null) {
            server.stop();
        }
    }

    @Override
    public void setUp() throws Exception {
        startServer();
        defaultConf = new Configuration();
        localFs = FileSystem.getLocal(defaultConf);
        ftpServerConfig = new Path(localFs.getWorkingDirectory(), "res");
        MinaListener listener = (MinaListener) server.getServerContext().getListener("default");
        int serverPort = listener.getPort();
        ftpFs = FileSystem.get(URI.create("ftp://admin:admin@localhost:" + serverPort), defaultConf);
    }

    @Override
    public void tearDown() throws Exception {
        localFs.delete(ftpServerRoot, true);
        localFs.delete(ftpServerConfig, true);
        localFs.close();
        ftpFs.close();
        stopServer();
    }

    /**
     * Tests FTPFileSystem, create(), open(), delete(), mkdirs(), rename(),
     * listStatus(), getStatus() APIs. *
     *
     * @throws Exception
     */
    public void testReadWrite() throws Exception {
        DFSTestUtil util = new DFSTestUtil("TestFTPFileSystem", 20, 3, 1024 * 1024);
        localFs.setWorkingDirectory(workDir);
        Path localData = new Path(workDir, "srcData");
        Path remoteData = new Path("srcData");
        util.createFiles(localFs, localData.toUri().getPath());
        boolean dataConsistency = util.checkFiles(localFs, localData.getName());
        replacedertTrue("Test data corrupted", dataConsistency);
        // Copy files and directories recursively to FTP file system.
        boolean filesCopied = FileUtil.copy(localFs, localData, ftpFs, remoteData, false, defaultConf);
        replacedertTrue("Copying to FTPFileSystem failed", filesCopied);
        // Rename the remote copy
        Path renamedData = new Path("Renamed");
        boolean renamed = ftpFs.rename(remoteData, renamedData);
        replacedertTrue("Rename failed", renamed);
        // Copy files and directories from FTP file system and delete remote copy.
        filesCopied = FileUtil.copy(ftpFs, renamedData, localFs, workDir, true, defaultConf);
        replacedertTrue("Copying from FTPFileSystem fails", filesCopied);
        // Check if the data was received completely without any corruption.
        dataConsistency = util.checkFiles(localFs, renamedData.getName());
        replacedertTrue("Invalid or corrupted data recieved from FTP Server!", dataConsistency);
        // Delete local copies
        boolean deleteSuccess = localFs.delete(renamedData, true) & localFs.delete(localData, true);
        replacedertTrue("Local test data deletion failed", deleteSuccess);
    }
}

16 View Complete Implementation : GeoBatchServer.java
Copyright GNU General Public License v3.0
Author : geosolutions-it
public clreplaced GeoBatchServer implements InitializingBean, ApplicationListener<ApplicationEvent> {

    private final static Logger LOGGER = LoggerFactory.getLogger(GeoBatchServer.clreplaced);

    private FtpServer ftpServer;

    private FtpServerConfig lastConfig;

    private FtpServerConfigDAO serverConfigDAO;

    private GeoBatchUserManager userManager;

    public void afterPropertiesSet() throws Exception {
        setLastConfig(serverConfigDAO.load());
        userManager.setServerConfig(getLastConfig());
        ftpServer = create(getLastConfig(), userManager);
        if (getLastConfig().isAutoStart())
            ftpServer.start();
    }

    public static FtpServer create(FtpServerConfig config, UserManager userManager) {
        // base configuration
        final FtpServerFactory serverFactory = new FtpServerFactory();
        final ConnectionConfigFactory configFactory = new ConnectionConfigFactory();
        configFactory.setAnonymousLoginEnabled(config.isAnonEnabled());
        configFactory.setLoginFailureDelay(config.getLoginFailureDelay());
        configFactory.setMaxAnonymousLogins(config.getMaxAnonLogins());
        configFactory.setMaxLoginFailures(config.getMaxLoginFailures());
        configFactory.setMaxLogins(config.getMaxLogins());
        serverFactory.setConnectionConfig(configFactory.createConnectionConfig());
        // change port
        final ListenerFactory factory = new ListenerFactory();
        factory.setPort(config.getPort());
        factory.setImplicitSsl(config.isSsl());
        serverFactory.addListener("default", factory.createListener());
        // user management
        serverFactory.setUserManager(userManager);
        // callback
        final Map<String, Ftplet> map = new HashMap<String, Ftplet>();
        map.put("GB-Ftplet", new GeoBatchFtplet());
        serverFactory.setFtplets(map);
        return serverFactory.createServer();
    }

    public void suspend() {
        if (ftpServer != null) {
            ftpServer.suspend();
        }
    }

    public void stop() {
        if (ftpServer != null) {
            ftpServer.stop();
        }
    }

    public synchronized void start() throws FtpException {
        if (!ftpServer.isStopped()) {
            LOGGER.warn("FTP server is already running and will not be started again.");
            return;
        }
        try {
            FtpServerConfig config = serverConfigDAO.load();
            if (true) {
                // !config.equals(lastConfig)) {
                // config has changed: recreate server with new config
                setLastConfig(config);
                userManager.setServerConfig(getLastConfig());
                ftpServer = create(getLastConfig(), userManager);
            }
            ftpServer.start();
        } catch (DAOException ex) {
            LOGGER.warn("Could not retrieve server config. Using old server instance", ex);
        }
    }

    public void resume() {
        if (ftpServer != null) {
            ftpServer.resume();
        }
    }

    public boolean isSuspended() {
        if (ftpServer != null) {
            return ftpServer.isSuspended();
        }
        return false;
    }

    public boolean isStopped() {
        if (ftpServer != null) {
            return ftpServer.isStopped();
        }
        return true;
    }

    public FtpServerConfig getLastConfig() {
        return lastConfig.clone();
    }

    /**
     * @param lastConfig
     *            the lastConfig to set
     * @throws DAOException
     */
    public void setLastConfig(FtpServerConfig lastConfig) throws DAOException {
        this.lastConfig = serverConfigDAO.load();
    }

    /**
     * @param ftpServer
     *            the ftpServer to set
     */
    public void setFtpServer(FtpServer ftpServer) {
        this.ftpServer = ftpServer;
    }

    /**
     * @return the ftpServer
     */
    public synchronized FtpServer getFtpServer() {
        return ftpServer;
    }

    public FtpServerConfigDAO getServerConfigDAO() {
        return serverConfigDAO;
    }

    public void setServerConfigDAO(FtpServerConfigDAO serverConfigDAO) {
        this.serverConfigDAO = serverConfigDAO;
    }

    public void setUserManager(GeoBatchUserManager userManager) {
        this.userManager = userManager;
    }

    public GeoBatchUserManager getUserManager() {
        return userManager;
    }

    /**
     * Dispose all the handled flow managers on container stop/shutdown
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event.getClreplaced().isreplacedignableFrom(ContextClosedEvent.clreplaced) || event.getClreplaced().isreplacedignableFrom(ContextStoppedEvent.clreplaced)) {
            this.stop();
        }
    }
}

16 View Complete Implementation : FTPServer.java
Copyright Apache License 2.0
Author : grycap
public clreplaced FTPServer {

    public static int MAX_FTP_USERS = 100;

    public static int DEFAULT_FTP_PORT = 21000;

    public static String FTP_USERS_FILE = "users.properties";

    private int numConnections;

    private String host;

    private FtpServerFactory serverFactory;

    private PropertiesUserManagerFactory userManagerFactory;

    private UserManager userManager;

    private FtpServer server;

    private Logger log;

    public FTPServer() throws IOException {
        this.log = Logger.getLogger(getClreplaced());
        this.numConnections = 0;
        if (this.serverFactory == null)
            this.serverFactory = configureFtpServerFactory();
    }

    private String selectNewUser() {
        String newUser = null;
        for (int i = 0; i < MAX_FTP_USERS; i++) {
            try {
                newUser = "user" + i;
                if (!userManager.doesExist(newUser))
                    break;
            } catch (FtpException e) {
                log.error("Error reading user file from FTP server.");
                return null;
            }
            if (i == MAX_FTP_USERS - 1) {
                log.error("Maximum number of users exceeded.");
                return null;
            }
        }
        return newUser;
    }

    public void deleteNewUser(String user) throws FtpException {
        if (userManager.doesExist(user))
            userManager.delete(user);
    }

    /**
     * Create
     * @param vmiName The name of the VMI
     * @param vmiFileName The filename of the VMI (to be uploaded or retrieved)
     * @param type The type of connection (upload, download) (@see FTPSession)
     * @return
     */
    public FTPTransferParams createOnTheFlyFTPConfiguration(String vmiName, String vmiFileName, int type) throws FtpException {
        log.debug("Creating on-the-fly FTP configuration");
        FTPTransferParams tp = new FTPTransferParams();
        BaseUser user = new BaseUser();
        String filePath, msg;
        String newUser = selectNewUser();
        if (newUser == null) {
            msg = "Error creating new user.";
            log.error(msg);
            throw new FtpException(msg);
        }
        // Create a temporary user in the FTP server.
        user.setName(newUser);
        String newPreplacedword = VMRCServerUtils.generateRandomChain(8);
        user.setPreplacedword(newPreplacedword);
        if (type == FTPSession.TYPE_UPLOAD) {
            filePath = RepositoryManager.getRepositoryLocationToStoreFile(vmiName, vmiFileName);
            log.debug("Creating the appropriate dirs to host file: " + vmiFileName);
            new File(filePath).getParentFile().mkdirs();
            user.setHomeDirectory(new File(filePath).getParent());
            List<Authority> auths = new ArrayList<Authority>();
            Authority auth = new WritePermission();
            auths.add(auth);
            user.setAuthorities(auths);
        } else {
            // DOWNLOAD
            String[] files = VMRCServerUtils.listDirectory(RepositoryManager.getRepositoryLocationForVMI(vmiName));
            if (files == null) {
                msg = "No file in the repository found for VMI " + vmiName;
                log.error(msg);
                throw new FtpException(msg);
            }
            log.debug("Found " + files.length + " related to " + vmiName + " in the repository. Will pick the first one.");
            filePath = RepositoryManager.getRepositoryLocationToStoreFile(vmiName, files[0]);
            log.debug("Obtained file " + filePath);
        }
        try {
            // Store the user into users.properties file
            userManager.save(user);
        } catch (FtpException e) {
            deleteNewUser(newUser);
        }
        tp.setUser(newUser);
        tp.setPreplaced(newPreplacedword);
        tp.setPath(filePath);
        tp.setHost(this.host);
        tp.setPort(DEFAULT_FTP_PORT);
        return tp;
    }

    private void startServerInternal() throws FtpException {
        log.info("Creating FTP server.");
        if (server == null) {
            log.debug("Creating and starting FtpServer instance");
            server = serverFactory.createServer();
            server.start();
        }
        log.info("Resuming already existing FTP server instance.");
        server.resume();
        log.info("Available FTP server: " + server);
    }

    /**
     * @param args
     */
    public void suspendServerInternal() {
        server.suspend();
    }

    /**
     * @param args
     */
    public synchronized void notifyEndOfTransfer() {
        numConnections--;
        log.debug("Finalizing FTP session. (" + numConnections + ") active sessions");
        // TODO Removed created user
        if (numConnections == 0) {
            log.debug("No active FTP sessions. Suspending FTP server.");
            suspendServerInternal();
        }
    }

    /**
     * @param args
     * @throws FtpException
     */
    public synchronized void notifyStartOfTransfer() throws FtpException {
        if (numConnections == 0) {
            log.debug("Initiating first FTP session. Starting up the FTP server.");
            startServerInternal();
            numConnections++;
        }
    }

    /**
     * @param args
     * @throws IOException
     */
    public FtpServerFactory configureFtpServerFactory() throws IOException {
        FtpServerFactory fsf = new FtpServerFactory();
        log.info("Configuring an on-the-fly FTP server.");
        String ftpUsersFilePath = null;
        File fFTPServerUserFile = null;
        ftpUsersFilePath = RepositoryManager.getRepositoryLocation() + File.separator + "conf" + File.separator + FTP_USERS_FILE;
        log.debug("Creating FTP users file at " + ftpUsersFilePath);
        fFTPServerUserFile = new File(ftpUsersFilePath);
        fFTPServerUserFile.mkdirs();
        fFTPServerUserFile.delete();
        fFTPServerUserFile.createNewFile();
        final Map<String, Ftplet> ftpletMap = new HashMap<String, Ftplet>();
        Ftplet ftplet = new ConfFtplet(this);
        ftpletMap.put("default", ftplet);
        fsf.setFtplets(ftpletMap);
        userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setFile(new File(ftpUsersFilePath));
        userManagerFactory.setPreplacedwordEncryptor(new Md5PreplacedwordEncryptor());
        userManager = userManagerFactory.createUserManager();
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(DEFAULT_FTP_PORT);
        fsf.addListener("default", listenerFactory.createListener());
        fsf.setUserManager(userManager);
        // Inicializar host ip.
        this.host = VMRCServerUtils.getPublicIP();
        return fsf;
    }
}

16 View Complete Implementation : HdfsOverFtpServer.java
Copyright MIT License
Author : iponweb
/**
 * Starts FTP server
 *
 * @throws Exception
 */
public static void startServer() throws Exception {
    log.info("Starting Hdfs-Over-Ftp server. port: " + port + " data-ports: " + preplacedivePorts + " hdfs-uri: " + hdfsUri);
    HdfsOverFtpSystem.setHDFS_URI(hdfsUri);
    FtpServer server = new FtpServer();
    DataConnectionConfiguration dataCon = new DefaultDataConnectionConfiguration();
    dataCon.setPreplacedivePorts(preplacedivePorts);
    server.getListener("default").setDataConnectionConfiguration(dataCon);
    server.getListener("default").setPort(port);
    HdfsUserManager userManager = new HdfsUserManager();
    final File file = loadResource("/users.properties");
    userManager.setFile(file);
    server.setUserManager(userManager);
    server.setFileSystem(new HdfsFileSystemManager());
    server.start();
}

16 View Complete Implementation : HdfsOverFtpServer.java
Copyright MIT License
Author : iponweb
/**
 * Starts SSL FTP server
 *
 * @throws Exception
 */
public static void startSSLServer() throws Exception {
    log.info("Starting Hdfs-Over-Ftp SSL server. ssl-port: " + sslPort + " ssl-data-ports: " + sslPreplacedivePorts + " hdfs-uri: " + hdfsUri);
    HdfsOverFtpSystem.setHDFS_URI(hdfsUri);
    FtpServer server = new FtpServer();
    DataConnectionConfiguration dataCon = new DefaultDataConnectionConfiguration();
    dataCon.setPreplacedivePorts(sslPreplacedivePorts);
    server.getListener("default").setDataConnectionConfiguration(dataCon);
    server.getListener("default").setPort(sslPort);
    MySslConfiguration ssl = new MySslConfiguration();
    ssl.setKeystoreFile(new File("ftp.jks"));
    ssl.setKeystoreType("JKS");
    ssl.setKeyPreplacedword("333333");
    server.getListener("default").setSslConfiguration(ssl);
    server.getListener("default").setImplicitSsl(true);
    HdfsUserManager userManager = new HdfsUserManager();
    userManager.setFile(new File("users.conf"));
    server.setUserManager(userManager);
    server.setFileSystem(new HdfsFileSystemManager());
    server.start();
}