Useful Java Code

From my experience


19 Nov 2016 View Comments
#java #computer #dao #pojo #gson #exception #xml #xstream

Some useful code blocks I find useful in Java

I am not sure about you guys, but at least for Java, there are certainly block of codes I like to keep around for later use. I have come across some useful ones (with the concept) which I will cover here, mainly for the reference.

1. DAO - Data Access Object

DAO is an abstraction where it provides an interface to data objects such as SQL/NoSQL Database, CSV, Spreadsheet, etc. It could literally be anything to store values. If you have typical structures to store some item. That could also be a DAO.

Simple codes that show how it could handle various DAO Object in maybe a day factory which constructs and provide you objects needed, Example of using Factory pattern:

public class DAOFactory {
    public DatabaseAccessObject getInstance(String type, Config config) {
        DatabaseAccessObject dao;
        if (MONGO_DATABASE.equals(type)) {
            dao = new MongoDatabase(config);
        } else if (DATABASE.equals(type)) {
            dao = new Database(config);
        } else if (CSV.equals(type)) {
            dao = new CSV(config);
        } else {
            throw new UnsupportedDAOException("not supported dao: "+type);
        }
        return dao;
    }
}

I would make the DAO implements a DatabaseAccessObject interface which provides basic operations such as OpenConnection, CloseConnection, getRows, writeRows, getColumns, writeColumns, checkConnection, etc. That would be common in each DAO object.

2. POJO - Plain Old Java Object

There are many ways to create a Java Object from the different set of documents. You can read/write from/to XML and JSON are the 2 great examples. However, you use the term for making anything into Java Objects such as Databases-POJO (Hibernate). I will just cover the 2 representations, XML, and JSON here.

:white_check_mark: XML

There are many different ways to make a POJO out of XML. Using @XStream is one of the ways. Here is a very simple usage. Say your XML look like,

<person>
   <birth_day>1980-01-01 00:00:01<birth_day>
... etc ...
</person>

Then you could convert this to a POJO by:

 @XStreamAlias("Person")
 public class Person {
 
     @XStreamAsAttribute
     @XStreamAlias("birth_day")
     private String birthDay; /

Another way would be using a sax and parse the raw XML. You can do something like getXMLDeclCharset, parseThisAsSuch using a DefaultHandler. Here is an example:

private String parseThisAsSuch(InputStream xmlStream, Charset cs, SAXParser reader) throws SAXException {
    final StringBuffer sb = new StringBuffer();
    try
    {
        DefaultHandler handler = new DefaultHandler() {

            @Override
            public void endElement(String uri, String localName, String name)
                    throws SAXException {
                sb.append(' ');
            }

            @Override
            public void startElement(String uri, String localName,
                    String name, Attributes attributes) throws SAXException {
                sb.append(' ');
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if(length > 0) {
                    sb.append(new String(ch, start, length));
                    sb.append('\n');
                }
            }
        };
        reader.setContentHandler(handler);            
        reader.parse(createInputSource(stream, cs));
    } catch(IOException ioe) {
        throw new SAXException(ioe);
    :wq!} 

    return sb.toString().trim();
}

As you can see, using SAXParser would add granularity to how the document is being parsed. This granularity could save you a bit of coding and time. For a simple task, I found myself easier to use just XStream as it is much flexible going back and forth with XML to POJO in annotated way. However, the SAX way is much more flexible in terms of what you wish to do with the raw XML.

:white_check_mark: JSON

There are also numerous ways to make a POJO out of JSON. A simple way is to use Jackson 2 (com.fasterxml.jackson.databind). Here is to read from JSON.

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'calvin'}";

//JSON from file to Object
Staff obj = mapper.readValue(new File("<json_file_location>"), Staff.class);

//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://stalkcalvin.com/api/staff.json"), Staff.class);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

However, I personally use Gson from Google most of the time. It’s similar logic as above. Let’s take a look at a Staff JSON:

{
  "staff": {
     "id": "123",
     "name": "calvin",
  }
}

Now in order to make a POJO, all you need is below:

public class Staff {
   @SerializedName("id");
   private int staffId;
   @SerializedName("name");
   private String staffName;
   ... etc ...
}

3. Exception Template

I think it is good to divide Exceptions into different sub-exceptions. We looked at DAO above, here would be an exception caused by DAO.

public class DataAccessObjectException extends Exception {

    public DataAccessObjectException() {
        super();
    }
    public DataAccessObjectException(String message) {
        super(message);
    }
    public DataAccessObjectException(String message, Throwable cause) {
        super(message, cause);
    }
    public DataAccessObjectException(Throwable cause) {
        super(cause);
    }

}

Templates are similar for any other exceptions, however, it gives names to what kind of exception it was and what it was for.

4. Copying a file to another location

Here is a way to copy a file to another file.

private void copyFile(File fromFile, File toFile) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        // reading and writing 16 KB at a time
        int bSize = 16 * 1024;
        byte[] buffer = new byte[bSize];
    
        bis = new BufferedInputStream(new FileInputStream(fromFile), bSize);
        bos = new BufferedOutputStream(new FileOutputStream(toFile), bSize);
        int last;
        while ((last = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, last);
        }
        bos.flush();
    } catch (IOException ioe) {
        log.error("Unable to copy fromFile: " + fromFile.getAbsolutePath());
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }
}

5. New list using static factories

Unless you are using a Guava libraries, I suggest you make your own static factory that handles these data structures with a name like below example:

public static <K, V> HashMap<K,V> newHashMap()
{
    return new HashMap<K, V>();
}

public static <K, V> HashMap<K,V> newHashMap(int initialSize)
{
    return new HashMap<K, V>(initialSize);
}

public static <T> ArrayList<T> newArrayList()
{
    return new ArrayList<T>();
}

public static <T> ArrayList<T> newArrayList(int initialSize)
{
    return new ArrayList<T>(initialSize);
}

6. Way to initialize common data structures

Initialize HashSet:

private static final Set<String> SYSTEM_COLLECTIONS_NAMES = new HashSet<String>() {
    {
        add("system.namespaces");
        add("system.indexes");
        add("system.profile");
        add("system.js");
    }
};

Initializing a List:

ArrayList<String> list = new ArrayList<String>() {
   {
     add("A");
     add("B");
     add("C");
   }
};

Initialize HashMap:

HashMap<String, String> h = new HashMap<String, String>() {
   {
      put("a","b");
   }
};

Or since you are defining statically, you can simply use the static block to initialize.

Conclusion

There are so many useful convenient functions in Java out there such as using annotations, interfaces, or libraries. However, those items deserve a separate blog on their own as there are many details to talk about those. Above items are really just referenced to me and people who might also find them useful. They often times come handy as they did for me. There are so many other useful design patterns I included as part of Algorithms Playground Project. Go to the linked URL and you will see a bunch of design patterns on all categorized with its own unit tests to show you a better understanding on each. Please step through the examples to understand how each of them works step by step and sees differences from another.

Share this post

Me

I am a passionate software developer working in Downtown, Vancouver. I strongly believe in art of algorithms and together with it to write clean and efficient software to build awesome products. If you would like to connect with me, choose one from below options :) You can also send me an email at