Java – Connect to FTP Server

import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;

public class FtpConnectDemo {

	public static void main(String[] args) {
		FTPClient client = new FTPClient();

		client.connect("ftp.domain.com");
		boolean login = client.login("admin", "secret");

		if (login) {
			System.out.println("Login success...");
			boolean logout = client.logout();
			if (logout) {
				System.out.println("Logout from FTP server...");
			}
		} else {
			System.out.println("Login fail...");
		}
		client.disconnect();
	}

}

Java – Generate Random alpha-numeric String

The code below show you how to use the apache commons RandomStringUtils class to generate some random string data.

import org.apache.commons.lang.RandomStringUtils;

public class RandomStringUtilsDemo {

	public static void main(String[] args) {
		//
		// Creates a 64 chars length random string of number.
		//
		String result = RandomStringUtils.random(64, false, true);
		System.out.println("random = " + result);

		//
		// Creates a 64 chars length of random alphabetic string.
		//
		result = RandomStringUtils.randomAlphabetic(64);
		System.out.println("random = " + result);

		//
		// Creates a 32 chars length of random ascii string.
		//
		result = RandomStringUtils.randomAscii(32);
		System.out.println("random = " + result);

		//
		// Creates a 32 chars length of string from the defined array of
		// characters including numeric and alphabetic characters.
		//
		result = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
		System.out.println("random = " + result);
	}

}

Output:

random = 2377316738997278218735578855577798247976319451877477254850564896
random = wwqbLxlRynIdptAoxuSIfbABRoOFHLyKaFEscrUoBQjAHPOkcIqfHuMnhXVzaLCf
random = 6nQ0PJf<#VgIi=’&d`*`Ru#i_exMoHXb
random = ZGbelXYEiLrlLBXKroCIDJPrevZPIGkD

Java – Convert Array to Map using Commons ArrayUtils

This example use the Apache Commons lang’s ArrayUtils class to convert a two dimensional array to a Map object.

import java.util.Map;
import org.apache.commons.lang.ArrayUtils;

public class ArrayToMapExample {

	public static void main(String[] args) {
		//
		// A two dimensional array of countries capital.
		//
		String[][] countries = {{"United States", "New York"},
				{"United Kingdom", "London"},
				{"Netherlands", "Amsterdam"},
				{"Japan", "Tokyo"},
				{"France", "Paris"}};

		//
		// To convert an array to a Map each array elements must
		// be an array with at least two elements where the first
		// element will be the key and the second element will be
		// the value.
		//
		Map countryCapitals = ArrayUtils.toMap(countries);

		System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
		System.out.println("Capital of France is " + countryCapitals.get("France"));
	}

}

Page 1 of 3123