java snippets

Decompile Java code with JAD

Tagged jad, java, decompile  Languages bash

How to decompile Java source code and include original line numbers with JAD:

jad -pi -b -ff -space -lnc -s java -d output_directory -r directory_containing_class_files\**\*.class

Unit testing of DAO's

Tagged dao, unit testing, jdbc, java  Languages java

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.

public class UserDAO {
  // irrelevant elements of DAO left out for brevity
  protected UserDAO(ConnectionFactory connectionFactory) {
    this.connectionFactory = connectionFactory;
  }
  private Connection getConnection() {
    // modify getConnection() logic. test if we have been
    // given a ConnectionFactory or not. If we have then
    // return a connection from there.
    if ( this.connectionFactory != null ) {
      return this.connectionFactory.getConnection();
    }
    // else return the connection from JNDI
  }
}

ConnectionFactory interface

We need to define a ConnectionFactory interface.

public interface ConnectionFactory {
  Connection getConnection();
}

ConnectionFactory implementation

We need an implementation of our ConnectionFactory.

public class JdbcConnectionFactory implements ConnectionFactory {
  // exception handling removed for brevity
  private String username, password, host, databaseName;
  public JdbcConnectionFactory(String username, String password, String host, String databaseName) {
    this.username = username;
    this.password = password;
    this.host = host;
    this.databaseName = databaseName;
  }
  public Connection getConnection() {
    // set up a jdbc connection and return it. mind the code, our concern 
    // is not about performance here.
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String connectionUrl = "jdbc:oracle:thin:@"+host+":1544:"+databaseName;
    DriverManager.getConnection(connectionUrl, username, passwd);
  }
}

Base class for DAO testing

Then we set up the base class for our DAO unit tests.

public class DaoTestBase extends TestCase {
  protected ConnectionFactory getConnectionFactory() {
    return new JdbcConnectionFactory("ora","ora123","hostnameOfMyDatabaseServer","myDb");
  }
}

DAO test class

Finally we write the test case itself.

public class UserDAOTest extends DaoTestBase {
  private UserDAO userDao;
  public void setUp() {
    super.setUp();
    this.userDao = new UserDAO(getConnectionFactory());
  }
  public void testFindByUsernameShouldReturnExactlyOneUser() {
    String username = "marko";
    User user = userDao.create(username);
    userDao.save(user);
    assertEquals(1, userDao.findByUsername(username).size());
  }
}

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.

Generating a password in Java

Tagged generator, java, password  Languages java

A simple password generator class.

/**
 * Simple password generator.
 *
 * @author marko haapala at aktagon com
 */
public class PasswordGenerator {
  public static final char[] HEX_CHARS = { 'a','b','c','d','e','f','g','h','0','1','2','3','4','5','6','7','8','9' };
  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',
                                              'v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
                                              'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','=',
                                              '!','"','#','¤','%','&','/','(',')' };
  /**
   * Generates an eight characters long password consisting of hexadecimal characters.
   *
   * @return the generated password
   */
  public static String generate() {
    return generate(HEX_CHARS, 8);
  }

  /**
   * Generates a password consisting of hexadecimal characters.
   *
   * @param length of the password
   * @return the generated password
   */
  public static String generate(final int length) {
    return generate(HEX_CHARS, length);
  }

  /**
   * Generates a password according to the given parameters.
   *
   * @param characters that make up the password
   * @param length of the password
   * @return the generated password
   */
  public static String generate(final char[] characters, final int length) {
    RandomString randomString = new RandomString(PseudoRandom.getRandom(), characters);
    return randomString.getString(length);
  }
}

Validating an email address in Java

Tagged validator, email, regexp, java, rfc 2822  Languages 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.

public class EmailValidator {
  public static boolean validate(final String emailAddress) {
    if ( emailAddress == null ) return false;
    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])*)+$";
    Pattern emailPattern = Pattern.compile(patternStr);
    return emailPattern.matcher(emailAddress).matches();
  }
}

Paginating a list in Java

Tagged java, pagination  Languages java

Not fully tested, but the idea works.

List list = ....;                           // Example: page size is 5
int originalSize = list.size();             // original size: 24
int start = Math.min(list.size(), Math.abs(currentPage * pageSize));      // start: 5
list.subList(0, start).clear();             // list now contains: 5, 6, 7, 8, 9,..., 23

int size = list.size();                     // size is now: min(listSize, originalSize - pageSize) = 19
int end = Math.min(pageSize, size);         // end: 5
list.subList(end, size).clear();            // list now contains: 5, 6, 7, 8, 9

boolean hasNext = (end < size);             // has next: 5 < 19
boolean hasPrevious =  (start > 0);         // has previous: 5 > 0

Parse a date in java

Tagged finnish, pã¤ivã¤mã¤ã¤rã¤n parsiminen, parsering av datum, java, date parser  Languages java

A simple class that parses a date given in finnish formats d.m.yyyy, dd.mm.yyyy and ddmmyyyy.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateParser {

  Calendar calendar = null;

  public DateParser(String dateAsString) {
    if ( dateAsString == null || dateAsString.length() < 8 ) {
      throw new RuntimeException("String must be at least 8 characters long and in one of these formats: ddmmyyyy | d.m.yyyy | dd.mm.yyyy");
    }
    dateAsString = dateAsString.replaceAll("\\.","");
    String parseString = "ddMMyyyy";
    if ( dateAsString.length() < 8 ) {
      parseString="dMyyyy";
    }
    try {
      Date date = new SimpleDateFormat(parseString).parse(dateAsString);
      calendar = Calendar.getInstance();
      calendar.setTime(date);
    } catch (Exception e) {
      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);
    }
  }

  public int getDayOfMonth() {
    return calendar.get(Calendar.DATE);
  }

  public int getMonth() {
    return calendar.get(Calendar.MONTH) + 1;
  }

  public int getYear() {
    return calendar.get(Calendar.YEAR);
  }

  public Calendar getTime() {
    return calendar;
  }

}

Format currency by Locale in Java

Tagged currency formatting, locale, java, rahan formatointi, formattering av valuta  Languages java

There are a few ways to format currency to your own locale. If you want the formatted result to appear without the currency sign then this is probably one of the better ways to do it. In the real world you would dig the locale from the user's request or session and pass it as a parameter to the method.

public static String formatCurrency(String amount) {
    NumberFormat decimalFormat = NumberFormat.getInstance(new Locale("fi", "FI", ""));
    decimalFormat.setMinimumFractionDigits(2);
    return decimalFormat.format(amount);
}

Split a URL into protocol, domain, port and URI using regular expressions

Tagged regex, java, url  Languages java
// Split URL into protocol, domain, port and URI
Pattern pattern = Pattern.compile("(https?://)([^:^/]*)(:\\d*)?(.*)?");
Matcher matcher = pattern.matcher(url);

matcher.find();

String protocol = matcher.group(1);            
String domain   = matcher.group(2);
String port     = matcher.group(3);
String uri      = matcher.group(4);

How to write UTF-8 data to an Oracle BLOB column with Java and JDBC

Tagged oracle, blob, jdbc, java, utf-8  Languages java

This example works with Oracle:

private Blob getBlob(Connection connection, String data)
{
  BLOB blob = BLOB.createTemporary(connection, true, BLOB.DURATION_SESSION);

  try
  {
      blob.open(BLOB.MODE_READWRITE);
      blob.putBytes(1, data.getBytes("UTF-8")); // Consider streaming, if data size is unknown. Note that setBytes doesn't work
  }
  catch(UnsupportedEncodingException ex)
  {
      throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  }
  catch(SQLException ex)
  {
      throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  }
  finally
  {
      try { if(blob != null) blob.close(); } catch(Exception ex) {};
  }
}

Then use the method like this:

Connection connection = getConnection();
PreparedStatement statement = getPreparedStatement(yer sequel);

statement.setBlob(1, getBlob(connection,  <Mao's Little Red Book>));

How to read UTF-8 data from an Oracle BLOB column with Java and JDBC

Tagged oracle, blob, utf-8, java  Languages java

This example works with Oracle:

private String getBlobAsString(Blob blob)
{
    StringBuffer result = new StringBuffer();
    
    if ( blob != null ) 
    {
        int read = 0;
        Reader reader = null;
        char[] buffer = new char[1024];
                                
        try
        {
            reader = new InputStreamReader(blob.getBinaryStream(), "UTF-8");

            while((read = reader.read(buffer)) != -1) 
            {
                result.append(buffer, 0, read);
            }
        }
        catch(SQLException ex)
        {
            throw new RuntimeException("Unable to read blob data.", ex);
        }
        catch(IOException ex)
        {
            throw new RuntimeException("Unable to read blob data.", ex);
        }
        finally
        {
            try { if(reader != null) reader.close(); } catch(Exception ex) {};
        }
    }
    
    return result.toString();
}

Then use the method like this:

ResultSet resultSet = your JDBC result set;

String utf8 = getBlobAsString(resultSet.getBlob("xml"));