<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4223339596261940054</id><updated>2024-10-24T16:02:11.743-07:00</updated><category term="Java"/><category term="Scala"/><category term="JavaFX"/><category term="JavaScript"/><category term="SBT"/><category term="Squeryl"/><category term="concurrency"/><category term="deferred"/><category term="jQuery"/><category term="plugin"/><category term="web"/><title type='text'>J...ava...S...cala...</title><subtitle type='html'>My experience on Java, Scala and....JavaScript</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>5</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4223339596261940054.post-7265290447908789914</id><published>2011-12-25T23:26:00.000-08:00</published><updated>2012-01-03T21:45:09.552-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="plugin"/><category scheme="http://www.blogger.com/atom/ns#" term="SBT"/><category scheme="http://www.blogger.com/atom/ns#" term="Scala"/><category scheme="http://www.blogger.com/atom/ns#" term="web"/><title type='text'>SBT 0.11.x Web plugin</title><content type='html'>After moving from SBT 0.7.x to 0.10.x, I wasn&#39;t able to run any of my web applications on SBT. After searching the web and SBT mail list I found&amp;nbsp;&lt;a href=&quot;https://github.com/siasia/xsbt-web-plugin/&quot;&gt;https://github.com/siasia/xsbt-web-plugin/&lt;/a&gt;&amp;nbsp;which might be the only solution out there. However simply following the instructions on the &lt;a href=&quot;https://github.com/siasia/xsbt-web-plugin/wiki/&quot;&gt;Getting Started&lt;/a&gt;, I wasn&#39;t able to install the plugin successfully. But here is basically how it should be done, just like describe on the site.&lt;br /&gt;
&lt;br /&gt;
Add the following to &quot;project/plugin.sbt&quot;
&lt;br /&gt;
&lt;pre class=&quot;brush: scala&quot; name=&quot;code&quot;&gt;sbtVersion(v =&amp;gt; &quot;com.github.siasia&quot; %% &quot;xsbt-web-plugin&quot; % (v+&quot;-0.2.10&quot;))
&lt;/pre&gt;
Then the following to build.sbt
&lt;br /&gt;
&lt;pre class=&quot;brush: scala&quot; name=&quot;code&quot;&gt;seq(webSettings :_*)

libraryDependencies += &quot;org.mortbay.jetty&quot; % &quot;jetty&quot; % &quot;6.1.22&quot; % &quot;container&quot;
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Here is a few things to be careful of.&lt;br /&gt;
for plugin.sbt&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;you actually need this line before the sbtVersion declaration&lt;br /&gt;&lt;pre class=&quot;brush: scala&quot; name=&quot;code&quot;&gt;resolvers += &quot;Web plugin repo&quot; at &quot;http://siasia.github.com/maven2&quot;&lt;/pre&gt;
&amp;nbsp;&lt;/li&gt;
&lt;li&gt;the variable &quot;v&quot; inside sbtVersion is the version of you SBT, so for the time I tried to install it was 0.10.0. It actually caused problem which says the library of version 0.10.0-0.2.10 could not be found on any repository I defined.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
for build.sbt&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;just make sure the jetty is included as &quot;container&quot; and not anything else, ie &quot;compile&quot; or &quot;test&quot;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;br /&gt;
After some more searching I realized one thing. The plugin only has the newest version and only with the most updated or whichever version it chooses of SBT in its github repository. If you try to test out the maven URL with guessing versions, you will get page not exists response if the version you want does not exists on server, so you can&#39;t even browse a list to see which version of SBT it supports and what the most updated version is. Due to this lack of backward support of the web-plugin, I was forced to move to 0.11.2. After the update, I had to upgrade my eclipse plugin. For which, I was luck that the SBT &lt;a href=&quot;https://github.com/typesafehub/sbteclipse&quot;&gt;Eclipse plugin&lt;/a&gt; has an upgraded version for the new SBT. Since I only had the Eclipse plugin and no other plugin, I could work as normal after upgrade my plugin.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/7265290447908789914/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://lunajs.blogspot.com/2011/12/sbt-011x-web-plugin.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/7265290447908789914'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/7265290447908789914'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/2011/12/sbt-011x-web-plugin.html' title='SBT 0.11.x Web plugin'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4223339596261940054.post-2326684256878571794</id><published>2011-10-20T21:13:00.000-07:00</published><updated>2014-11-30T01:33:15.733-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="JavaFX"/><title type='text'>JavaFX 2.0 EventHandler &amp; EventFilter</title><content type='html'>Some clarification about addEventFilter and addEventHandler from my observation.&lt;br /&gt;
&lt;br /&gt;
Looking from the API they both take the exact same parameters. So what&#39;s the difference?&lt;br /&gt;
&lt;br /&gt;
Event Filters will be called before Event Handlers.&lt;br /&gt;
Call sequence:&lt;br /&gt;
&lt;br /&gt;
1. call all EventHandlers added with addEventFilter (most likely in order which they are added, but no guarantee). All EventHandlers will be called, even if any handlers called event.consume().&lt;br /&gt;
&lt;br /&gt;
2. call all EventHandlers added with addEventHandler, except those that with the same EventType which is handled in EventHandlers in step 1 and had called event.consume().&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot; name=&quot;code&quot;&gt;final TextField text&amp;nbsp;= new TextField(&quot;&quot;);

text.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;handler 1&quot;);
      event.consume();
    }
});
text.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;handler 2&quot;);
    }
});
    
text.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;filter 1&quot;);
    }
});
text.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;filter 2&quot;);
    }
});
&lt;/pre&gt;
&lt;br /&gt;
Output is like this:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;handler 1&lt;br /&gt;
&amp;gt;&amp;gt; handler 2&lt;br /&gt;
&lt;br /&gt;
As you can see there is no use calling event.consume() in the Handler phase.&lt;br /&gt;
&lt;br /&gt;
Now using event.consume() in the Filter phase:&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot; name=&quot;code&quot;&gt;final TextField text&amp;nbsp;= new TextField(&quot;&quot;);

text.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;handler 1&quot;);
      event.consume();
    }
});
text.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;handler 2&quot;);
    }
});
    
text.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;filter 1&quot;);
      event.consume();
    }
});
text.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {
      
    @Override
    public void handle(KeyEvent event) {
      System.out.println(&quot;filter 2&quot;);
    }
});
&lt;/pre&gt;
&lt;br /&gt;
The output is:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 2&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
There, the events of the same type in the Handler phase are no longer being called.&lt;br /&gt;
&lt;br /&gt;
One more thing, if the Filter event is listened on KeyEvent.KEY_TYPED and event.consume() is called, the default behavior of key will be consumed as well, which means no character will be printed out.&lt;br /&gt;
&lt;br /&gt;
To make the example more complete (&lt;i&gt;Thanks to Peter Moufarrej&lt;/i&gt;), let&#39;s add parent-child idea into the scene. Suppose the TextField is inside a GridPane and have all the same EventHandlers and EventFilters as the TextField.
&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot; name=&quot;code&quot;&gt;grid.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {

    @Override
    public void handle(KeyEvent event) {
        System.out.println(&quot;grid handler 1&quot;);
        event.consume();
    }
});
grid.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {

    @Override
    public void handle(KeyEvent event) {
        System.out.println(&quot;grid handler 2&quot;);
    }
});

grid.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {

    @Override
    public void handle(KeyEvent event) {
        System.out.println(&quot;grid filter 1&quot;);
        event.consume();
    }
});
grid.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler&amp;lt;KeyEvent&amp;gt;() {

    @Override
    public void handle(KeyEvent event) {
        System.out.println(&quot;grid filter 2&quot;);
    }
});
&lt;/pre&gt;
&lt;br /&gt;
The output is:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; grid filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid filter 2&lt;br /&gt;
&lt;br /&gt;
Suppose we comment out the event.consume() inside gride&#39;s EventFilter.
&lt;br /&gt;
The output is:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; grid filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 2&lt;br /&gt;
&lt;br /&gt;
Let&#39;s comment out the event.consume() inside text&#39;s EventFilter.
&lt;br /&gt;
The output is:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; grid filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;handler 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;handler 2&lt;br /&gt;
&lt;br /&gt;
If we take out all the event.consume()
The output is:&lt;br /&gt;
&lt;br /&gt;
&amp;gt;&amp;gt; grid filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;filter 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;handler 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;handler 2&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid handler 1&lt;br /&gt;
&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt;&lt;span style=&quot;background-color: transparent;&quot;&gt;&amp;nbsp;&lt;/span&gt;grid handler 2&lt;br /&gt;
&lt;br /&gt;
As you can see the execution order is from parent.eventFilter -&amp;gt; child.eventFilter -&amp;gt; child.eventHandler -&amp;gt; parent.evenHandler. The EventFilter phase is like the Event Capture phase and EventHandler is like the Event Bubble phase of JavaScript.</content><link rel='replies' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/2326684256878571794/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://lunajs.blogspot.com/2011/10/javafx-20-eventhandler-eventfilter.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/2326684256878571794'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/2326684256878571794'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/2011/10/javafx-20-eventhandler-eventfilter.html' title='JavaFX 2.0 EventHandler &amp; EventFilter'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4223339596261940054.post-151017378320446622</id><published>2011-07-01T01:44:00.001-07:00</published><updated>2020-08-13T23:24:12.748-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="deferred"/><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript"/><category scheme="http://www.blogger.com/atom/ns#" term="jQuery"/><title type='text'>jQuery Deferred In Use</title><content type='html'>Since jQuery 1.5, Deferred was introduced in the framework and the whole Ajax module was rewritten with it. Deferred is implemented based on the &lt;a href=&quot;http://wiki.commonjs.org/wiki/Promises/A&quot;&gt;Promise/A&lt;/a&gt; design. I had heard of this concept before but never paid much attention to it until jQuery, which I use a lot of, implemented it. I realized the power of it, but never got a chance to use it until now.&lt;br /&gt;
&lt;br /&gt;
Now I am faced with a problem (probably a design flaw from the beginning). I am using a jQuery plugin called &lt;a href=&quot;http://www.jplayer.org/&quot;&gt;jPlayer&lt;/a&gt;, which is a great library for playing sound on web pages. In order to simply the use of jPlayer, I decided to write a method that will play sound for a given sound URL path, so that everyone using it will just have to give the path of the sound file to play and not have to worry about anything else. So, on every page that uses jPlayer, I instantiate/setup an instance of jPlayer so it can be reused (only one sound will be played at once) for every sound file.&lt;br /&gt;
Code looks like:&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;javascript&#39;&gt;$(function() {
  var $jp = $(&quot;#jplayer&quot;);
  if ($jp.length == 0) {
    $jp = $(&quot;&amp;lt;div id=&quot;jplayer&quot;&amp;gt;&amp;lt;/div&amp;gt;&quot;);
    $(&quot;body&quot;).append($jp)
  }
  
  $jp.jPlayer({
      &quot;swfPath&quot; : &quot;../js&quot;,
      &quot;solution&quot; : &quot;flash, html&quot;,
      &quot;ready&quot; : function () {
        console.log(&quot;player ready&quot;)
        //setMedia must be called here
      },
      &quot;supplied&quot; : &quot;mp3&quot;,
      &quot;preload&quot; : &quot;none&quot; //auto
  });
});

function playMusic(musicSrc) {
  console.log(&quot;play music: &quot;+musicSrc);
  $(&quot;#jplayer&quot;).jPlayer(&quot;setMedia&quot;, {&quot;mp3&quot; : musicSrc}).jPlayer(&quot;play&quot;); 
}
&lt;/code&gt;&lt;/pre&gt;The method &lt;i&gt;playMusic&lt;/i&gt; is exposed for use.&lt;br /&gt;
({&quot;solution&quot; : &quot;flash, html&quot;} is there to make sure FF uses Flash. In most IE, it will use Flash automatically.)&lt;br /&gt;
&lt;br /&gt;
Notice the &quot;&lt;i&gt;ready&lt;/i&gt;&quot; parameter in jPlayer&#39;s constructor. It is a callback for the constructor. The reason for it is because in some browser Flash is required to play sound file, and the loading time of Flash is unknown and asynchronous. The callback is to tell you when the Flash is ready then you can play your sound. If is not ready and you play, nothing will happen and you&#39;re left in the dark to wonder why.&lt;br /&gt;
This worked fine for most of the cases, since, up and until I see my problem, all my use cases were that user will click something to trigger the play. And by that time, Flash is most likely to be loaded. Yes, it&#39;s a dangerous assumption.&lt;br /&gt;
&lt;br /&gt;
Now the problem comes when I need to play sound when the page finished loading. If I simply add a line like this&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;javascript&#39;&gt;window.onload = function(){
  playMusic(&quot;../images/applause.mp3&quot;);
}
&lt;/code&gt;&lt;/pre&gt;or simply&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;javascript&#39;&gt;playMusic(&quot;../images/applause.mp3&quot;);
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
These don&#39;t work.&lt;br /&gt;
For the first case, Flash is not&amp;nbsp;necessarily&amp;nbsp;ready when &lt;i&gt;playMusic &lt;/i&gt;is called.&lt;br /&gt;
The second case has the following output from Firebug and obvious don&#39;t work:&lt;br /&gt;
&lt;blockquote&gt;&lt;div class=&quot;logRow logRow-log&quot;&gt;&lt;span class=&quot;objectBox objectBox-text &quot; role=&quot;presentation&quot;&gt;play music: ../images/applause.mp3&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;logRow logRow-log&quot;&gt;&lt;span class=&quot;objectBox objectBox-text &quot; role=&quot;presentation&quot;&gt;player ready&lt;/span&gt;&lt;/div&gt;&lt;/blockquote&gt;&amp;nbsp;Now, without changing any API, I need a way to get my function or sound played when the Flash is ready. Here is where Deferred comes into play.&lt;br /&gt;
I simply has to instantiate an instance of Deferred and let my&amp;nbsp;&lt;i&gt;playMusic &lt;/i&gt;passes every call to the Deferred.&lt;br /&gt;
And resolves the Deferred when Flash is ready. This way all calls to&amp;nbsp;&lt;i&gt;playMusic &lt;/i&gt;will queued up in the Deferred before it is resolved, and if it is resolved, the function will be called immediately. Also, this way I don&#39;t have to worry about when and where I am calling&amp;nbsp;&lt;i&gt;playMusic&lt;/i&gt;.&lt;br /&gt;
Here is the new code:&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;javascript&#39;&gt;var jplayerDeferred = $.Deferred();
$(function() {
  var $jp = $(&quot;#jplayer&quot;);
  if ($jp.length == 0) {
    $jp = $(&quot;&amp;lt;div id=&quot;jplayer&quot;&amp;gt;&amp;lt;/div&amp;gt;&quot;);
    $(&quot;body&quot;).append($jp)
  }
  
  $jp.jPlayer({
      &quot;swfPath&quot; : &quot;../js&quot;,
      &quot;solution&quot; : &quot;flash, html&quot;,
      &quot;ready&quot; : function () {
        console.log(&quot;player ready&quot;)
        //setMedia must be called here
        jplayerDeferred.resolve();
      },
      &quot;supplied&quot; : &quot;mp3&quot;,
      &quot;preload&quot; : &quot;none&quot; //auto
  });
  
});

function playMusic(musicSrc) {
    
  jplayerDeferred.done(function(){
    console.log(&quot;play music: &quot;+musicSrc);
    $(&quot;#jplayer&quot;).jPlayer(&quot;setMedia&quot;, {&quot;mp3&quot; : musicSrc}).jPlayer(&quot;play&quot;); 
  });

}

&lt;/code&gt;&lt;/pre&gt;Then I can just call it like this right after.&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;javascript&#39;&gt;playMusic(&quot;../images/applause.mp3&quot;);
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Now as soon as the Flash gets loaded, the sound is played. Here is the output from Firebug.&lt;br /&gt;
&lt;blockquote&gt;&lt;div class=&quot;logRow logRow-log&quot;&gt;&lt;span class=&quot;objectBox objectBox-text &quot; role=&quot;presentation&quot;&gt;player ready&lt;/span&gt;&lt;/div&gt;&lt;div class=&quot;logRow logRow-log&quot;&gt;&lt;span class=&quot;objectBox objectBox-text &quot; role=&quot;presentation&quot;&gt;play music: ../images/applause.mp3&lt;/span&gt;&lt;/div&gt;&lt;/blockquote&gt;


&lt;link rel=&quot;stylesheet&quot;
      href=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/androidstudio.min.css&quot;&gt;
&lt;script src=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;hljs.initHighlightingOnLoad();&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/151017378320446622/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://lunajs.blogspot.com/2011/07/jquery-deferred-in-use.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/151017378320446622'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/151017378320446622'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/2011/07/jquery-deferred-in-use.html' title='jQuery Deferred In Use'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4223339596261940054.post-6536612347877391018</id><published>2011-06-30T02:32:00.001-07:00</published><updated>2020-08-13T23:16:20.057-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="concurrency"/><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Scala"/><title type='text'>Concurrency Pitfalls and More?</title><content type='html'>Read the&amp;nbsp;&lt;a href=&quot;http://weblogs.java.net/blog/cayhorstmann/archive/2011/05/04/dozen-concurrency-pitfalls&quot;&gt;A Dozen Concurrency Pitfalls&lt;/a&gt;&amp;nbsp;a while back and began to search and asking for correct answers. Yes, there are some people posting too like &lt;a href=&quot;http://blog.darevay.com/2011/05/java-concurrency-pitfalls-in-scala-answers/&quot;&gt;here&lt;/a&gt;. So this is mainly note to myself.&lt;br /&gt;
&lt;br /&gt;
Here are the question and answer&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;val stopMe = new Runnable {
  private var stop = false
  override def run() { while (!stop) doSomething(); println(&quot;Stopped&quot;) }
  def stopTask() { stop = true }
}
new Thread(stopMe).start()
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;no synchronization, no guarantee that the value changed for      &quot;stop&quot; will ever be seen&lt;/li&gt;
&lt;li&gt;&lt;span data-jsid=&quot;text&quot;&gt;&amp;nbsp;stop is not volatile so jvm spec cant guarantee the changed stop value to be visible among threads&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class MyTask implements Runnable {
  private val done = new ArrayBlockingQueue[String](1)
  private val stop = new AtomicBoolean

  public void run() {
    while (!stop.get()) doSomething() 
    done.put(&quot;DONE&quot;)
  }

  public void stopNow() {
    stop.set(false)
    done.take() // Wait until run completes
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;span data-jsid=&quot;text&quot;&gt;&amp;nbsp;&lt;/span&gt;if doSomething() call stopNow(), then...deadlock?&lt;/li&gt;
&lt;li&gt;&lt;span data-jsid=&quot;text&quot;&gt;stop.set(false) invocation should be stop.set(true)&lt;/span&gt; &lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class BackgroundTask(iters: Int) extends Runnable {
  override def run() { for (i &amp;lt;- 1 to iters) doSomething() }
}
new Thread(new BackgroundTask(1000)).run()
println(&quot;Started backgroundTask&quot;)
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;should call &quot;start()&quot; instead of &quot;run()&quot;. I do that all the time &lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;val items = new ConcurrentHashMap[String, Int]
 ...
val keys = items.keySet().toArray
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;values when keySet() is called may not be the same when toArray is      finished, therefore, result maybe unintended&lt;/li&gt;
&lt;li&gt; &lt;span data-jsid=&quot;text&quot;&gt;&lt;span class=&quot;text_exposed_show&quot;&gt;val keys =  items.keySet().toArray has no sense if it is not run in  keys.synchronized block - other threads may change items and toArray  will throw ConcurrentModificationExce&lt;wbr&gt;&lt;/wbr&gt;&lt;span class=&quot;word_break&quot;&gt;&lt;/span&gt;ption&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Stack {
  private val myLock = &quot;LOCK&quot;  

  def push(newValue: Int) {
    myLock.synchronized {
      ...
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;String constant is shared in Java, all Stack will use the same      &quot;LOCK&quot; &lt;/li&gt;
&lt;li&gt;&lt;span data-jsid=&quot;text&quot;&gt;&lt;span class=&quot;text_exposed_show&quot;&gt; &quot;LOCK&quot; String is  pointing to instance in JVM`s internal strings cache (somewhere in  String class) - this synchronized method may cause much &quot;wider&quot;  synchronization than it seems (global lock on all non-new &quot;Lock&quot;  Strings)&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Stack {
  ...
  def push(newValue: Int) {
    new String(&quot;LOCK&quot;).synchronized {
      ...
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;new.......every push call creates a new lock object......nothing is really      synchronized with it&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Stack {
  private var values = new Array[Int](10)
  private var size = 0

  def push(newValue: Int) {
    values.synchronized {
      if (size &amp;gt; values.size) reallocate()
      values(size) = newValue
      size += 1
    }
  }
  ...
  private def reallocate() {
    values = values ++ new Array[Int](values.size)
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;everytime &quot;reallocate()&quot; is called the reference of      &quot;values&quot;  changes, therefore similar to &quot;releasing&quot; the      lock unintentionally &lt;/li&gt;
&lt;/ul&gt;&lt;pre class=&quot;brush: scala&quot;&gt;class Stack {
  private val myLock = new ReentrantLock
  private val cond = myLock.newCondition()
  ...
  def pop() = {
    myLock.lock()
    try {    
      do { cond.await() } while (size == 0) 
      size -= 1
      values(size)
    } finally { myLock.unlock() }
  }
}
&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;should always do while-do instead of do-while &lt;/li&gt;
&lt;li&gt;A do/while is used for the condition variable rather than just while. If cond is in a signaled state initially, the condition that size is zero may not be checked&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Stack {
  private val myLock = new ReentrantLock
  private var values = new Array[Int](10)
  private var size = 0 
  ...
  def write(fileName: String) {   
    myLock.lock()
    val out = new PrintWriter(fileName)
    try {
      out.println(size + &quot; &quot; + values.mkString(&quot; &quot;))
    } finally {  
      out.close()
      myLock.unlock()
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;out.close() might throw exception, causing myLock.unlock() to never get called&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;val queue = new ArrayBlockingQueue[String](10)
val button = new JButton(&quot;Start&quot;)
button.addActionListener(new ActionListener {
  override def actionPerformed(event: ActionEvent) {
    queue.put(event.toString)
  }
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;if queue.put is blocked, as queue is full, the main UI thread will be      blocked &lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Model {
  private val myLock = new ReentrantLock
  private def withMyLock(block: =&amp;gt; Unit) { 
    myLock.lock(); try { block } finally { myLock.unlock() ; }
  }

  private val listeners = new ArrayBuffer[ChangeListener]
  
  def addListener(l: ChangeListener) { withMyLock { listeners += l } }
  def removeListener(l: ChangeListener) { withMyLock { listeners -= l } }
  def fireListeners() {
    withMyLock {
      for (l &amp;lt;- listeners) l.stateChanged(new ChangeEvent(this))
    }
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;since ChangeListener is implemented by other ppl, if they call  addListener      or removeListener in there listener then unexpected  behavior might occur      (in fireListeners)&lt;/li&gt;
&lt;li&gt;should use CopyOnWriteArrayList in order to allow a listener to call add/remove listener when the event is being dispatched without causing a CME and/or deadlock&lt;/li&gt;
&lt;/ul&gt;&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;val queue = new ArrayBlockingQueue[String](10)
val formatter = new SimpleDateFormat(&quot;MMM dd HH:mm:ss&quot;)
class MyTask extends Runnable {
  override def run() {
    Object result = doSomething()
    queue.put(formatter.format(new Date) + &quot; &quot; + result)
  }
}
for (i &amp;lt;- 1 to 10) { new Thread(new MyTask).start() }
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;simple....................because SimpleDateFormat is too simple to run in multi-thread.......lol. refer to &lt;a href=&quot;http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html&quot;&gt;JavaDoc&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class Stack(val maxSize: Int) {
  private val array = new ArrayDeque[Int]

  def put(value: Int) {
    array.synchronized {
      while(array.size == maxSize) {
        wait()
      }
      array.add(value)
    }
  }
  ...
}
&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&amp;nbsp;&lt;span data-jsid=&quot;text&quot;&gt;&lt;span class=&quot;text_exposed_show&quot;&gt; synchronizes on this.array but waits on this = IllegalMonitorStateExcepti&lt;wbr&gt;&lt;/wbr&gt;&lt;span class=&quot;word_break&quot;&gt;&lt;/span&gt;on&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;u&gt;&lt;b&gt;Some Other:&lt;/b&gt;&lt;/u&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;public class MyServlet implements Servlet{
    private Object something;

    public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
        this.something = request.getAttribute(&quot;something&quot;);
        doSomething();
    }

    private void doSomething(){
        this.something ...
    }
}&lt;/code&gt;&lt;/pre&gt;Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Servlet is Singleton in a container. Mutating a instance field will result in unexpected behavior of other process on running this Servlet &lt;/li&gt;
&lt;/ul&gt;&lt;b&gt;&lt;br /&gt;
&lt;a href=&quot;http://en.wikipedia.org/wiki/Double-checked_locking&quot;&gt;Double-Checked Locking idiom &lt;/a&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;java&#39;&gt;// Broken multithreaded version
// &quot;Double-Checked Locking&quot; idiom
class Foo {
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null) {
       synchronized(this) {
         if (helper == null) {
            helper = new Helper();
         }
       }
    }
    return helper;
  }
  // other functions and members...
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Answer:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;When thread A is creating a new instance of Helper, thread B may come in and see that &quot;&lt;i&gt;helper&lt;/i&gt;&quot; is no longer &lt;i&gt;null&lt;/i&gt; and uses the not-fully-instantiated instance&lt;/li&gt;
&lt;/ul&gt;

&lt;link rel=&quot;stylesheet&quot;
      href=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/androidstudio.min.css&quot;&gt;
&lt;script src=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;hljs.initHighlightingOnLoad();&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/6536612347877391018/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://lunajs.blogspot.com/2011/06/concurrency-pitfalls-and-more.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/6536612347877391018'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/6536612347877391018'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/2011/06/concurrency-pitfalls-and-more.html' title='Concurrency Pitfalls and More?'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4223339596261940054.post-8201341970033872473</id><published>2011-06-28T02:19:00.003-07:00</published><updated>2020-08-13T23:11:17.671-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java"/><category scheme="http://www.blogger.com/atom/ns#" term="Scala"/><category scheme="http://www.blogger.com/atom/ns#" term="Squeryl"/><title type='text'>Squeryl with Java Experiment</title><content type='html'>This is an attempt to use the popular Scala ORM/DSL &lt;a href=&quot;http://squeryl.org/index.html&quot;&gt;Squeryl &lt;/a&gt;with plain Java code.&amp;nbsp;I had been watching Squeryl grow for a while and loved the syntax and style since the beginning, but never had a chance to actually use it. The first attempt I had with it was trying to use it with &lt;a href=&quot;http://www.assembla.com/spaces/liftweb/wiki/Squeryl&quot;&gt;Squeryl-Record&lt;/a&gt; module in &lt;a href=&quot;http://liftweb.net/&quot;&gt;Lift&lt;/a&gt;. However at the time, it was just too much to handle for someone who is quite new to Scala, Record and Squeryl. So, I took a step back and start with just Squeryl and try to connect with Java, which am familiar with, and see if it&#39;s really that &quot;straight forward&quot; as it says on the &lt;a href=&quot;http://squeryl.org/using-in-java.html&quot;&gt;site&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
I use Squeryl 0.9.4 built against Scala 2.9.0.&lt;br /&gt;
&lt;br /&gt;
First thing, it is not directly possible to make Squeryl looks 100% Java, due to the nature that Squeryl requires its model class to be defined in Scala. Of course, you can always map the Scala model to a Java counter part.&lt;br /&gt;
&lt;br /&gt;
Alright let&#39;s get on it.&lt;br /&gt;
&lt;div&gt;(I am using a real world DAO Java interface from one of my project, by only changing the model to be implemented by Scala)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;According to point 2 of &quot;&lt;a href=&quot;http://squeryl.org/using-in-java.html&quot;&gt;Using in a Java project&lt;/a&gt;&quot; (oh wait, all 3 points are labeled &quot;1&quot;), define Schema class in Scala.&lt;/div&gt;&lt;div&gt;Here is my Schema:&lt;/div&gt;&lt;div&gt;
  &lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;abstract class BaseEntity extends KeyedEntity[Long] {
  @BeanProperty
  var id: Long = 0
  @BeanProperty
  var createDate: Timestamp = new Timestamp(System.currentTimeMillis)
}

@BeanInfo
class Members(@BeanProperty var name: String, @BeanProperty var email: String) extends BaseEntity

@BeanInfo
class Categories(@BeanProperty var code: String, 
    @BeanProperty var name: String, 
    @BeanProperty var sequence: Int, 
    @BeanProperty var parentId: Long) extends BaseEntity

@BeanInfo
class Articles(@BeanProperty var categoryId: Long, 
    @BeanProperty var name: String, 
    @BeanProperty var sound1Url: String, 
    @BeanProperty var sound2Url: String, 
    @BeanProperty var imageUrl: String, 
    @BeanProperty var estimatedDuration: Int, 
    @BeanProperty var clickCount: Int) extends BaseEntity {
    def this() = this(null.asInstanceOf[Long], null, null, null,&amp;nbsp;
          null, null.asInstanceOf[Int], null.asInstanceOf[Int])
}

object Models extends Schema {
  
  val members = table[Members]
  
  val categories = table[Categories]
  
  val articles = table[Articles]
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Here I am making all model properties &lt;i&gt;var&lt;/i&gt; instead of &lt;i&gt;val&lt;/i&gt; so it behaves like what Java objects usually behaves, mutable.&lt;br /&gt;
One thing to notice here is that, in my original Java version of the models, I have all the Int as java.lang.Integer, and Long as java.lang.Long. Therefore, I could have NULL for my number properties. However, in Scala Int and Long actually maps to Java&#39;s int and long, so there will always be the default value of 0. In the Articles model&#39;s zero-argument constructor, I am simply&amp;nbsp;demonstrating&amp;nbsp;that setting the values to null won&#39;t set the field to NULL.&lt;br /&gt;
In the site it says&lt;br /&gt;
&lt;blockquote&gt;&quot;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: verdana, &#39;Lucida Grande&#39;, arial, helvetica, sans-serif; font-size: 12px; line-height: 18px;&quot;&gt;@BeanInfo annotations, this will cause the compiler to generate Java style getters and setters for every property, the class will then look exactly like POJOs in the Java code&lt;/span&gt;&quot;&lt;/blockquote&gt;However this will only make the model class usable to by Java but does not actually properly generate the Java getter/setter, so @BeanProperty is still necessary for each property.&amp;nbsp;Here is what you get for not using @BeanProperty&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVVRJKQGSA1YyAwUlFQmJ4VVDLpA2jhj30GVFXtltqgXpR92fgom1jpTA8fxwzxjL9L0IdSFSb0WN_5O82ir2TJ8j2aFqHtBKas_JjmwhOR4SV-h1c1datUKnWutQGv_LI_9tC54zyP8I/s1600/2011-6-28+%25E4%25B8%258B%25E5%258D%2588+02-52-01.png&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;75&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVVRJKQGSA1YyAwUlFQmJ4VVDLpA2jhj30GVFXtltqgXpR92fgom1jpTA8fxwzxjL9L0IdSFSb0WN_5O82ir2TJ8j2aFqHtBKas_JjmwhOR4SV-h1c1datUKnWutQGv_LI_9tC54zyP8I/s320/2011-6-28+%25E4%25B8%258B%25E5%258D%2588+02-52-01.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Also implement a zero-argument constructor for each model class, so other Java code can instantiate the model class like the way usual Java code does.&lt;br /&gt;
&lt;br /&gt;
Next, define the DAO. Here I use a DAO interface taken from my project and just changed the model class to the new Scala implemented model&lt;br /&gt;
&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;java&#39;&gt;public interface ArticlesDao {

  public boolean existsByCategory(Long categoryId);
  
  public Articles findById(Long id);
  
  public int deleteById(Long id);
  
  public List&amp;lt;Articles&amp;gt; findByCategory(Long categoryId);
  
  public int insert(Articles articles);
  
  public int update(Articles articles);
  
  public List&amp;lt;Articles&amp;gt; findTopCountArticles(int top);
  
  public int addClickCount(Long id, int count);
}
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
And let&#39;s start the fun by implementing it with Squeryl&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;package com.netgents.dw.dao.scala

import java.lang.{Long =&amp;gt; JLong}
import java.util.List
import scala.collection.JavaConversions._
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.SessionFactory
import org.squeryl.Session
import com.netgents.dw.dao.ArticlesDao
import com.netgents.dw.model.Models._
import com.netgents.dw.model.Articles
import org.springframework.stereotype.Repository

@Repository(&quot;scala.articlesDao&quot;)
class ArticlesDaoImpl extends ArticlesDao {
  
  def existsByCategory(categoryId: JLong): Boolean = 
    byCategory(categoryId).headOption.map(_ =&amp;gt; true).getOrElse(false)
  
  def findById(id: JLong): Articles =
    articles.lookup(id.longValue).getOrElse(null)
  
  def deleteById(id: JLong): Int = 
    if(articles.delete(id.longValue)) 1 else 0
  
  def findByCategory(categoryId: JLong): List[Articles] = 
    byCategory(categoryId).toList
  
  private def byCategory(categoryId: JLong) =
    from(articles) (a =&amp;gt; 
      where(a.categoryId === categoryId.longValue) 
      select(a) 
      orderBy(a.id))
  
  def insert(a: Articles): Int = {
    articles.insert(a)
    1
  }
  
  def update(a: Articles): Int = {
    articles.update(a)
    1
  }
  
  def findTopCountArticles(top: Int): List[Articles] =
    from(articles)(a =&amp;gt; 
      select(a) 
      orderBy(a.clickCount desc)).take(top).toList

  def addClickCount(id: JLong, count: Int): Int = {
    org.squeryl.PrimitiveTypeMode.update(articles)(a =&amp;gt; //dont know why i cant just use update without specifying full class package
      where(a.id === id.longValue)
      set(a.clickCount := a.clickCount.~ + count))
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Here are some basic and small things to notice. Because we are basically working with Java , we need to give java.util.Long an alias, so we can work with it easier. And add&amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: monospace; white-space: pre;&quot;&gt;import scala.collection.JavaConversions._ &lt;/span&gt;to make Scala List convert to Java List.&lt;br /&gt;
&lt;br /&gt;
Here are some problems I encountered&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Due to the requirement of original API both insert and update are required to return the number of records affected. However, both insert and update in the &lt;a href=&quot;http://squeryl.org/api/index.html#org.squeryl.Table&quot;&gt;Table&lt;/a&gt;&amp;nbsp;don&#39;t return the number of records affected. Insert returns the inserted instance with id populated. Update simply returns Unit. I am not sure if what will happen if something goes wrong in database and the database doesn&#39;t give any error and just returned 0 as number of affected records (I have encountered that with a version of MS SQL2005), or when update did not find any record to update, so for now I can only assume 1 record is affected as long as there is no exception (actual effect explained later).&lt;/li&gt;
&lt;li&gt;not sure how to do top/limit SQL directly, except by using &quot;take&quot;. (I am sure it&#39;s just because I didn&#39;t look hard enough)&lt;/li&gt;
&lt;/ol&gt;&lt;br /&gt;
Alright, you might have noticed I did not use any transaction {} or inTransaction {}. This is because I am planning to put my transaction control in my Service level.&lt;br /&gt;
&lt;br /&gt;
As you may have noticed my usage of the @Repository annotation, yes I will be using &lt;a href=&quot;http://www.springsource.org/&quot;&gt;Spring&lt;/a&gt; to take care of my transaction. In order to make Squeryl work with Spring or any outside transaction support, you have to use the &lt;a href=&quot;http://sessionfactory.externaltransactionmanagementadapter/&quot;&gt;SessionFactory.externalTransactionManagementAdapter&lt;/a&gt;&amp;nbsp;instead of the good old&amp;nbsp;SessionFactory.concreteFactory. And this is the way to use Squeryl without wrapping inside transaction/inTransaction {}. However, there are more things to be done than just implementing this method. According to the document,&amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: Arial, sans-serif; font-size: 13px;&quot;&gt;Session.cleanupResources&amp;nbsp;&lt;/span&gt;needs to be called manually when your done with the connection. Since I use Spring&#39;s annotated transaction, I decide to write my own TransactionManager.&lt;br /&gt;
Here is my implementation:&lt;br /&gt;
&lt;pre&gt;&lt;code class=&#39;scala&#39;&gt;class MyDataSourceTransactionManager extends DataSourceTransactionManager {

  @PostConstruct
  def init() {
    SessionFactory.externalTransactionManagementAdapter = Some(() =&amp;gt; {
      if(Session.hasCurrentSession) {
        Session.currentSessionOption.get
      }
      else {
 
        val s = new Session(DataSourceUtils.getConnection(getDataSource), 
                    new MySQLAdapter, None){
          override def cleanup = {
            super.cleanup
            unbindFromCurrentThread
          }
        }
        //Session.create(DataSourceUtils.getConnection(getDataSource), new MySQLAdapter)
        s.bindToCurrentThread
        s
      }
    })
  
  }
  
  override def doCleanupAfterCompletion(transaction: AnyRef) {

    super.doCleanupAfterCompletion(transaction)
    Session.cleanupResources //clean up resources when done, following the doc
  }

}
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
The problems I faced here are&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Session needs to be controlled by myself so that all query made in the same transaction will get the same Session. Here I leverage the built-in Session storing mechanism, bindToCurrentThread.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Since I am using s.bindToCurrentThread, I need to unbind when I am done. However Session.cleanupResources doesn&#39;t do that and I don&#39;t have direct access to unbindFromCurrentThread, so I override the Session&#39;s implementation to call unbindFromCurrentThread when cleanup is called.&lt;/li&gt;
&lt;/ol&gt;&lt;div&gt;One small tip here is that since I am using Spring&#39;s transaction control, when getting Connection, I have to use&amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: monospace; white-space: pre;&quot;&gt;DataSourceUtils.getConnection(getDataSource) &lt;/span&gt;instead of simply &amp;nbsp;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: monospace; white-space: pre;&quot;&gt;getDataSource.&lt;/span&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-family: monospace; white-space: pre;&quot;&gt;getConnection.&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div&gt;There, that&#39;s about it, the rest can be plain Java and not to worry that the DAO is in Scala&lt;br /&gt;
&lt;br /&gt;
Let&#39;s do a little test.&lt;br /&gt;
&lt;br /&gt;
I will leave out the detail of Service implement because it&#39;s mostly mapping of 1 to 1 method call to DAO.&lt;br /&gt;
&lt;br /&gt;
Here is my test class&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;&lt;pre&gt;&lt;code class=&#39;java&#39;&gt;@Test(expected = RuntimeException.class)
public void test1() {

  Articles a = new Articles();
  a.setId(234);
  a.setCategoryId(1L);
  a.setEstimatedDuration(100);
  a.setName(&quot;Article 1&quot;);
  a.setSound1Url(&quot;sound url 1&quot;);
  a.setSound2Url(&quot;sound url 2&quot;);
  a.setImageUrl(&quot;image url&quot;);
  a.setClickCount(6);
  articlesService.insert(a);
    
  assertEquals(1L, a.getId());//id should be set to 1 after insert
    
  a.setSound1Url(null);
  a.setImageUrl(&quot;image url updated&quot;);
    
  articlesService.update(a);
    
  a = articlesService.findById(new Long(1));
    
  assertNotNull(a);//a should not be null
  assertNull(a.getSound1Url());//should be null now
  assertEquals(&quot;image url updated&quot;, a.getImageUrl());
  
  articlesService.deleteById(new Long(1));
  
  a = articlesService.findById(new Long(1));
    
  assertNull(a);//should be deleted

  //lets see if not record is found to update
  a = new Articles();
  a.setId(artId);
  a.setCategoryId(new Long(34));
  a.setEstimatedDuration(321);
  a.setImageUrl(&quot;another image url&quot;);
  articlesService.update(a);//will throw a RuntimeException: failed to update
}
  
@Test
public void transaction() {
    
  articlesService.goodInsertsActions();
  
  List&amp;lt;articles&amp;gt; as = articlesService.findByCategory(new Long(1));
  
  assertEquals(60, as.size());//inserted 60 records

  //test to see if transaction works
  try {
    articlesService.badInsertsActions();
  }
  catch(Exception e) {
    System.out.println(&quot;error message: &quot;+e.getMessage());
  }
  as = articlesService.findByCategory(new Long(1));
    
  assertEquals(60, as.size());//worked, number of records stayed at 60    
}
&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;Here is what I do in &lt;i&gt;goodInsertsAction&lt;/i&gt; and &lt;i&gt;badInsertsAction&lt;/i&gt;&lt;/div&gt;&lt;pre&gt;&lt;code class=&#39;java&#39;&gt;@Override
public void goodInsertsActions() {
  doInserts();
}

@Override
public void badInsertsActions() {
  doInserts();
  throw new DataIntegrityViolationException(&quot;hell with it&quot;);
}

private void doInserts() {
  Articles a;
  for(int i = 1; i &amp;lt;= 60; i++) {
    a = new Articles();
    a.setCategoryId(1L);
    a.setEstimatedDuration(100);
    a.setName(&quot;Article &quot; + i);
    a.setSound1Url(&quot;sound url 1&quot;);
    a.setClickCount(6 + i);
    articlesDao.insert(a);    
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;div&gt;The test demonstrated:&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;id will be updated once data is inserted and new id&amp;nbsp;retrieved&lt;/li&gt;
&lt;li&gt;values can be simply NULL without the use of Scala&#39;s convention of Option&lt;/li&gt;
&lt;li&gt;when update cannot find a record to update a RuntimeException is raised&lt;/li&gt;
&lt;li&gt;transaction is working good&lt;/li&gt;
&lt;/ol&gt;&lt;/div&gt;

&lt;link rel=&quot;stylesheet&quot;
      href=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/androidstudio.min.css&quot;&gt;
&lt;script src=&quot;//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;hljs.initHighlightingOnLoad();&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://lunajs.blogspot.com/feeds/8201341970033872473/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://lunajs.blogspot.com/2011/06/squeryl-with-java-experiment.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/8201341970033872473'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4223339596261940054/posts/default/8201341970033872473'/><link rel='alternate' type='text/html' href='http://lunajs.blogspot.com/2011/06/squeryl-with-java-experiment.html' title='Squeryl with Java Experiment'/><author><name>Steven</name><uri>http://www.blogger.com/profile/18326437909361845233</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVVRJKQGSA1YyAwUlFQmJ4VVDLpA2jhj30GVFXtltqgXpR92fgom1jpTA8fxwzxjL9L0IdSFSb0WN_5O82ir2TJ8j2aFqHtBKas_JjmwhOR4SV-h1c1datUKnWutQGv_LI_9tC54zyP8I/s72-c/2011-6-28+%25E4%25B8%258B%25E5%258D%2588+02-52-01.png" height="72" width="72"/><thr:total>0</thr:total></entry></feed>