Developer Notes

Practical notes, advises on application development (java, seam, android, google api)

Useful Eclipse navigation shortcuts for java developer

Posted by Andrey Chorniy on June 14, 2011

I find that this article (10 Eclipse Navigation Shortcuts…) is great and will save you a lot of time in development/coding if you are programming in Eclipse. I personally prefer Intellij Idea for java development, but in case of Android “Eclipse + ADT plugin” doesn’t leave much chances to alternative IDE’s.
Great shortcuts, I use part of them before and really miss “CTRL-E” Go to other open editors

Go to other open editor

and “CTRL-O” Go directly to a member (method, variable)

Posted in Android, Tips and Tricks | Tagged: , , , | Leave a Comment »

Richfaces a4j:poll and a4j:push Can Do More Together

Posted by Andrey Chorniy on February 27, 2011

Task: Update the content of the page if the content is changed on server-side, in other words – show the most-fleshiest content to the user.

The most simple solution that comes to mind is to use <a4j:poll/> component which will periodically call some action which will load fresh content and re-render the content on the page. But that not very optimal since you will create the content on server-side and send it back to the client each time you execute the polling request.

a4j:push component looks like the one who was created to avoid that every-time re-rendering. Here is what demo-site says about it:

The main difference between a4j:push and a4j:poll components is that a4j:push makes request to minimal code only (not to JSF tree) in order to check the presence of messages in the queue. If the message exists the complete request will be performed. The component doesn’t poll registered beans but registers EventListener which receives messages about events.

Looks very promising, but in reality it’s a kind of tricky to integrate it with your real application because some code on the server side should execute something like that:

synchronized (listener) {
listener.onEvent(new EventObject(this));
}

But, to do so we should have something in background which will periodically check for updates and generate the events and send them to our listener. Starting a Thread is not good option since we have to worry about the way to stop it, as well who start Thread’s in web-apps ? @Asynchronous task is better one option, but still has the same issues – we have to worry about it lifecycle and stop updates at some point (user may leave the page or close his browser) so we actually has no good way to manage the lifecycle of launched background tasks.
At first I try to use a4j:push with action=”#{myActionBean.checkForUpdates}” but action is not called by a4j:push, it just checks if he has new events and only if it has such – execute action and do reRendering (all that JSF lifecycle) 

But it looks like combination of a4j:poll and a4j:push could work here in that way.

  • a4j:poll execute an action which check for updates in the data and fire an Event if they are exists
  • a4j:push periodically check for new events and re-render content on new event

So, a4:poll play role of assistant, actually it’s like the managed background task on the serverside which periodically poll for the data, but it’s live on the client-side, so in case user will close his browser – server will not execute the requests to datsource anymore.

I call it a “conditional re-rendering”. Here is the JSF code I use to make it working.

<a4j:form id="pollForm" eventsQueue="queue">
    <a4j:region id="pollRegion" selfRendered="true" renderRegionOnly="true">
        <a4j:poll action="#{myActionBean.checkForNewData}"
            id="datasetChangedChecker" interval="#{myActionBean.pollInterval}"
            ajaxSingle="true" limitToList="true" immediate="true" bypassUpdates="true">
        </a4j:poll>
    </a4j:region>
<!-- the function below execute an ajax-call to server which enable the push and re-render <a4j:push /> to start it -->
<a4j:jsFunction name="startPushUpdates"
                action="#{myActionBean.startPushUpdates}"
                reRender="dataSetReRendererPush" ajaxSingle="true"/>
</a4j:form>

<a4j:form id="pushForm" eventsQueue="queue">
    <a4j:push id="dataSetReRendererPush" ajaxSingle="true"
              eventProducer="#{myActionBean.addUpdatesListener}"
              interval="#{myActionBean.pollInterval}"
              reRender="contentPanel,datasetChangedChecker,dataSetReRendererPush"
              enabled="#{myActionBean.pushUpdatesStarted}"
     />
</a4j:form>

<a4j:outputPanel id="contentPanel">
   <!-- Updated content goes here -->
</a4j:outputPanel>

The only issue here is that we have to ensure that a4j:push is executed AFTER a4j:poll so action called in a4j:poll will generate the event before we will execute the a4j:push. Unfortunately we don’t have the way to manage it in JSF with attributes, but that could be done with help of postponed launching of a4j:push (with some reasonable gap which should be bigger than time required to execute check for data-updates)
The postponed a4j:push execution is achieved with enabling it with ‘enabled=”#{myActionBean.pushUpdatesStarted}”‘ attribute and calling the javascript with timeout

jQuery(document).ready(function() {
    window.setTimeout(startPushUpdates, 5000);
});

so, having all that JSF code and MyActionBean.java we have quite optimal solution
I didn’t include java-code here but I believe if you read this line than you most probably got the idea and capable to implement it on your own :-)

Future notes: it looks that IceFaces propose their own vision of ajax-push and it’s not based on periodical polling of server from server-side.
IceFaces push model
As well they have Direct-To-Dom rendering which looks like much more optimal way of re-Rendering. Haven’t tried it yet, but for me it looks ajax-push at IceFaces and re-rendering is a more optimal solution.
It would be nice to hear from the ones who try both RichFaces and IceFaces ajax push approaches.
BTW, just find that RichFaces team prepare some updates to a4j:push in RF-4.0

With this release we have added a few new components, redesigned a4j:push to use advanced Comet implementation and JMS servers

Posted in Software Development, Tips and Tricks | Tagged: , , , , , , | 2 Comments »

Export to Excel with jXLS can be faster

Posted by Andrey Chorniy on February 14, 2011

I got a question about the jXLS performance, in short it was like “jXLS is a kind of slow for my big reports”.
I mentioned that in my previous post (Creating Excel reports from java is easy)

It’s true, especially about latest jXLS, after I updated my jxls-0.9.8 to 1.0-RC1 (see downloads) I noticed that report generation become MUCH SLOWER. I believe the difference is in the expression library version JEXL. In the 1.0-RC1 they start using JEXL-2.0.1 version and before they use JEXL-1.1
Anyway, it looks downgrading it back to the jXLS 0.9.8 solves my problems, the performance is not blazing fast but much better than in jXLS 1.0. I bet jXLS 0.9.9 work faster than 1.0

Posted in Software Development, Tips and Tricks | Tagged: , , , , | 1 Comment »

Howto disable form submit on Enter and fix for RichFaces rich:inputNumberSpinner

Posted by Andrey Chorniy on November 6, 2010

It’s quite generic problem – to disable automatic form submit on ENTER, to avoid occasional submits which could lead either to page refresh or even to redirecting to another page.
The general idea is to define onkeypressed event handler for text input fields
Here is the article which describe the general approach to do it in HTML.

we can assign onkeypressed event handler to all fields just with few lines (with help of JQuery of course)

function noEnter() {
    return !(window.event && window.event.keyCode == ENTER_KEY_CODE);
}

jQuery(document).ready(function(){
      jQuery(:input:text).keypress(function(){
           return noEnter();
      });
});

That works fine for a lot of components, but not for rich:inputNumberSpinner.  ”onkeypressed” handler was assigned and was called, but … it still not work, after a plenty time in debug I finally ensured that it not working and start investigating the richfaces sources for that component and found that it has a javascript command that DIRECTLY perform the form submit. And there is no way to prevent this behavior using tags or javascript handlers.
BTW – I really like new google-chrome developer tools, pretty good and *faster* alternative to FireBug in FF)

After some googling I  found that there is an RF issue exists (not resolved yet) and there is no way to prevent form submission according to the richfaces-issue and actually in the related-post this issue is described in details, but it looks that solution could be only fixing the RichFaces library itself.
So, let’s do it!  We will need to build it form sources, since direct update of the script in the jar-file is not working – richfaces have minified scripts and they are pretty hard to read/modify :-)

You can download patched richfaces-ui.jar from here.

  1. Download RichFaces sources (I prefer to use stable builds)
  2. Extract them and navigate to the file in which form-submission is done “ui/inputnumber-spinner/src/main/resources/org/richfaces/renderkit/html/script/SpinnerScript.js”
  3. comment out that crazy row
            if (e.keyCode == 13){
                if (this.spinner.required || "" != this.edit.value)
                    this.edit.value = this.getValidValue(this.edit.value);
                if (this.edit.form) {
    //                this.edit.form.submit();
                }
            }
    }
    
  4. Lets build the Richfaces from sources. The first problem you can met is the memory. We will need a bunch of memory, so ensure that you have 64-bit java (since you will need a lot of memory – about 1500MB – I was not able to allocate this amount on 32-bit java in Windows-XP)
    so, instead of redefining env variables I just copied mvn.bat to mvn64.bat and added the following lines
    set JAVA_HOME=E:/Java/jdk/jdk.1.6_64
    set MAVEN_OPTS=-Xms512m -Xmx2048m -XX:PermSize=256m -XX:MaxPermSize=512m
    
  5. no lets rebuild richfaces-ui to do it, let’s grab few command-lines from developmentBuild.sh
    cd %PROJECT_DIR%/ui
    mvn64  clean install -Dmaven.test.skip=true
    cd %PROJECT_DIR%/ui/assembly
    mvn64  clean install -Dmaven.test.skip=true
    
  6. Let’s take a cup of tea since it will take a while…
  7. After build is done you will find the updated richfaces-ui.jar in the local maven repository.
    ${repository-home}/org/richfaces/ui/richfaces-ui/3.3.3.Final/richfaces-ui-3.3.3.Final.jar

Posted in Software Development, Tips and Tricks | Tagged: , , , , , , | 3 Comments »

HierarchyViewer missed in Android SDK r07 for Windows

Posted by Andrey Chorniy on October 29, 2010

I just updated to Android SDK-r07 and find out that I don’t have hierarchy-viewer tool anymore, what a nice surprise :-)
I know this program is stored in hierarchyviewer.jar so just created the hv.bat in tools directory with just

java -Xmx512m  -jar ./lib/hierarchyviewer.jar

.. and it works for me.

Another way – is to download Android-SDK-r06 and take hierarchyviewer.bat from it. Still don’t know how it happens that Android-SDK-r07 miss that great tool launcher

For those who don’t know nothing about that great tool, I recommend to take a look at article about layout-efficiency in android and about layout-optimization – and start using and in your layouts. And of course spend some time exploring your view-s in HierarchyViewer.

Posted in Android, Tips and Tricks | Tagged: , , , | 1 Comment »

Show dynamic progress of time-consuming process in Seam/RichFaces

Posted by Andrey Chorniy on October 22, 2010

Sometimes you need to start really time-consuming task on the server, but doing that with simple h:commandAction which will re-render page after it is done is not a good idea. Showing a4j:status (which could be blocking – see “avoid concurrent call to conversation“) – is a bit better and will work for relatively short tasks (like 5 – 15 seconds, matter of taste actually) but still not good solution for really long tasks (something more than 1 minute)

For really long tasks I recommend to show the progress indicator (it’s also known usability fact that user will think that task with dynamic progress-bar is faster than the same task but without progress-bar)

There is a quite good component to do it with Richfaces – it’s progressBar component, the only problem to do it with Seam is that you should initiate progress (by calling the action) and that action should immediately return and start some background process.  It’s always bad practice to use Thread’s in the web-containers, in Seam we have alternative Asynchronous tasks, but.. the problem with them is that they actually will be running in completely separate scope (they don’t know nothing about your conversation scope)

The trick here is to pass all the required parameters to asynchronous method and use them for returning the results too (in the conversation). That way we are not crazy about memory issues, since as long the long computation process will be ended the memory will be released (the reference to the object will be only in the initiator – the conversation scoped bean)

So, the solution may look like that.

  1. Define the PrgressBean.java which will hold all required initialization parameters for the process and methods to access the progress-state
  2. add “progressBean” attribute (+getter) in your action-class (ConversationBean.java)
  3. define methods to start process which will make a call to asynchronous method in other “LongProcess.java” and pass the progress bean to it
  4. add rich:progressBar and start/stop buttons in “commandPanel” (could be done inside progressBar only), + “updatedResults” – here you can show intermediate and final results during the process (optional)

In short – it is all you need to show very informative long-running process progress.

Future Notes:

Richfaces has few other ways to build your own progressBean – it is a4j:poll and a4j:push components. rich:progressBean actually utilize “pooling” approach, in most cases it’s quite enough to periodically update progress/results for the user, so actually there is no much sense to write your own  approach using a4j:poll.  a4j:push maybe quite good alternative to rich:progressBar since it use much less traffic and doesn’t update JSF tree (so it’s potentially a better alternative). I think you can easily adapt described approach to use a4j:push – you just need to add few pieces  (addListener method and send events to the listener during the process)

Code-Snippets

Java Code:

@Name("longProcess")
@AutoCreate
public class LongProcess {
    private ProgressBean progress
    @Asynchronous
    public void startProcess(ProgressBean progress) {
        this.progress = progress;
        this.progress.setInProgress(true);
        try {
            runProcess();
        } finally {
            this.progress.setInProgress(false);
        }
    }

   private void runProcess(){
     //perform your time-consuming operations here and periodically update the progress status
....
     progress.setPprogress(progressValue);
....
     if (progress.shouldStop()){
        //finish long process and return
     }
....
   }
}

@Name("conversationBean")
@Scope(ScopeType.CONVERSATION)
public class ConversationBean  {
    private ProgressBean progressBean = new ProgressBean();
    @In LongProcess longProcess;

    public void startProcess(){
        if (!progressBean.isInProgress()) {
           progressBean = createNewProgressBean(); //initialize it with required parameters here
           longProcess.startProcess(progressBean);
        }
    }
    public ProgressBean getProgressBean(){
        return progressBean;
    }
    public void stopProcess(){
       progressBean.stop(); //update the internal state of progress-bean so long-process will check it and stop
    }
}

Richfaces/JSF code

<h:panelGroup id="commandPanel">
<a4j:commandButton action="#{conversationBean.startProcess}"
        value="Start" onclick="this.disabled=true;"
        rendered="#{!conversationBean.progressBean.inProgress}"
        reRender="commandPanel,proggressPanel,updatedResults">
</a4j:commandButton>
<a4j:commandButton action="#{conversationBean.stopProcess}"
        value="Stop" onclick="this.disabled=true;"
        reRender="commandPanel,proggressPanel,updatedResults"
        rendered="#{suggestedEventController.progressBean.inProgress}">
</a4j:commandButton>
</h:panelGroup>

<a4j:outputPanel id="proggressPanel">
<rich:progressBar value="#{conversationBean.progressBean.progress}"
                  label="#{conversationBean.progressBean.progress} %"
                  enabled="#{conversationBean.progressBean.inProgress}"
                  minValue="-1" maxValue="100"
                  interval="#{conversationBean.updateRate}"
                  reRender="#{conversationBean.shouldUpdateTable ? 'updatedResults':'anyEmptyComponent'}"
                  reRenderAfterComplete="proggressPanel, updatedResults, commandPanel">
    <f:facet name="initial">
        <h:outputText value="&amp;lt; Click to start"/>
       <!-- we also may show here button to start process as in RichFaces example (I use separate commandPanel instead) -->
    </f:facet>
    <f:facet name="complete">
        <h:outputText value="Process Completed"/>
      <!-- we also may show here button to restart process as in RichFaces example -->
    </f:facet>
</rich:progressBar>

<h:panelGroup id="updatedResults">
      <!-- it could be used to show results (for example list of processed or generated rows) -->
     <rich:dataTable value="#{conversationBean.progressBean.items}>
     </rich:dataTable>
</h:panelGroup>
</a4j:outputPanel>

Please take a notice at 2 parameters used in rich:progressBar
interval="#{conversationBean.updateRate}"
it use a method conversationBean.updateRate to determine the update rate. I’s optional and could be just hardcoded to some value like “1000″ (1 second). Can be used to dynamically set it to appropriate value, so your progress bar will not be updated to often and can be even changed during a process to fit to your real update rate

reRender="#{conversationBean.shouldUpdateTable ? 'updatedResults':'anyEmptyComponent'}"
As you see reRender here use dynamic condition, so conversationBean has a control other it and can skip heavy “updatedResults” update to save a traffic

Posted in Software Development, Tips and Tricks | Tagged: , , , , , , , , , , , | 6 Comments »

Free Hosted Redmine

Posted by Andrey Chorniy on July 23, 2010

I like Redmine, it’s simple but yet powerful, one tool with almost all you need for managing project  (Issue tracker, time-sheets, wiki, file-share tool, cool filtering and reporting tools)

Just Like It.

Here is the link to the free redmine hosting (you can still have your project private) the only limitation I found – you can’t create users on your own (i.e you don’t have Admin rights which of course correct for free public service). Of course you can’t install plugins, but even without that Redmine offer you a lot

Thank you guys for your service https://www.hostedredmine.com/

And thanks to Redmine creators, I wish I will contribute to Redmine too.

Posted in Software Development | Tagged: , , , | 2 Comments »

How to view android sources in Eclipse

Posted by Andrey Chorniy on May 26, 2010

I don’t know any more straightforward way to work with (view/browse) android sources in eclipse on the moment. I have downloaded sources from GIT before, but that actually doesn’t allow me to browse them in Eclipse. I still have to find the source on the disk to browse it, since they are scattered in different folders.

I find this article very helpful http://android.opensourceror.org/2010/01/18/android-source/ (all information below is actually taken from this article)

So, in short – download zipped sources from

Unzip it them in the corresponding \source folder for particular platform/SDK  ${android-sdk-home}/platforms/android-4/sources

And refresh you project in Eclipse, that’s all – it works for me in “Eclipse Galileo” and “Eclipse Helios” so I believe it should work for you too.

There is some possible problem with viewing sources in debug which is covered in the source article – “Just click on that “Edit Source Lookup Path” button to add a source lookup path.

Click edit source lookup path button

In that dialog leave “Default” selected and click “Add.”

Leave default selected=

In the following “Add Source” dialog choose “File System Directory” and hit the OK button: Then choose the source directory where you unzipped the code. The debugger should now show all the code you can debug into.

Define path to unpacked sources

Posted in Android, Software Development | Tagged: , , , , | 1 Comment »

3 Magic words from Google “Upload, Train, Predict” = Prediction API

Posted by Andrey Chorniy on May 21, 2010

Yesterday, May 20, 2010 on Google I/O the brand new API was announced by Google “Prediction API
It looks very promising and open the wide range of areas to use it of course.
In short it will expose to everyone (on the moment only to “selected everyone” on the moment since it has limited access on the moment) the ability to build their own “Supervised Classification” without coding, without writing algorithms to analyze and learn from their data.

To use that API you have to sign-up and wait until Google decide to give you an access, so don’t wait and sign-up to the Prediction API access if you are interested
So, generally you have to do 3 relatively simple things (except thinking about the classification task description)
Upload your data to Google Storage

Train classify your data set

Predict use the model which google create from your data-set to predict (classify)

Usage of Google Prediction

Looking at the answers from Google representatives I can say that is absolutely fresh pilot product but for it is very promising, especially if they will have API to describe the data-set, configure prediction models and algorithms, etc. It will allow embed complex prediction based logic even in mobile phones without having actual computation and programming on client side.  One more example of how to transform  complex and scaring into simple.

Posted in Software Development | Tagged: , , , , | Leave a Comment »

Lucene spellchecker for TinyMCE

Posted by Andrey Chorniy on May 11, 2010

I just finished creation of Lucene based spellchecker for TinyMCE editor. It is based on the same code as the two previous ones “Jazzy-based” and “JMySpell-based

You can download code from the jspellchecker (http://jspellchecker.svn.sourceforge.net/viewvc/jspellchecker/trunk/)

All configuration for TinyMCE still the same, just use updated path to spellchecker-servlet

spellchecker_rpc_url&nbsp;   : "/spellchecker/lucene-spellchecker",

Current implementation is based on the org.apache.lucene.search.spell.PlainTextDictionary (it is just the list of words delimited with newlines) and have additional memory-configuration servlet parameter “max_memory_usage” (value in megabytes which define the maximum size of Lucene indexes which could be stored in memory)

Indexes for spellchecker created at the first access to the particular language after web-application startup (or pre-created for “preloadedLanguages” on servlet-startup).
To speed-up index access (and the spell checking as the result) spellchecker indexes initially created on the file-system and after that they are moved to memory
It use 2-level cache to achieve the maximum performance and memory-management.

  • 1-st level of the cache is the cache of SpellCheckers which use In-Memory (RAMDirectory) Lucene indexes
  • 2-nd level cache store File-System SpellCheckers (FSDirectory) which don’t take memory but just hold the reference to the Directory object

1-st level cache implementation (based on LinkedHashMap) is also responsible for memory-management, it guarantees that summary size of all In-Memory indexes is less than “maxMemoryUsage” (this parameter is configured in servlet init parameters in megabytes)

On the moment I’ve found one-issue of Lucene spellchecker, it’s related to multi-word processing.  For example I have “New-York” in my dictionary, but it doesn’t processed as one-word (Lucene index-reader split it into two words of course).

The extension points of that spellchecker could be

  1. Usage of IndexReader to read existent Lucene indexes
    Dictionary dictionary = new LuceneDictionary(reader, indexedField);
  2. Use extended form of suggestSimilar which boost “most-popular” terms (it need the initial index-reader, so applicable only for LuceneDictionary based on IndexReader)
    suggestions = spellChecker.suggestSimilar(word, maxSuggestionsCount, fieldIR, suggestedField, true);
    See the code examples for that in the  “Did-you-mean feature with Hibernate Search, Lucene and Seam. Example application”.

Posted in Software Development | Tagged: , , , , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.