Parse a date in java
A simple class that parses a date given in finnish formats d.m.yyyy, dd.mm.yyyy and ddmmyyyy.
1 import java.text.SimpleDateFormat; 2 import java.util.Calendar; 3 import java.util.Date; 4 5 public class DateParser { 6 7 Calendar calendar = null; 8 9 public DateParser(String dateAsString) { 10 if ( dateAsString == null || dateAsString.length() < 8 ) { 11 throw new RuntimeException("String must be at least 8 characters long and in one of these formats: ddmmyyyy | d.m.yyyy | dd.mm.yyyy"); 12 } 13 dateAsString = dateAsString.replaceAll("\\.",""); 14 String parseString = "ddMMyyyy"; 15 if ( dateAsString.length() < 8 ) { 16 parseString="dMyyyy"; 17 } 18 try { 19 Date date = new SimpleDateFormat(parseString).parse(dateAsString); 20 calendar = Calendar.getInstance(); 21 calendar.setTime(date); 22 } catch (Exception e) { 23 throw new RuntimeException("String must be at least 8 characters long and in one of these formats: ddmmyyyy | d.m.yyyy | dd.mm.yyyy",e); 24 } 25 } 26 27 public int getDayOfMonth() { 28 return calendar.get(Calendar.DATE); 29 } 30 31 public int getMonth() { 32 return calendar.get(Calendar.MONTH) + 1; 33 } 34 35 public int getYear() { 36 return calendar.get(Calendar.YEAR); 37 } 38 39 public Calendar getTime() { 40 return calendar; 41 } 42 43 } 44
Paginating a list in Java
Not fully tested, but the idea works.
1 List list = ....; // Example: page size is 5 2 int originalSize = list.size(); // original size: 24 3 int start = Math.min(list.size(), Math.abs(currentPage * pageSize)); // start: 5 4 list.subList(0, start).clear(); // list now contains: 5, 6, 7, 8, 9,..., 23 5 6 int size = list.size(); // size is now: min(listSize, originalSize - pageSize) = 19 7 int end = Math.min(pageSize, size); // end: 5 8 list.subList(end, size).clear(); // list now contains: 5, 6, 7, 8, 9 9 10 boolean hasNext = (end < size); // has next: 5 < 19 11 boolean hasPrevious = (start > 0); // has previous: 5 > 0
Generating a password in Java
A simple password generator class.
1 /** 2 * Simple password generator. 3 * 4 * @author marko haapala at aktagon com 5 */ 6 public class PasswordGenerator { 7 public static final char[] HEX_CHARS = { 'a','b','c','d','e','f','g','h','0','1','2','3','4','5','6','7','8','9' }; 8 public static final char[] SECURE_CHARS = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u', 9 'v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 10 'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','=', 11 '!','"','#','¤','%','&','/','(',')' }; 12 /** 13 * Generates an eight characters long password consisting of hexadecimal characters. 14 * 15 * @return the generated password 16 */ 17 public static String generate() { 18 return generate(HEX_CHARS, 8); 19 } 20 21 /** 22 * Generates a password consisting of hexadecimal characters. 23 * 24 * @param length of the password 25 * @return the generated password 26 */ 27 public static String generate(final int length) { 28 return generate(HEX_CHARS, length); 29 } 30 31 /** 32 * Generates a password according to the given parameters. 33 * 34 * @param characters that make up the password 35 * @param length of the password 36 * @return the generated password 37 */ 38 public static String generate(final char[] characters, final int length) { 39 RandomString randomString = new RandomString(PseudoRandom.getRandom(), characters); 40 return randomString.getString(length); 41 } 42 } 43
Validating an email address in Java
The source of the regexp is this site: Email unlimited. According to Wikipedia the regexp on the source page validates the email address according to RFC 2822 – Internet Message Format. I have still to write a comprehensive test suite, but the tests I do have for this validator pass.
1 public class EmailValidator { 2 public static boolean validate(final String emailAddress) { 3 if ( emailAddress == null ) return false; 4 String patternStr = "^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$"; 5 Pattern emailPattern = Pattern.compile(patternStr); 6 return emailPattern.matcher(emailAddress).matches(); 7 } 8 }
Unit testing of DAO's
This “snippet” explains how to unit test DAO ’s outside of a J2EE container. This is a bit bigger than a snippet, but worth so much. Some Spring magic could also be used, but I’m not polluting this example with xml in fear of it getting too tedious and complicated to understand.
DAO
Your DAO needs a protected constructor that takes a ConnectionFactory as parameter. You also need to modify your DAO ’s getConnection() method as shown below.
1 public class UserDAO { 2 // irrelevant elements of DAO left out for brevity 3 protected UserDAO(ConnectionFactory connectionFactory) { 4 this.connectionFactory = connectionFactory; 5 } 6 private Connection getConnection() { 7 // modify getConnection() logic. test if we have been 8 // given a ConnectionFactory or not. If we have then 9 // return a connection from there. 10 if ( this.connectionFactory != null ) { 11 return this.connectionFactory.getConnection(); 12 } 13 // else return the connection from JNDI 14 } 15 }
ConnectionFactory interface
We need to define a ConnectionFactory interface.
1 public interface ConnectionFactory { 2 Connection getConnection(); 3 }
ConnectionFactory implementation
We need an implementation of our ConnectionFactory.
1 public class JdbcConnectionFactory implements ConnectionFactory { 2 // exception handling removed for brevity 3 private String username, password, host, databaseName; 4 public JdbcConnectionFactory(String username, String password, String host, String databaseName) { 5 this.username = username; 6 this.password = password; 7 this.host = host; 8 this.databaseName = databaseName; 9 } 10 public Connection getConnection() { 11 // set up a jdbc connection and return it. mind the code, our concern 12 // is not about performance here. 13 Class.forName("oracle.jdbc.driver.OracleDriver"); 14 String connectionUrl = "jdbc:oracle:thin:@"+host+":1544:"+databaseName; 15 DriverManager.getConnection(connectionUrl, username, passwd); 16 } 17 }
Base class for DAO testing
Then we set up the base class for our DAO unit tests.
1 public class DaoTestBase extends TestCase { 2 protected ConnectionFactory getConnectionFactory() { 3 return new JdbcConnectionFactory("ora","ora123","hostnameOfMyDatabaseServer","myDb"); 4 } 5 }
DAO test class
Finally we write the test case itself.
1 public class UserDAOTest extends DaoTestBase { 2 private UserDAO userDao; 3 public void setUp() { 4 super.setUp(); 5 this.userDao = new UserDAO(getConnectionFactory()); 6 } 7 public void testFindByUsernameShouldReturnExactlyOneUser() { 8 String username = "marko"; 9 User user = userDao.create(username); 10 userDao.save(user); 11 assertEquals(1, userDao.findByUsername(username).size()); 12 } 13 }
Caveats
Never, ever use the protected constructor in production code! Its sole purpose is to enable a simple jdbc connection that can be used in unit tests. The production code gets a bit polluted (one import and seven LOC ), but it’s a really small sacrifice for such a great cause.