Java Servlet – Logging with Log4j Example

[code lang=”java”]import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import org.apache.log4j.*;

public class LoggingServlet extends HttpServlet {

private static Logger logger = Logger.getLogger(LoggingServlet.class);

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
logger.info("invoked the LoggingServlet…");
PrintWriter writer = res.getWriter();
writer.println("Check your web server console…");
writer.flush();
writer.close();
}

}[/code]

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.

[code lang=”java”]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);
}

}[/code]

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.

[code lang=”java”]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"));
}

}[/code]