Pure-Essence.Net

SPEL! I conquered you on a Friday!

Posted by: pureessence on: July 22, 2011

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:


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.

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.

Andy’s meatball recipe

Posted by: pureessence on: July 19, 2011

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

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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       				http://www.springframework.org/schema/jms http://www.springframework.org/schema/context/spring-jms-3.0.xsd
					http://activemq.apache.org/schema/core http://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: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Namespace Name
Key: http://activemq.apache.org/schema/core

Then add a second one:

Location: http://activemq.apache.org/schema/core/activemq-core-5.3.0.xsd
Key Type: Schema Location
Key: http://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<<<

Eclipse 3.6 freezes at startup

Posted by: pureessence on: June 23, 2011

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. :-)

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.

m2eclipse plugin jdk warning

Posted by: pureessence on: June 15, 2011

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.

Eclipse 3.6 Auto Static Import

Posted by: pureessence on: June 9, 2011

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.*
  • Then if you have Preferences -> Java -> Editor -> Save Actions -> Organize imports selected

    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.

    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.

Grails: I will not use you

Posted by: pureessence on: June 8, 2011

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 annotation.

class Person {
  String firstName
  static mapping = {
      table 'people'
      firstName column:'First_Name'
  }
}

But that’s hardly worth a complete switch.

During the whole presentation I was thinking of a pyramid:

I remember not too long ago Spring and Hibernate are the newest and coolest kids on the block. Now we are just piling it on. What will we add next? I mean do you still need know Java any more to support applications? You really just need tons and tons of framework knowledge. Where do you get these knowledge from school? They are not going to teach them in college.

So I upgraded to jQuery UI version 1.8.2 at work and thought that I should instead of using the autocomplete plugin which is deprecated, switch over to use the jQuery UI build-in autocomplete widget.

jQuery UI autocomplete widget is NOTHING like the original jQuery autocomplete plugin!!!

At least by jQuery UI version 1.8.2 it’s not.

The jQuery UI autocomplete widget is crap just like I remembered when it first came out.

Things I found that annoyed the heck out of me:

  • Highlight doesn’t work. Use this hack instead.
  • Must match doesn’t work. More info available here.
    I ended up using a separate javascript function I wrote.
    function jQueryUIAutoCompleteMustMatch(input) {
    	var found = 0;
    	
    	var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( jQuery.trim($(input).val()) ) + "$", "i" );
    	
    	jQuery.each($('.ui-autocomplete li'), function(i, val) {
    		if(jQuery.trim( $(val).text() ).match( matcher ) ) {
    			found = 1;
    		}
    	});
    	
    	if (found) {
    		return true;
    	} else {
    		$(input).val('');
    		return false;
    	}
    }
    

    inside of your autocomplete setup, do

    change: function(event, ui) {jQueryUIAutoCompleteMustMatch($(this));}
    

  • To mimic the scrollHeight property on the autocomplete plugin, you will need to use css overrides. More info here (Example).
    .ui-autocomplete {
    	max-height: 220px;
    	overflow-y: auto;
    	/* prevent horizontal scrollbar */
    	overflow-x: hidden;
    	/* add padding to account for vertical scrollbar */
    	padding-right: 20px;
    }
    /* IE 6 doesn't support max-height
     * we use height instead, but this forces the menu to always be this tall
     */
    * html .ui-autocomplete {
    	height: 220px;
    }
    

  • To mimic the behavior of the option formatResult in the original plugin, you may do something like:
    $( "#tags" ).autocomplete({
    	source: availableTags,
    	minLength: 0,
    	delay: 0,
    	close: function(event, ui) {
    		var numberOnly = $(this).val().match(/\d+/);
    		$(this).val(numberOnly);
    	}
    })
    ;
    

    Above is to format the result as number only.

  • If you want the pop up search results as soon as the user has the focus on the input without entering anything, you will need to bind the search call on the focus event of the input. More info here.
    I ended up with
    $(input).autocomplete({
    		source: list
    	})
    	.focus(function() {
    		$(this).autocomplete("search");
    	})
    	;
    
  • I finally recognized that the jQuery UI autocomplete widget has far fewer options you may set. For example, by version 1.8.2, below are the only options
    • disabled
    • appendTo
    • autoFocus
    • delay
    • minLength
    • position
    • source

    If you wish to get your autocomplete working the same as your old one, chances are you will need to add a lot more additional code/hack.

This is the biggest disappointment for me since I started using jQuery.

>>> My Example with everything configured the way I want <<<

Bubo loves his new toy

Posted by: pureessence on: June 5, 2011


While Mommy and Daddy were in Las Vegas…

Our Las Vegas Vacation

Posted by: pureessence on: June 4, 2011

We stayed at the MGM Grand hotel in Las Vegas from May 27th – June 3rd, 2011.

The Favorite Thing:
The climate. It’s just crazy to think you do not sweat after miles of walking in 90 degree weather because it’s not humid. My skin looks gorgeous here. There is no road construction because the asphalt just doesn’t break and bend like it is in Iowa.

The Least Favorite Thing:
The cigarettes smell. I’m totally ready to get out of this ash tray after a week of consistent second hand smoke.

The Biggest Disappointment:
Stack restaurant. You are not paying high prices for the food quality or quantity but rather the *hip* atmosphere. Unfortunately the atmosphere did not attract us. When the music was playing, the bass was so loud that I thought I was sitting on a massage chair. The hostess looked unfriendly and was more interested in sizing us up than seating us. I think the prices on the menu are filters for people. Stack is more of a yuppie pick up place than a restaurant.

The Happiest Memory:
We had a great time meeting the LV Cabbie especially our trip with him to Hoover Dam.

The Funniest Experience:
My husband was taking a dump in the bathroom. All of the time he was on the toilet, he was hearing the slot machine music. As soon as a big load came out, the music changed to the victorious winning fanfare. He was waiting for someone to open his stall and hand him some money. It was perfectly well timed.

The Shows:

  • Ron White’s show was excellent. The guy who opened up for him was hilarious.
  • Criss Angel’s show was great. Although the disappearance acts were getting a bit repetitive toward the end. He definitely added a nice touch of comedy to his show with his assistants.
    • My husband, Andy, ordered us front row seats. Criss did the “foresee the future” act. He tossed his arm band randomly into the audience and then had the person who got the band toss it randomly to another person and then another person. The three random people in the audience had Margret as the first name, Canada as the birth place and 7 as the favorite number respectively. In a chest placed in the mid air prior to the beginning of the show resided a piece of paper with “Margret, Canada, 7” written on it. After the act, Criss gave the paper to me. It’s nice to get a souvenir (photo) from the show but too bad it’s just an ordinary piece of paper. It’s hard to convince people of its origin.
  • The O show was ridiculously amazing. There are not enough adjectives in the English language to properly depict its magnificence. The stage, the performers and the musicians (they do most of their music LIVE) were all perfect. I feel proud they had to put the Chinese female acrobats toward the end of the show. Not much could look more impressive than that. After the show, I wanted to purchase some souvenirs of the Chinese girls but nothing even remotely represented them in their shop.

Other Reflections:

  • MGM Grand turned out to be a great hotel to stay at. We used our Jacuzzi spa (photo) every day we stayed. We enjoyed lounging around their lazy river and grand pools (photo 1 | photo 2 | photo 3 | photo 4 | photo 5 | photo 6). The top three hotels among the ones we visited are: MGM Grand, The Mirage and Rio.
  • Hoover Dam was extraordinary (photos). You feel insignificant in such a grand construction surrounded by beautiful water and mountains.
  • The fountains shows at Bellagio were breathtaking (video 1 | video 2). It was hard to believe they were giving out such artistic and well choreographed shows for free.
  • We are willing to stay at Rio next time. Even though it’s off the Strip, but with convenient free shuffle service and two ridiculously delicious buffets, World Carnival Buffet (video) and Village Seafood Buffet (video), it’s worth it.
  • We loved this little frozen yogurt place in the Mirage called Blizz. My husband found his new favorite flavor: pistachio.
  • The most commonly littered items are cigarette butts, beer bottles and nude women flyers.

Lessons Learned:

  • The maps they give out at the hotels are awfully deceiving and horribly out of scale. Just because it looks close on the map doesn’t necessarily mean it’s in walking distance.
  • Always have a cab company number handy. Flagging cabs doesn’t work here as well as in other big cities like Shanghai if you wander off the crowded areas.
  • If you want a good place to eat, ask a cab driver. If you want a great place to eat, ask a fat cab driver like the LV Cabbie. He recommended China Mama which turned out to be one of the best dining experiences we had in Las Vegas.
  • If you want to visit more of the surrounding suburbs and places where the locals go, I suggest you rent a car. Cab fare may stack up quickly if you do not.

The Photos:

Las Vegas Vacation | Hoover Dam | MGM Grand Pool

My most adorable Pomeranians

Categories

Archives

SocialVibe


Follow

Get every new post delivered to your Inbox.

Join 123 other followers