Pure-Essence.Net

2011 nfjs Central Iowa Software Symposium

Posted by: pureessence on: August 8, 2011

  • In: geeky | java | plug
  • 2 Comments

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 spacer

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.

Tags: Central Iowa Software Symposium, nfjs

QUnit – test your javascript

Posted by: pureessence on: July 24, 2011

  • In: geeky | non php code
  • Leave a Comment

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

  • jQuery tests under CI
  • Syn instead of Selenium?
  • QUnit and automated browser tools

>> Run my test suite <<

QUnit simple example:

HTML:

<!DOCTYPE html>
<html>
<head>
	<title>Test Suite</title>
	<script src="/img/spacer.gif"> 

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:

  • QUnit tutorials
  • API documentation
Tags: javascript, jQuery, qunit, unit test

My father’s Gui Lin experience

Posted by: pureessence on: July 24, 2011

  • In: chinese | love n family | personal | rants
  • 1 Comment

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.

SPEL! I conquered you on a Friday!

Posted by: pureessence on: July 22, 2011

  • In: geeky | java
  • Leave a Comment

Today is my first attempt at using SPEL. After a mighty struggle, I was able to conquer it!

Background:

I needed a year variable for some work on a jsp page. It’s not always defined. I know for our routable datasource, a default year is required in order for it to work. I wanted to use the same default year but I only want the variable to be defined once and used in both places.

So I looked into SPEL.

It seems like the correct solution for the problem.

My original idea:

spacer
As it turns out, SPEL does not yet support embedded variables. SPEL, you must improve yourself!

My workaround:

I do not love it but it accomplishes my goal of not defining it more than one place.

Define the variable in a properties file e.g. application.properties
defaultYear=2011

Then use placeholder instead of SPEL notation to include it in spring.

spacer

Syntax grrr syntax:

Sadly some of my time was to learn the fact you CANNOT put a space between # and { in SPEL. For example, # {bean.property} will NOT work, but #{bean.property} will. It seems obvious afterwards but the error message you get just DOES NOT help you come to that conclusion.

Moral of the story:

SPEL is very handy but it’s yet perfect. Do keep that in mind as an alternative solution when dealing with Spring. If you use annotation, you can do @Value(“#{bean.property}”). Refer documentation for more info.

Tags: spel, spring, Spring Framework

Andy’s meatball recipe

Posted by: pureessence on: July 19, 2011

  • In: freebies | plug | recipes
  • Leave a Comment

My husband Andy made these meatballs last night. They were soooooo good. I had to share the recipe since it’s his ORIGINAL creation with inspiration from Robert Irvine.

Ingredients
½ lb Ground Beef
½ lb Ground Pork
1 Bratwurst Patty (approx. 1/3 lb ground bratwurst)
1 cup panko bread crumbs
2 eggs
½ cup fresh chopped green onion
½ cup fresh chopped parsley
½ cup fresh chopped cilantro
2 large cloves garlic diced or minced
¼ cup chopped Basil

Cooking direction
Preheat Oven to 375 degrees – combine all ingredients and mix well. Form into 1.5” balls and place in a greased baking pan. Bake covered for 20 minutes. Uncover and bake an additional 5 minutes.

Java concurrency – Multiple queue monitors

Posted by: pureessence on: June 25, 2011

  • In: geeky | java
  • Leave a Comment

At work, I’ve implemented a queue monitor batch application. Due to business rule changes, it now needs to monitor two queues. Instead of creating another batch application, I really wanted to stick with the same application but just create two threads, each monitoring its own queue.

However, the twist I need is to have the main batch application thread die as soon as either queue monitoring thread dies.

I’ve been searching for a graceful way to handle such a concurrency need in Java. Thank you to Gary Myers, I’ve got a great start on it.

The basic idea is to pass a java blocking queue to both of the threads and if either thread fails, do blockingQueue.offer to indicate so. Then in the main thread, it will check for the blocking queue’s result. blockingQueue.take() blocks/waits for it to return and then continues the execution of the main thread.

Things I learned that made today AMAZING!

  • Put repositories in the pom.xml instead of settings.xml for maven to look through multiple repositories
  • Use SynchronousQueue to ensure only 1 element at a time may exist in the queue
  • Use daemon to make sure the JVM will die even if there is a thread running
  • You can EMBED ActiveMQ using spring so you don’t have install it at all

Below is a simple concurrency example that demonstrates the idea from Gary Myers.

Worker:

public class Worker implements Runnable {
   private BlockingQueue<String> finishedQueue;
   private String result;
   private long sleepTime;

   public Worker(BlockingQueue<String> finishedQueue, String result, long sleepTime) {
      this.finishedQueue=finishedQueue;
      this.result=result;
      this.sleepTime=sleepTime;
   }

   public void run() {
      try {
         TimeUnit.SECONDS.sleep(sleepTime);
         finishedQueue.offer(result); //you have to use offer to get this queue to work.  It will throw an exception if there is something in the queue.
      } catch(InterruptedException e) {
         e.printStackTrace();
      }
   }
}

DaemonThreadFactory:

public class DaemonThreadFactory implements ThreadFactory {
   private AtomicInteger counter;

   public DaemonThreadFactory() {
      this.counter=new AtomicInteger(0);
   }

   public Thread newThread(Runnable r) {
      Thread thread=new Thread(r);

      //if you wanted you can make this class generic by having the constructor take arguments that can be used to configure the following
      thread.setDaemon(true); //need it to be daemon so the JVM will die even if there is a thread running
      thread.setName("Daemon Thread: " + counter.incrementAndGet()); //you don't have to give it a name, but I always do.

      return thread;
   }
}

Test the threads in a simple example:

public class Main {
   public static void main(String[] args) throws InterruptedException {
      ExecutorService service=Executors.newFixedThreadPool(2, new DaemonThreadFactory());
      SynchronousQueue<String> queue=new SynchronousQueue<String>(); //this queue can hold 1 element at a time, so basically the first thread to finish will be the one to successfully put the element in the queue
      //create the runnables before hand so that extra time isn't spent instantiating the runnables at submission time.
      Runnable runnable1=new Worker(queue, "Runnable 1", 4);
      Runnable runnable2=new Worker(queue, "Runnable 2", 3);

      service.execute(runnable1);
      service.execute(runnable2);

      System.out.println("before queue");
      System.out.println(queue.take());
      System.out.println("after queue");

      service.shutdown();
   }
}

I will not go into the details of the code I added for queue monitoring as they are a lot more involved.

The coolest thing I learned about ActiveMQ is how you can embed it using the following spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="www.springframework.org/schema/beans"
       xmlns:xsi="www.w3.org/2001/XMLSchema-instance"
       xmlns:p="www.springframework.org/schema/p"
       xmlns:jms="www.springframework.org/schema/jms"
       xmlns:amq="activemq.apache.org/schema/core"
       xsi:schemaLocation="www.springframework.org/schema/beans www.springframework.org/schema/beans/spring-beans-3.0.xsd
       				www.springframework.org/schema/jms www.springframework.org/schema/context/spring-jms-3.0.xsd
					activemq.apache.org/schema/core activemq.apache.org/schema/core/activemq-core.xsd">

    <!--  Embedded ActiveMQ Broker -->
    <amq:broker id="broker" useJmx="false" persistent="true">
        <amq:transportConnectors>
            <amq:transportConnector uri="tcp://localhost:0" />
        </amq:transportConnectors>
    </amq:broker>

    <!--  ActiveMQ Destination  -->
    <amq:queue id="destination" physicalName="com.threads.example.queue" />

    <!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->
    <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" />

    <!-- JMS Producer Configuration -->
    <bean id="jmsProducerConnectionFactory"
          class="org.springframework.jms.connection.SingleConnectionFactory"
          depends-on="broker"
          p:targetConnectionFactory-ref="jmsFactory" />

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
          p:connectionFactory-ref="jmsProducerConnectionFactory"
          p:defaultDestination-ref="destination" />
</beans>

Once done, your application will run without your manual ActiveMQ installation. Above is from the example here.

If running in Eclipse…

  • Install m2eclipse plugin if you have not
  • Import -> Maven -> Existing Maven Projects
  • Select the MultipleQueueMonitors folder
  • Add src, resources, properties as source folders
  • Change the jre to whatever you want to use

The following error may occur in Eclipse

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c:
The matching wildcard is strict, but no declaration can be found for element 'amq:broker'.

To fix it, you must associate the ActiveMQ XSD URL with the schema.

Go to XML->XML Catalog in Preferences, and add a User Specified Entry.

Location: activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Namespace Name
Key: activemq.apache.org/schema/core

Then add a second one:

Location: activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Schema Location
Key: activemq.apache.org/schema/core/activemq-core.xsd

Hit OK.

For more info, visit this stackoverflow thread.

>>>Check out or download the source from my github account if you are interested<<<

Tags: activemq, concurrency, java, queue, spring-jms

Eclipse 3.6 freezes at startup

Posted by: pureessence on: June 23, 2011

  • In: geeky | java
  • 2 Comments

My Eclipse 3.6 froze today at startup. I think what I did was that I clicked on the shortcut a bit too fast and two instances of Eclipse started running at the same time. I got an error message for one saying “workspace in use”. I killed the one that showed the error message but then my Eclipse will no longer start up.

I searched around for solutions.

The one that SORTA worked for me is below from here.

  • cd .metadata/.plugins
  • mv org.eclipse.core.resources org.eclipse.core.resources.bak
  • Start eclipse. (It should show an error message or an empty workspace because no project is found.)
  • Close all open editors tabs.
  • Exit eclipse.
  • rm -rf org.eclipse.core.resources (Delete the newly created directory.)
  • mv org.eclipse.core.resources.bak/ org.eclipse.core.resources (Restore the original directory.)
  • Start eclipse and start working. spacer

However, just doing that did not exactly solve my problem. I ended up going to the .metainfo/.plugins/org.eclipse.core.resources/.project directory and started deleting random project and trial on error. I finally found the project that was the culprit and fixed my issue.

Another suggestion by a coworker that has worked before if Eclipse freezes at startup is:

  • cd workspace\.metadata\.plugins\org.eclipse.ui.workbench
  • Make backup of workbench.xml
  • Edit workbench.xmlfile and remove all <editor> tags.
Tags: eclipse, freeze up

m2eclipse plugin jdk warning

Posted by: pureessence on: June 15, 2011

  • In: geeky | java
  • Leave a Comment

More info – old issue but I ran into it on every freaking machine at home.

After I installed the m2eclipse plugin on Eclipse 3.6, I keep getting the following warning on the console:

The Maven Integration requires that Eclipse be running in a JDK, beacuase a number of Maven core plugins are using jars from the JDK.

Please make sure the -vm options in eclipse.ini is pointing to a JDK and verify that Installed JREs are also using JDK installs.

The solution that worked for me is changing the shortcut properties for eclipse e.g.

C:\JAVA\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_25\bin\javaw.exe"

I couldn’t get the eclipse.ini updates to work for some stupid reason.

Tags: eclipse, m2eclipse, maven, plugin

Eclipse 3.6 Auto Static Import

Posted by: pureessence on: June 9, 2011

  • In: geeky | java
  • Leave a Comment

After I started using JUnit 4, I really want Eclipse to automatically import org.junit.Assert.* statically for me. So when I do ctrl+space on methods like assertTrue, it will do:

import static org.junit.Assert.*;

for me.

I’ve figured it out for a while but I’ve been noticing it conflicting with my save action -> organize imports setting.

I finally got fed up and decided to investigate a bit further today.

Below are screenshots of Eclipse version 3.6.

  • Preferences -> Java -> Editor -> Content Assit -> Favorites all of the paths you wish to import statically e.g. org.junit.Assert.*
    spacer
  • Then if you have Preferences -> Java -> Editor -> Save Actions -> Organize imports selected
    spacer

    Make sure you update Preferences -> Java -> Code Style -> Orangize Imports to have Number of static imports needed for .* (e.g. ‘java.lang.Math.*) to 1.
    spacer

    This way when you save your java files in Eclipse, it will not change your org.junit.Assert.* import to org.junit.Assert.assertTrue import. Otherwise it will require you to import again if you wish to use another method like assertFalse which in my opinion is annoying.

Tags: eclipse, static import

Grails: I will not use you

Posted by: pureessence on: June 8, 2011

  • In: geeky | java | rants
  • 2 Comments

After the cijug presentation on Grails, I’ve decided I will not use it.

I know Grails is hot and cool but I don’t like it. It’s probably just a personal preference.

Why don’t I want to use Grails

  • It’s built on spring and hibernate, so why not just use them directly?
  • It’s just adding another layer of complexity. Now if something goes wrong, you need to know grails (groovy) plus all of the frameworks it uses underneath.
  • The generation bit is nice but personally I want control over all of the magic. You will need to modify them anyway. So why not just write them from scratch and LEARN YOUR HTML? This reminds me of the old Microsoft FrontPage HTML generation that always bit my ass when I first started creating web pages. But it probably wouldn’t be as bad since Microsoft was targeting their own browsers with the HTML generated.
  • The URL mapping is stupid. Spring’s innate annotation style mapping is so much easier.
  • I’m not a fan of the taglib. Why do I ever want to write HTML in Java? It makes me feel dirty. Plus it’s harder to debug. Personally the only “taglib” I like is facelets’ version. It felt more like writing HTML.

The only thing I really liked about Grails based on the presentation is the orm custom mapping. I prefer that over hibernate’s innate xml or a

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.