java

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);
  }
}

Fixing Java networking problems in Debian Sid

Tagged java, ioexception, ipv6, sysctl, debian sid, sidux, network problem  Languages java

I got bitten by IPV6 again. IPV6 is not yet here and probably will not be until the current hard disk is used up. So here is how to fix networking problems for Java applications running on Sid(ux). I suddenly ran into strange network connectivity problems with all Java applications and found they are related to this bug. You will identify this problem by mysterious IOExceptions during network connections even when telnet makes connections without a hitch.

sudo sysctl -w net.ipv6.bindv6only=0

For a permanent solution change 1 to 0 for that property in this file: /etc/sysctl.d/bindv6only.conf

How to parse RSS/Atom feeds with the ROME Java library

Tagged rome, java, atom, rss, feed, parse  Languages java

This is a simple example of how to use the ROME library to parse feeds:

import com.sun.syndication.io.*;
import com.sun.syndication.feed.synd.*;
import java.net.URL;
import java.util.*;

public class RomeParserTest {

    public static void main(String args[]) {
        try {
            SyndFeedInput sfi = new SyndFeedInput();

            String urls[] = {
                "...", 
                "..." 
            };
            
            for(String url:urls) {
                SyndFeed feed = sfi.build(new XmlReader(new URL(url)));

                List entries = feed.getEntries();

                System.out.println(feed.getTitle());            
                System.out.println(entries.size());
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

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

Unit testing of DAO's

Tagged unit testing, dao, 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.

How to parse RSS/Atom feeds with Scala and the Rome library

Tagged scala, feed, atom, rss, parse  Languages java

This snippet shows how to parse feeds with Scala and the Rome library:

import com.sun.syndication.io._
import com.sun.syndication.feed.synd._
import java.net.URL

object FeedParser {
  def main(args: Array[String]): Unit = {
    try {
      val sfi = new SyndFeedInput()

      val urls = List("http://hbl.fi/rss.xml")
      
      urls.foreach(url => {
        val feed = sfi.build(new XmlReader(new URL(url)))

        val entries = feed.getEntries()

        println(feed.getTitle())
        println(entries.size())
      })
    } catch {
      case e => throw new RuntimeException(e)
    }
    
  }
}

Also see: https://gist.github.com/585235/bf328d90d094305121cec0ba2a646ce0093fa654

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

Tagged java, regex, 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);

Parse a date in java

Tagged finnish, date parser, java, pã¤ivã¤mã¤ã¤rã¤n parsiminen, parsering av datum  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;
  }

}

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>));

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);
}