Posts

Showing posts with the label java

Avoid hibernate anemia and reduce code bloat

One of my beefs with Hibernate as an ORM is that it encourages anemic domain models that have no operations and are simply data structures. This coupled with java's verbosity tend to make code unmaintainable (when used by third party systems) as well as cause developers to focus in THINGS instead of ACTIONS. For example take the following class that represents a way to illustrate part of a flight booking at an airline: public class Flight { public Date start; public Date finish; public long getDuration() { return finish.getTime() - start.getTime(); } } This is the core "business" requirement for a use case in this model in terse java. Form an OO perspective, start and finish are attributes, and getDuration is an operation (that we happen to believe is mathematically derived from the first two fields. Of course, due to training and years of "best practices" brainwashing, most folks will immediately and mindlessly follow the java ...

Web application framework popularity over time

I thought I'd do a quick comparison of web frameworks to see how popularity is trending nowadays per google trends. I realized this is has some serious drawbacks, but as a person who has been in the j2ee space for years, I find the trend very interesting. The trend is clear, if you're an ace J2EE super guru, you are about in the same position as a yii developer. While you're experience might be transferrable, the days of java containers ruling the universe appear to be numbered. To do some other interesting comparisions, let's look at java specifically. This roughly supports my observation that Struts is dying off, spring is holding stead, and gwt...while making a big splash a few years ago seems to be tapering off. These numbers are a little deceptive because back in 2005 a lot of the "up and coming" frameworks, languages, and tools didn't even exist. So let's take a look at just the upstarts. I've included rails because it's...

Fun with character encoding and when to use ISO8859 instead of UTF-8

What character encoding are you using? Most folks nowadays settle on UTF-8 for web centric type applications, but things can get squirrelly if you use this encoding and start working with non-unicode systems. Recently, we had a situation where we took the string representation that started out with an array of 17 0xff values. In a unicode aware system, using UTF-8, this will translate into a character sequence of 17 0xfffd values. What happened? How did an array of 8 bit values get magically translated into an array of 16 bit values? It requires a bit of digging, but the short version is that if your source system is using 8 bit characters (something like iso 8859-n) and you translate to unicode, you will fail on certain byte values because they are invalid in UTF-8 and other character encodings. The only thing that can then happen is to change the character to the "invalid character" which is 0xfffd. For reference, in UTF-8 the values 192, 193, and everything ove...

java static fields

A great many people starting out with java development have only a vague understanding of the difference between a "public static String", "public String", and the difference between a class and an object. As this was confusing to me at first, I thought I would give a quick overview. A class defines a template for what data and operations are available when you tell the JVM to create an object. So, for example: class BlogPost { public BlogPost(String inString) { text = inString; BlogPost.latest = this; } public String text = ""; public static BlogPost latest; } When you do the following BlogPost myPost = new BlogPost("Hello"); You're telling the JVM to allocate some memory on the heap to store a reference to a memory location and from now on, when I refer to myPost, it means that memory location. BlogPost is a class, myPost is an Object that is a reference to a memory location that is an ins...

equals and hashCode for dummies (again)

In java, writing equals and hashcode methods are perennial problems. Newbies and experts alike are confounded when things go haywire and troubleshooting problems can be extremely difficult. A common thing that a poor hashcode/equals implementation will cause are intermittent problems and/or mysterious out of memory errors. To help clear things up, I'll give a 10,000 overview of how the core java libraries use the hashcode/equals methods. Essentially, the hashcode/equals methods are used when storing things in Hashes (HashMap, Hashtable, HashSet). Things often go wrong when folks start using custom objects as keys for these classes. For example, let's say we have a person class that looks something like this: public class Person { public Person(String orgName) { this.name = orgName } private String name; public String getName() { ...

Fixing Hibernate, DB2, H2, and Boolean Issues With a User Type

Edit: It was pointed out that this was a problem with H2, NOT Derby... not sure how I missed that, I've updated (Thanks Nick) Our team recently started using H2 for local development, with our production database being DB2. One nice thing is that the sql dialects for these are nearly identical and you don't need to change the dialect to get things to mostly work. We did, however, hit a snag with our boolean type fields. By default, the values for a boolean object default to "1" and "0" (or 1 and 0) when using the db2 driver and definition the column as a char(1), but when using the h2 jdbc driver (with the DB2 hibernate dialect), the values were getting translated to "true" and "false" which was breaking because obviouly you cannot store 4 characters in a 1 character field. After googling the problem, it turns out a lot of people have run into this and there aren't any obvious solutions float...

How to juice your java performance

Warning: This is a preoptimization In my previous post about equals and hashcode I thought I'd point out how to redesign the class in question to make better use of performance. If you have a situation where you create groups of objects that are immutable, but you need to pass them around in hashsets and/or look things up, a way to increase performance is to change from something like the following: package blog.mainguy; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class LookupEntity { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object other) { if (other != null && other instanceof LookupEntity) { return new EqualsBuilder().append(this.getName(), ((LookupEntity) other).getName()).isEquals(); } else { return ...

Java programmers: Code to the interface, even if the interface is a class

After spending a considerable amount of time trying to figure out how to refactor some particularly hairly (hairy + gnarly) data access code, I thought I'd share some insight into a popular misconception about what coding to the interface actually means. Let's say we're writing a data access layer and we have something called the UserDAO. a simple implementation might be something like: public class User { public int id; public String name; } public class UserDao { public boolean save(User toBeSaved) { } } I'm going to dodge the issue of the user class not having getters and setters and thus not following the javabean spec and talk about the UserDao Interface. Yes, you heard me, the UserDao class effectively is an interface in this example. Sit down and just think about that for a minute, once you've done that, move to the next paragraph. A great (GREAT) many java developers might not get to this paragraph because they'll imme...

Java classes, objects, and instances demystified (hopefully)

A great many people are competent java developers, but have only a vague understanding of the difference between a "public static method", "public method", and the difference between a class and an object. As this was confusing to me at first, I thought I would give a quick overview. A class defines a template for what data and operations are available when you tell the JVM to create an object. So, for example: public class BlogPost { public String text = ""; public static BlogPost latest; public static BlogPost create(String input) { latest = new BlogPost(); latest.text = input; return latest; } public int getTextSize() { return text.length(); } } When you compile this class, it is creating a file that the java runtime can later use to enable programmers to load an object into memory that has a single attribute called "text" which is a reference to another o...

The java collections framework for newbies

I don't consider myself a java expert by any measure, but there's a disturbing thing I've noticed. There are a LOT of people who claim to be "java developers", but they have zero clue what the "java collections framework" is. This post is designed for folks who keep getting stumped on interview questions or are mystified when someone starts talking about the difference between a Set and a List (for example). If you google "java collections framework for dummies" you'll find this link which has a more complete, if fairly dense explanation. I'm going to do you one better and give a rule of thumb that you can use without thinking about it. At it the root of things, a collection is something you can store other things inside. Just like in real life, a collection of marbles is just a "bunch" of marbles. The big difference in the collections framework is that the different implementations have different things they DO with t...

The ruby and java fightclub

As a person who has one foot firmly in java and another in ruby, I'm often in a situation where I try to have an objective conversation about the advantages and disadvantages between the the two. Unfortunately, both of these camps are not very objective about themselves and each other. Ruby guys seem to think that ruby is all sunshine and lollipops and java is spawn of satan and visa versa. Find any java developer who knows nothing about ruby (or ruby on rails) and strike up a conversation about the advantages and disadvantages between the two. If they in any way care about programming, you will typically end up with a seriously heated discussion about: Performance, Scalability, Compiler Safety, Support, Maintainability, other stuff. On the other side of the equation, I'm a bit at a loss because I've never met a ruby developer who didn't previously work as a java (or C) developer. Typically a new convert from java/whatever has all the zeal of a new religious co...

Computus in scala and java

In the spirit of the holiday, I figured I would try my hand at writing computus in scala and java. For those who aren't aware, computus is the algorithm used to compute which day easter falls on. First, the scala version: object Computus { def main(args: Array[String]) { val start = System.currentTimeMillis() for (year 11)) || (epact_val ==24)) { epact_val + 1 } else { epact_val } } def n_whatever(year:Long):Long = { 44- correct_epact(year) } def fix_n(year:Long):Long = { val n=n_whatever(year) if (n 31) { "April " + (day_of_march -31).toString() } else { "March " + day_of_march.toString() } } } and now the java version public class JavaComputus { public static void main(String[] args) { Long start = System.currentTimeMillis(); for (long i = 2000; i 11)) || (epact_val ==24)) { return epact_val + 1; } else { return epact_val; } } ...

Parsing RSS in java and Jruby

I've been playing around with some rss feed parsing and decided to contrast the ruby way with the java way. First, the java way import com.sun.syndication.feed.synd.*; import com.sun.syndication.io.*; import java.net.URL; import java.util.List; public class RssJava { public static void main(String[] args) { long start = System.currentTimeMillis(); int total = 0; int entries = 0; try { SyndFeedInput input = new SyndFeedInput(); SyndFeed synFeed = input.build(new XmlReader(new URL("http://mikemainguy.blogspot.com/feeds/posts/default"))); for (SyndEntry entry : (List ) synFeed.getEntries()) { entries++; List contents = entry.getContents(); for (SyndContent content : contents) { total += content.getValue().split(" ").length; } } } catch (Exception e) { e.printStackTrace(); ...

Example of the difference between Ruby and Java

Having worked extensively with both ruby and java, I thought I'd share some interesting differences between how one can approach solving problems in the two languages. Let's take a common example of a function that will take a variable number of arguments and return a string with all non-null values separated by commas. We'll start by just using the core runtime and see what we can do. Here's the Java example: public class StringJava { public static void main(String[] args){ System.out.println(printComma("test1","test2","Test3")); System.out.println(printComma("test1",null,"Test3","Test4")); } public static String printComma(String... names) { StringBuffer buff = new StringBuffer(); boolean first = true; for (String str: names) { if (str != null) { if (first) { buff.append(str); first = fal...

Technology and programming trends

Image
As technologist, I'm always keeping my eyes on the market. There's nothing worse from a marketability perspective than being the best chariot wheel repairman when the entire world has moved on to automobiles. If you're going to be in a niche, you better be in one that is HIGHLY lucrative. To this end, I took a look on indeed.com and tried to see how various programming languages stacked up as far as job postings. java, ruby, groovy, c#, php, c, erlang, vb, delphi Job Trends Java jobs - Ruby jobs - Groovy jobs - C# jobs - PHP jobs - C jobs - Erlang jobs - VB jobs - Delphi jobs Obviously this is not comprehensive, but it shows what I "kinda" already knew. C is king, with java taking a large secondary position and C# following up behind java. One thing to note is that that largest percentage shown on that chart is 4%. This roughly means that the market is SO fragmented that a large leader only captures 4%. For the COBOL folks clinging on fo...

Garage sale maps

The Backstory My wife is an avid garage sailer. She finds garage sales she thinks have promise, then cruises by them to see if there is anything of interest. She is so accomplished at this that she routinely turns a profit by snagging things that folks didn't realize had resale value, and flipping them at local consignment shops. While this doesn't pay the bills, it DOES provide enough extra cash to actually have her garage sailing at least pay for itself with a little left over. This is, however, not without it's share of problems: First, the postings online (or paper) for garage sales are scattered to the four winds. At this point, craigslist.org is the hands down winner for quality and quantity of posts. Local newspapers/classified also have a good quantity, but the few sites I found on google geared toward this are suffering terribly from a strategic chicken and egg problem. Second, while craigslist has a fairly high quality set of sales established, it h...

Active Directory Authorization with Java

I have a situation where I need to be able to have sub groupings of users in Active directory to manage who can see particular pieces of information. It turns out this is easy, but unintuitive. An important detail is to realize that groups can be put inside into other groups and you can use the "member" and "memberOf" attributes to determine who is in which group. So if you have an OU in Active directory called "OU=web,DC=mainguy,DC=org" and you create a group with a name of "CN=Germany National Sales,OU=web,DC=mainguy,DC=org". From here in Active directory you create any number of subgroups and put them in the parent group (under the same OU in our example, but that's not necessary). At this point, you can dump users into any of the groups and you can get segregate users into nested structures. With a little creativity you can use recursion to have deeper nesting (not necessarily a good thing) as well as a "deny/allow" capab...