Pure-Essence.Net

Jackson Ignore Property/Convenience Method

Posted by: pureessence on: May 23, 2012

Here’s something I learned about Jackson and you may run into it.

What gets serialized by default?

Properties of an object are initially determined by process called auto-detection: all member methods and fields are checked to find:

  • “Getter” methods: all no-argument public member methods which return a value, and conform to naming convention of “getXxx” (or “isXxx”, if return type is boolean; called “is-getter”) are considered to infer existence of property with name “xxx” (where property name is inferred using bean convention, i.e. the leading capitali letter(s) is changed to lower case
  • field properties: all public member fields are considered to represent properties, using field name as is.

This means Jackson will map any convenience methods you create on the POJO that’s public and starts with “get” and returns a value. This may NOT be the behavior you want.

@JsonIgnoreProperties can be used at a class level and it works for me.

But in order to prevent me from tediously adding all of convenience methods on my POJO to the list, I started to use “return” as the keyword instead of “get” so Jackson will ignore those methods by default. Of course if you want JSTL to be able to show the convenience method output on the screen, the convenience method has to begin with “get”. So I’m using a mix of solutions to this problem.

Java Generics – conditionally instantiate a class

Posted by: pureessence on: May 8, 2012

From Class to list of Enums

public static <T extends Enum> List<T> getList(Class<T> clazz) {
    return Arrays.asList(clazz.getEnumConstants());
}

So if I want to instantiate a class via some condition, I can do the following but still how do I know what type to use?

public class Foo {
	public String getName() {
		return "hi";
	}
}

public class Foo2013 extends Foo {
	public String getAge() {
		return "age";
	}
}

public class FooFactory {
	@SuppressWarnings("unchecked") // what do I need to do to not having to use this??
	public static <F extends Foo> F getFoo(int year) {
		try {
			if (year >= 2013) {
				return (F) Foo2013.class.newInstance();
			} else {
				return (F) Foo.class.newInstance();
			}
		} catch (InstantiationException e) {
			// TODO
		} catch (IllegalAccessException e) {
			// TODO
		}
		return null;
	}
}

public class FooFactoryTest {
	@Test
	public void testFooFactory() {
		Foo foo = FooFactory.getFoo(2011);
		Assert.assertEquals(Foo.class, foo.getClass());

		Foo foo2013 = FooFactory.getFoo(2013);  // <-- how can I do Foo2013 foo2013 without repeating the logic?
//		foo2013.getAge();
		Assert.assertEquals(Foo2013.class, foo2013.getClass());
	}
}

https://github.com/dodozhang21/JavaGenerics

CSS Positions

Posted by: pureessence on: March 4, 2012

A coworker asked me about CSS positions. I admit I’m no expert in this topic. However, I want to illustrate my brief understanding. Maybe you will find them helpful.

Position: static
Default, you don’t have to set it.

Position: relative
It’s like a ghost image. Setting the corresponding properties of top, left, right, or bottom will move this element out of the its original document location but it will not affect any surrounding elements. The surrounding elements will treat it as if its position never changed.

Position: absolute
Takes the element out of its normal document location. The corresponding properties of top, left, right, bottom will be based off its first parent element whose position is not static. Check out this example to get an idea. The parent element is bubbled all the way up until it finds the document window.

Position: fixed
Similar to the absolute position except its parent element is the browser window. I’ve tried using this many years ago and found that IE didn’t support it. It sounds like pre IE 8 never supported it properly. Because of this, I never found a great use for it.

If I confused you, the positions are explained in greater details here. I find it very well written.

幸福是什么感觉

Posted by: pureessence on: October 23, 2011

幸福是什么?其实幸福没有绝对的答案,关键在于你的生活态度。善于抓住幸福的人才懂得什么是幸福。一直以为感受幸福是件很困难的事,那是一种灯火阑珊处的境界。经过岁月的流年以后,才明白,幸福其实很简单,只要心灵有所满足、有所慰藉就是幸福。
幸福就是一种满足感。
健康的活着就是一种莫大的幸福!!
幸福无处不在 只要用心细细体会 你就能感觉到。

Daily wtf Watson story: Active Directory

Posted by: pureessence on: October 1, 2011

A coworker of my husband’s, let’s call him Watson, has some interesting ways of dealing with situations. As a system administrator, he has unique powers.

Two days ago my husband received a support ticket regarding a temporary employee unable to log into her machine. My husband updated her password and verified and he could log in and closed the ticket. A day later, the ticket was reopened with the same issue. This time my husband tried her login on a different machine and true enough, he got the invalid username or password error. He searched Active Directory looking for the temporary employee’s login and found nothing. It appeared someone had deleted the employee’s account.

My husband scratched his head and inquired Watson:

“Watson, did you do anything with Mary’s account?”

Watson: “Yes, the manager requested that I delete her account.”

My husband got the manager on the phone and asked about the situation. The manager confirmed that he created a ticket to have Mary removed from a certain mailing list. As my husband was on the phone with the manager, Watson was listening and became rather irritated and printed the ticket and showed it to my husband. The ticket titled “Remove Mary from mailing list ABC”. My husband said to Watson:

“Watson, the ticket requested her removed from a mailing list, you deleted her entire Active Directory account!”

Watson: “How else was I supposed to get her off that mailing list?”

My husband: “Remove her from the mailing list?”

Watson barked: “Yes! I could have done that!” and stormed off and did not say anything else.

jQuery read only elements

Posted by: pureessence on: September 22, 2011

There is a business requirement on a project I have at work to only allow a certain number of properties editable at a certain stage of the domain object’s life cycle. And like always, the properties defined to be editable could change in the future.

I already have a page that allows the user to edit all properties of the domain object, I really do not wish to duplicate that code. Please note that if you set an input element on a form as disabled, the value associated with the element will NOT be submitted via form post, that certainly is NOT what I’m looking for. I want the values of the *read only* fields still be submitted by the form but I just don’t want the user to edit the values. So I looked into using the readonly attribute in HTML. It’s complete crap.

For faqs.org:

It’s important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don’t change the value of the field.

Basically it works half-hearted and most browsers (IE, FF) do not indicate (by default) that a field is readonly. So the users will probably be left wondering why they cannot edit the field.

I searched around for an alternative and found this wonderful jQuery plugin readonly. Even though I couldn’t get it to work right for my application, the idea behind it is genius. You basically put overlay layers on top of any input fields you wish to make read only. The plugin seems a bit outdated. Perhaps it doesn’t work well with the newer version of jQuery but the idea still works well. Therefore I implemented my own.

This implementation automatically makes all input fields read only unless the input field has the class excludeMeFromReadOnly. This is just my implementation for demonstration. I do not provide any support for this code. Use where you see fit.

CSS

.readOnlyOverlay {
	position: absolute;
	background-color: #666;
	opacity: 0.3;
	filter: alpha(opacity=30);
	padding: 0pt !IMPORTANT;
	margin: 0pt !IMPORTANT;
}

javascript function generateOverlay

function generateOverlay(element) {
	var dimension = getDimensions($(element));
	//console.log('top=' + dimension.top + ' left=' + dimension.left +' width='+ dimension.width + ' height=' + dimension.height);

	// disassociate corresponding label attributes so the value of the element cannot be changed by clicking on the labels
	var id = $(element).attr('id');
	var label = $('label[for="'+id+'"]');
	$(label).removeAttr('for');
	
	// set my tabindex to -1 so tabs will ignore me
	$(element).attr('tabIndex', -1);
	$(label).attr('tabIndex', -1);

	// create a div overlay
	var overlay = $('<div class="readOnlyOverlay">&nbsp;</div>').appendTo('body');
	$(overlay).css('top', dimension.top).css('left', dimension.left).css('width', dimension.width).css('height', dimension.height);
}

javascript function getDimensions

function getDimensions(element){
	var ret = {};

	// The multiple acquisitions of the CSS styles are required to cover any border and padding the elements may have.
	// The Ternary (parseInt(...) || 0) statements fix a bug in IE6 where it returns NaN,
	//  which doesn't play nicely when adding to numbers...
	ret.width = $(element).width() 
	  + (parseInt($(element).css('borderLeftWidth')) || 0)
	  + (parseInt($(element).css('borderRightWidth')) || 0)
	  + (parseInt($(element).css('padding-left')) || 0)
	  + (parseInt($(element).css('padding-right')) || 0);
	ret.height = $(element).height() 
	  + (parseInt($(element).css('borderTopWidth')) || 0) 
	  + (parseInt($(element).css('borderBottomWidth')) || 0)
	  + (parseInt($(element).css('padding-bottom')) || 0)
	  + (parseInt($(element).css('padding-bottom')) || 0);
	var offsets = $(element).offset();
	ret.left = offsets.left;
	ret.top = offsets.top;

	return ret;
}

jQuery selector

// select all input,select elements. I'd wrap my form in a div.
$('div#formContent input, div#formContent select, div#formContent textarea').each(function(i, element) {
	// if the element doesn't have the class named excludeMeFromReadOnly, overlay it to make it look like it's read only
	if(!$(element).hasClass('excludeMeFromReadOnly')) {
		generateOverlay($(element));
	}
});

Please note, the plugin contains a lot more logic including IE hacks etc. Fortunately for me, I really don’t care about IE prior to version 8 in my particular scenario. Therefore I don’t need all of those hacks.

—>Example code (example at jsFiddle)<—

jQuery.each vs Javascript for loop

Posted by: pureessence on: September 2, 2011

Being a big jQuery fan, I use jQuery.each method a lot in my Javascript code. Until recently I didn’t think too hard what jQuery.each really is.

Its description says it’s an iterator but it certainly is NOT a true iterator.

For example:

Let me know what you expect the code below to return.

var myVars = ['foo1', 'foo2', 'foo3'];

function containsValue(myValue, myCollection) {
	jQuery.each(myCollection, function(i, val) {
		if(val == myValue) {
			return true;
		}
	});
	return false;
}

$(document).ready(function() {
	console.log(containsValue('foo2', myVars));
});

Before I know better, I’d expect it to return true. Since myCollection DOES CONTAIN the value ‘foo2′. However the function containsValue WILL ALWAYS RETURN FALSE. That’s because when you return out of jQuery.each, it simply exits out of jQuery.each but not the containing function. In fact, whether you do anything in the callback function at all, jQuery.each ALWAYS RETURNS the collection you pass in.

e.g.

var returnedVar = jQuery.each(myVars, function(i, val) {});
console.log(returnedVar === myVars); // evaluates to true

In my opinion, jQuery.each acts more like a closure than an iterator. Sure you may use it as an iterator as long as you not returning anything. If you are just changing behaviors or collecting information, it will mimic an iterator. But you need to know, it really is not an iterator.

Personally I’m going to start to use Javascript’s native for..in statement instead of jQuery.each for Javascript collection variables. There is also an argument that jQuery.each may never perform faster than the native support for an iterator. Therefore below I will rewrite the function above using for..in.

function containsValueWithFor(myValue, myCollection) {
	for (index in myCollection) {
		if(myCollection[index] == myValue) {
			return true;
		}
	}
	return false;
}

console.log(containsValueWithFor('foo2', myVars)); // true

var myMap = {'lala':'foo1', '2':'foo2', 'b':'foo3'};

console.log(containsValueWithFor('foo2', myMap)); // true as well for an object/map

—>Example code<—

2011 nfjs Central Iowa Software Symposium

Posted by: pureessence on: August 8, 2011

My survey responses to the 2011 nfjs Central Iowa Software Symposium event for my company.

Benefits to you and the company from attending this event:
Keep up to date regarding the current technologies and development in the Java community.

Information that your co-workers / the company should be aware of:
Functional programming is making a big splash on the JVM. We really should come out of the traditional OO & imperative programming mindset and start think of solving programming challenges in a multi-paradigm fashion. We should upgrade from CVS to Git :)

Information that you learned that may have negative impacts to the company:
None

Would recommend this event / company presenting to someone else? Why?
Yes. The presenters have great knowledge about their topics. They always make me think harder and different about what I am doing at work.

Additional Comments or Suggestions:
I greatly enjoyed learning more about Scala, akka and functional programming thinking. The multi-paradigm session by Ted Neward opened my eyes. I took logic & functional programming courses in college and was super impressed by how concise and powerful those languages can be used to solve particular issues. Now many frameworks on the JVM prove that as Java programmers (who are innately OO & imperative), we may fully utilize the power of programming languages of other paradigms. This motivates me to explore a newer realm of programming.

I learned a lot from the Seven wastes of software development session e.g. communication is 38% tone, 7% words & 55% body languages. Therefore we should avoid plain emails for especially business rules discussion; converse with a coworker face to face is a much more effective way of communication. I think I don’t always do well in this area. Perhaps programmers are generally shy and introverted. I need to learn to open up more.

I also loved the Spock session although I feel Spock as a framework is yet completely mature for prime time. The fact it doesn’t have a version 1.x release somewhat speaks for this. (And it’s not yet in maven central repository.) I love its various features. But it’s still under heavy development phase as its community is actively adding more features to the framework. If we start using it now, we may need to upgrade our code dramatically later to get its full effects e.g. the @Unroll feature is going to change soon. However, I’m super excited to revisit it in a few months or so to see where it’s at. The fact that it’s a test framework great for both state testing & interaction testing (mocking) is awesome! It sounds like the mocking part of it is yet as mature as other mocking frameworks e.g. Mockito. For example, it doesn’t support partial mock/spy. This does not make me want to switch from Mockito to use it.

I will also use many of the new features of Groovy I learned since I just started using Groovy for testing. The SQL class Groovy has is extremely powerful and gave me many ideas as how I can utilize it to make testing more dynamic and more maintenance free.

QUnit – test your javascript

Posted by: pureessence on: July 24, 2011

After over ten years of javascript programming, I’m finally seriously considering writing at least unit tests for my javascript. Since I’m such a big fan of jQuery, QUnit seems like the obvious choice.

It’s sad but better late than never.

The truth is, in my opinion, the fact that javascript test frameworks do not yet maturely work with many of the continuous integration software deters programmers from using them. What’s the point of unit testing if they don’t automatically get run? Based on my research, JSUnit is the only one that integrates with ANT innately. But JSUnit is more of an abandomware now so people are looking for alternatives.

QUnit + CI topics

>> Run my test suite <<

QUnit simple example:

HTML:

<!DOCTYPE html>
<html>
<head>
	<title>Test Suite</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
	<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
	<!-- Your source files go here -->
	<script type="text/javascript" src="functions.js"></script>

	<!-- Your tests files go here -->
	<script type="text/javascript" src="isEvenTest.js"></script>
	<script type="text/javascript" src="startsWithTest.js"></script>

</head>
<body>
	<h1 id="qunit-header">QUnit example</h1>
	<h2 id="qunit-banner"></h2>
	<div id="qunit-testrunner-toolbar"></div>
	<h2 id="qunit-userAgent"></h2>
	<ol id="qunit-tests"></ol>

	<!-- Any HTML you may require for your tests to work properly -->
	<div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>

Source javascript file:

function isEven(val) {
	return val % 2 === 0;
}

function startsWith(data, startsWithStr) {
	data = jQuery.trim(data);
	startsWithStr = jQuery.trim(startsWithStr);
	if(data) {
		return data.toUpperCase().lastIndexOf(startsWithStr.toUpperCase(), 0) === 0;
	} else if(data === startsWithStr) {
		return true;
	} else {
		return false;
	}
}

Sample test file:

$(document).ready(function(){

	module("startsWithTest");

	test('startsWith', function() { 
		ok(startsWith("ll-925", "ll-"), 'Starts with ll-'); 
		ok(!startsWith("ll-925", "xl-"), 'Does not start with xl-'); 
		ok(!startsWith("", "xx-"), 'Does not start with xx-'); 
		ok(startsWith(" xx-sdgj ", "xx-"), 'Trimming test: starts with xx-'); 
		ok(startsWith(" xx-sdgj", " xx- "), 'Trimming test 2: starts with xx-'); 
		ok(startsWith("", " "), 'Empty string starts with empty string'); 
		ok(startsWith("Mn-u59", "mN-"), 'Non case sensitive test'); 
//		raises(startsWith(foo, " "), 'Undefined test 1');  // undefined is obviously not considered a normal exception
	}) 

});

>> git repo for the source <<

Additional resources:

My father’s Gui Lin experience

Posted by: pureessence on: July 24, 2011

Gui Lin (Chinese: 桂林; pinyin: Guìlín;) is a prefecture-level city in China, situated in the northeast of the Guangxi Zhuang Autonomous Region on the west bank of the Li River. Its name means “forest of Sweet Osmanthus”, owing to the large number of fragrant Sweet Osmanthus trees located in the city. The city has long been renowned for its unique scenery.

My father and his girlfriend’s family visited Gui Lin about a month ago.

Although the scenery was exceptional like you’d expect but his experience was far from it. Gui Lin is a cyclone for tourist traps. He shared some of his bad experience and they were so jaw dropping, I have to blog about them.

The Taxi
There is no meter on any of the taxi in that city. You bargain the price prior to your ride with the taxi driver and then s/he takes you to your destination. See a problem with this particular arrangement or lack of governmental enforcement of honesty? Well, he’s experienced it.

On the way back from a previous trip, my father inquired the average cab fare from his hotel to the dock for his next day’s cruise. The driver indicated around 60 rmb. The next morning, a different taxi driver wanted 80 rmb for the ride. My father did not give in since he thought the fare should be 60 rmb. The taxi driver instead of not agreeing to the ride, took the 60 rmb and dropped them off at a different dock than their actual desired destination. It took them a while to figure out they were at the WRONG dock since they were unfamiliar with the area. They were late for their cruise and had to spend additional fare in order to travel to the correct dock.

The Bamboo Raft Ride
A bamboo raft takes you down the stream of the river slowly by its current. My father had arranged a taxi to pick them up at the end of the trip. Although the price of the ride was advertised to include food, they provided inedible dishes on the raft so they could market other dishes for extra cost. There were various vendors who stationed at different locations down the stream. Some claimed the fish dishes were prepared with fish freshly caught in the river earlier in the morning. They charged a lot for them. My father and his girlfriend’s family did not purchase any. They were later dropped off at a dock in which they thought was the end of the trip. However, after a half hour wait for the taxi, my father called the taxi driver he paid for. The taxi driver informed my dad that he was dropped at the wrong location. The raft people dropped them off way prior to the end of the trip. My father was once more duped for exercising his right of not purchasing overpriced marketed tourist goods.

Gui Lin has been on my list of must visit places for a long time. Based on my dad’s accounts, I think I’m going to wait a little longer for that wish.

My most adorable Pomeranians

Categories

Archives

SocialVibe


Follow

Get every new post delivered to your Inbox.

Join 123 other followers