Tuesday, January 25, 2011

jquery IE AJAX issues

The list of issues when working with jquery IE AJAX issues are so huge and painful that I plan to maintain a log here :

1. trim() javascript function is not implemented in IE.
 Solution: Use $.trim('str ') instead of javascript trim()

2. Use javascript stacktrace jquery plugin. This is a life savior for identifying IE issues..
http://eriwen.com/javascript/js-stack-trace/
Open source in git here



Friday, January 21, 2011

Spring mvc 3 junit test

Below is a code snippet to easily test a spring annotated web controller


public abstract class BaseWebControllerTest {
    @Autowired
    protected ApplicationContext context;
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected HandlerAdapter handlerAdapter;

    public void before() {
        handlerAdapter = context.getBean(HandlerAdapter.class);
    }
   
    void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        final HandlerMapping handlerMapping = context.getBean(HandlerMapping.class);
        final HandlerExecutionChain handler = handlerMapping.getHandler(request);
        assertNotNull("No handler found for request, check you request mapping", handler);

        final Object controller = handler.getHandler();

        final HandlerInterceptor[] interceptors = handlerMapping.getHandler(request).getInterceptors();
        for (HandlerInterceptor interceptor : interceptors) {
            final boolean carryOn = interceptor.preHandle(request, response, controller);
            if (!carryOn) {
                return;
            }
        }

        handlerAdapter.handle(request, response, controller);
    }

}


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/test-app-config.xml")

public class MyControllerTest extends BaseWebControllerTest{
    MyController controller;

    @Before
    public void before() {
        super.before();
        controller = context.getBean(MyController.class);
    }

    @Test
    public void testGetRestRequest() throws Exception {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
       
        request.setContentType("application/json");
        request.setMethod("GET");
        request.setRequestURI("/rule/"+id);

        handle(request, response);
       
        String result =response.getContentAsString();
        logger.info("RESULT : "+result);
        //assert json response is right.
    }
}

Reference:
http://efreedom.com/Question/1-2314377/Testing-Spring-MVC-Annotations

Thursday, January 13, 2011

Batch scripts

Context : If you are a java programmer? and you use tomcat  on windows? and you do not want repeated stress injury?
If yes then below are the scripts:

#1# Script to shutdown tomcat, deploy app, and startup ##
set tomcat_home=C:\..\apache-tomcat-6.0.20
set CATALINA_HOME = %tomcat_home%
cmd /c %tomcat_home%\bin\shutdown.bat

cmd /c mvn clean package -Dmaven.test.skip
rmdir /s /q %tomcat_home%\webapps\coacs

copy target\myhotapp.war %tomcat_home%\webapps
cmd /c %tomcat_home%\bin\startup.bat

#2# Run tomcat in debug mode  - store this under tomcat/bin as tomcat-debug.bat ##
set CATALINA_HOME=C:\Apps\apache-tomcat-6.0.20
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
%CATALINA_HOME%\bin\catalina.bat jpda start




Friday, January 7, 2011

Oracle fix for schema table prefix and running scripts from sql developer

In oracle it appears like a NON_OWNER user though granted access(select, insert, delete, update) to tables created by OWNER of the table cannot directly view them without the schema prefix.

This would mean all the queries in the java application will have to have this table owner user name prefix.

The possible options to drop this prefix :

1. ALTER SESSION SET CURRENT_SCHEMA= OWNER_SCHEMA ; (AFTER LOGON trigger as mentioned here )
But this works only for the current session unless we have a logon trigger. This seems like a preferred approach as per various forum threads.

2. Create views/synonyms from the NON_OWNER current user per table. So the tables can be accessed without prefix.

3. It could be something simpler as well (I am no DB expert) like setting the default current schema for the NON_OWNER user in some other way.


Running scripts from SQL developer:


To run this from sqldeveloper :
1. Set a default Path: Tools menu > Preferences > Database > Worksheet > Select default path to look for scripts
2. open run.sql from sqldeveloper File > Open
3. Run script.

Tuesday, January 4, 2011

iPhone apps - App-le a day

iPhone apps seems like the new trend and what else should a developer be doing in his spare time?



My motivation:

1. Millions of users. You can share apps with the world and make a small earning till iphone user base exists. Isn't that cool

2. Its market place is excellent

3. One of the best integration of technology man possesses - all in the palms of your hand.

4. Good way to know more about Apple & their products.





Few iPhone apps that I have been churning are now live on itunes:




1. AutoSignIn(free) - formerly called LogMeIn.




An auto login app to help you login to most of the popular sites -like gmail, admob, ebay, yahoo, gdocs, etc.. As iphone has no provision to store your password/email this should be handy. I use most of the time.
The idea is that you dont need an app for every popular website on the internet. Just an autologin app should do as most websites are mobile friendly these days.
Was formerly called
LogMeIn. Due to copyright issues had to rename to AutoSignIn with a better icon. Hope we enjoy.

2. gDox (free)



An auto login app for gDocs. Live now.




3. Radio players (free)



Has a very intuitive interface for couple of iphone radio apps i have been spamming itunes store with (until they said no more). Some are regional. Below is the list.
  • Radio kannada
  • Tamil Hits
  • Telugu hits
  • Radio Eye - English radio stations organized based on top stations and genre
  • Hindi hits




4. aMaze!! (free)



An attempt to use Chipmunk physics engine and sparrow framework to build a maze game with balls moved into target square through iphone movement. Its a free app with some nice music and interface (except that the physics engine is not that great).
Learnings:
Chipmunk C library is free but hard to code(its objective C library costs 200 bucks and i didn't wanted to shell out a $). Though this was a good experience with physics engine, i found it to be unstable and not so easy to work around memory and timer issues of chipmunk C library. Would not recommend anyone to use chipmunk c library (don't know if the paid objective C bundle is better). Better go for cocos 2d. Its more popular.



5. Java JEE IQ (Was $1. Now free)



Java/j2ee quick notes for revision etc esp. during interview. It consists of notes from an industry perspective- has spring/hibernate/struts/JSR's/core java/ etc and some useful pdfs. This was my first app and i spent a lot of time learning objective c/buying macbook & ipod touch/installing snow leopard/xml parsing library/xcode/interface builder/ and understanding how to make a release to itunes. I am charging a $ for all that effort of mine. Hope it is acceptable.




All the above apps can be found by searching 'bri8' on itunes store or following this link:
http://itunes.apple.com/us/artist/bri8-ltd/id396468155



OpenID

It is so convenient to pull out information from account which user already has instead of making the user key in the boring registration form. In a way it follows DRY(do no repeat yourself) principle.

Here comes OpenID. You can also auto register the user with this php script. Cool stuff for my community site..

Open ID +PHP : http://devzone.zend.com/article/3581

Friday, December 31, 2010

Tomcat remote debug

Windows:
under tomcatHome/bin create a file called startup-debug.bat or startup.bat and add below:

set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
catalina.bat jpda start

UNIX: 
export JPDA_ADDRESS=8000
export JPDA_TRANSPORT=dt_socket
catalina.sh jpda start

Run the bat/sh file you just modified. Connect at port 8000 for debug..


To configure remote debugging when windows as setup as a service you edit your tomcat configuration and add these startup parameters:

C:\tomcat\bin> tomcat5w //ES//Tomcat5

-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n




Friday, December 10, 2010

Online java IDE

Its a shame we don't have  a proper online java editor to build full scale web applications in java.

Most of them found only allow you to compile a small code snippet or dont allow you to execute java code for security reasons.

Cant imagine the amount of progress we can make if we have a full fledged online java editor. eg: Imagine we are able to do online development of existing java projects on sourceforge site. Imagine how much code you can produce if development is as simple as opening up a browser and keying in your ideas.. Imagine how many projects u can get involved in simultaneously.


JDK6 has the new in memory as well as runtime compiler API: search JavaCompiler. Not many have taken advantage of it i believe.

Some online ide like options:
compilr - can only compile, not run
ECCO: - looks like an interesting project on SF but abandoned 3 yrs back
ideOnea simple code  compile and run project



Wednesday, December 8, 2010

iBatis - simplify persistence

iBatis is in between hibernate and jdbc. A somewhat ORM. It is more about simplicity.

What is iBatis ?

  • A JDBC Framework
    • Developers write SQL, iBATIS executes it using JDBC.
    • No more try/catch/finally/try/catch.
  • An SQL Mapper
    • Automatically maps object properties to prepared statement parameters.
    • Automatically maps result sets to objects.
    • Support for getting rid of N+1 queries.
  • A Transaction Manager
    • iBATIS will provide transaction management for database operations if no other transaction manager is available.
    • iBATIS will use external transaction management (Spring, EJB CMT, etc.) if available.
  • Great integration with Spring, but can also be used without Spring (the Spring folks were early supporters of iBATIS).

What isn't iBATIS ?

  • An ORM
    • Does not generate SQL
    • Does not have a proprietary query language
    • Does not know about object identity
    • Does not transparently persist objects
    • Does not build an object cache

Useful links:
Spring 3 + ibatis + maven sample in git : link
ibatis tutorial: link

Wednesday, July 14, 2010

Jboss overview

At a high level :  EJB container + Servlet container  = Jboss application server

With more and more web applications turning to spring and hibernate tomcat is more than sufficient. But I am writing down the jboss details here as part of my porting project investigation work.

Default Port: 8180
http:[jboss]/jmx-console makes managing server easier using mbeans.

JBoss Directory Structure

bin/  :Scripts to control JBoss
client/
: Libraries for use by remote clients.
docs/
  : it's documentation!
lib/
:Core libraries.
server/
: Services hosted and served. Your apps go in here.


server/
               There are three sample configurations: default(security, transaction services and RMI), minimal(logging and hot-deployment) and all(Everything in default plus clustering, webservices) . Thee folders under this are useful:

  conf/     Meta-information for the configuration.
  data/     Data store for JBoss. This directory is created by JBoss when the configuration is started for the first time.
  deploy/  Location for the deployed components - dynamically scanned do detect any additions or changes made while JBoss is running (hot-deployment). Put apps here.
  lib/        Libraries (in addition to the core ones) required by this configuration.
  log/      Service specific logs. Like data/ this directory is created by JBoss on first instantiation.
  tmp/     Used as temporary store by JBoss. Similarly to log/ and data/ this directory is created by JBoss.
  work/    Used for JSP caching.


You can run your own instance of jboss under server/ and starting it from bin/run_[instance].bat ..what this batch file should do is set environment variables, and start jboss using org.jboss.Main -c [instance name]



Ref: http://www.novell.com/coolsolutions/feature/14912.html




Wednesday, July 7, 2010

Liferay CMS/ web content management/ workflow/ staging

Liferay out of the box has a web content management system. The web pages can mostly have these web content (articles) as web pages. The web content resource are organized as below: In liferay control panel you have the following for CMS: Article Holds the content. The article fields can be configured using a structure. Can belong to a type. Can apply a category. Can be tagged. Stored in DB column journalarticle.content as xml. Web content list and web content article portlets use these articles. Structure Defines all the fields the article will have like text input, text area, image input,etc . Also the velocity template can access these fields using the names configured here. Template An article can be displayed using a velocity template. Template can have a structure applied to it. So an article on using a structure can choose one of these templates. Tags and categories Provides a way to organize articles. Document library Documents can be uploaded. They are stored in the database. There is a document library portlet for managing this. Image gallery Holds images. These are available for article. More on the workflow staging later...
Please refer my other post here for more

Tuesday, May 18, 2010

cloud hosting monthly costs comparison

Most of the cloud providers charge hourly. Its easier to compare costs if we can get a monthly pricing. However the hardware they provide is difficult to compate.
The simple monthly pricing formula is [cost per hour] x running 24 hrs per day x 30 days = [cost per hour] x 720 hours a month
Here is an attempt for linux as of may 2010:

 

Amazon EC2:(Standard On-Demand Instances)
Small $0.085/hr => $61.2/month
Large $0.34/hr => $244.8/month

rackspacecloud
256MB/10GB 0.015/hr => $10.95/month
512 MB/20GB 0.30/hr => $21.90/month

opsourcecloud 

0.26/hr => $191/month
http://www.opsourcecloud.net/getstarted/pricing/

Amazon does provide the Pay only for what you use. But how does it identify our usage and what it exactly means is not clear ? Yet to figure it out. Somewhere I did read that till your app is shutdown it means the CPU is used..Would it make any sense for web app...I may be wrong..

Google App engine:
-cant write to disk.
-blacklisted set of java APIs, so few apps dont work
- cant use hibernate . So most open source apps built on hibernate wont work.
- 30 seconds HTTP response limit. So cant use streaming.
- Shutsdown app if not used for certain hours. So will give you screen deaths after first access.
- Use it only if you are ready to get tied to google ORM and big table. Also no joins..duplicate your data and...grrr..
-Then why use it ? Hmmn .. But it gives basic usage stuff for free. If you are ready to align your apps to what GAE provides and live with its limitations, then you are good to go.

Cloud is still evolving i think.
For my basic app needs, I would rather prefer to setup my own boxes and network infra to cut costs and have full control.

Reference:
http://www.raditha.com/blog/archives/cloud-hosting-making-sense-of-the-pricing.html

Tuesday, May 11, 2010

jQuery gotchas

1. Playing with checkboxes:
To get all the checked checkboxes from a group use :
$("input.selectArticleCheckBox:checked");

2. To hide multiple elements in a screen with the same name use class instead of id:
$('tr.filterSection').show();
This shows all elements with class filterSection in a tr

3. Iterating through an array:
       $.each(
                    articles,
                    function( intIndex, obj ){                 
                        alert(obj.value);
                    }
         );

4. Check if element is visible: $('.classMessage').is(":visible")

5. Email validation using regex:
var regexEmail= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z0-9]{2,4})$/;                          
if(!regexEmail.test(currentFieldValue)) { }

6. Manipulating select fields
$('#selectList').val();$('#selectList :selected').text();

7. Debugging jquery on stupid IE
//global catch all
function
handleError(e)
{
alert(’An error has occurred!\n’+e);
return true;
}
window.onerror = handleError;
Use stacktrace.js as a life saviour : stactrace.js
  Nice link here
  More

8. CORS - cross site ajax call using jquery.
Browsers restrict from making cross site calls. Alternative is to use JSONP (JSON with padding)
The web server hosting the JSON, should wrap the json with  the function name which needs to be implemented in the javascript/jquery code. Also the jquery should send
jsoncallback=? parameter. Also older jquery version doesnt support .ajax based jsonp.

var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, null)
.done(function( data ) {
alert("gotdata");
});
*update : the above didnt work, so tried with $.ajax() by passing jsonCallBack: "functionName"

9. show()/hide() in jquery is too slow as it does some data caching. also setting $().css("display","none") is slow.  Hence used CSS based hiding :
       $('tr.tableStyleRow').addClass("rowShowClass");
        $('tr.tableStyleRow').removeClass("rowHideClass");

.rowHideClass{
    visibility:hidden !important;;
    display:none !important;;
}
.rowShowClass{
    visibility:visible !important;;
    display:block !important;;
}



Ref:  Jquery cheat sheet :
Build your own jquery plugin tutorial
spring mvc with jquery ajax
restful spring mvc

Tuesday, May 4, 2010

Liferay 5+

  • Liferay experiences thread link
  • Public render parameter(JSR 286) in liferay to read a request parameter: link 
  • Website search (page search based on meta tags : link
  • Building a hello word portlet using plugins SDK:link
  • Liferay and opensso integration:(quite neat) : link
  • Organization vs community : link
  • Adding validation messages in liferay : link
  • Popup in liferay : link
  • Liferay hook plugins : link : Hooks are event handlers and they are Good stuff !.  Liferay provides the following events : Application Startup Events, Login Events, Service Events                                               Gotchas : Better to use hooks as plugins. Tried in ext once and it broke other hooks.
  • Customizing labels(internationalized): Done in Language-ext.properties
    : link
  • A good review of liferay 5.x is here
  • Liferay architecture is SOA based :

* Above image is taken from book Liferay Portal 5.2 Systems Development.pdf

Friday, April 30, 2010

Inter portlet co-ordination (JSR 286)

Prior to JSR 286, the support for inter portlet communication was rather minimal and information sharing between different portlets was accompalished primarily using application scoped session objects or vendor specific APIs. Both of above methods were rather problematic as in the former maintaining the uniqueness of the session attribute over a complex aaplication was a concern and in the later portability of the portlet was hampered. In order to provide coordination between portlets the Java Portlet Specification v2.0 (JSR 286) introduces the following mechanisms:
  1. public render parameters in order to share render state between portlets.
  2. portlet events that a portlet can receive and send.
Also JSR 286 specifies about Portlet Events..
An example where a portlet may want to offer receiving events is for state changes triggered by simple user interactions, e.g. adding an item to a shopping cart. By offering this as an event to other portlets these can trigger adding items to the shopping cart based on the user interactions happing inside these portlets.

More details here:
http://blog.xebia.com/2009/04/19/inter-portlet-coordination-with-jsr-286/

Thursday, March 25, 2010

JDK hidden treasures

Couple of tools we occasionally use but knowing them is useful esp. when we want to peek into JVM.

jps  -List the java process running.
eg: jps -m -l

jvisualvm - Visualize all the VMS running. Seems to be a better option than jconsole. Comes with jdk1.6+ i think
http://java.sun.com/javase/6/docs/technotes/guides/visualvm/intro.html

jconsole -
eg: TODO: remotely manage Mbeans??

jar
eg: jar xvf --to extract, jar cvf -- to create ?

jarsigner  --useful for signing applets.
jstack --??

java  - The jvm ...
javac  - The compiler

javaw  - As far as I know useful to run a process without sticking it to the console which is opening it. eg: javaw eclipse




Friday, March 19, 2010

Good tools for web developers

Must have tools for web developers Xrefresh which works with firebug. Basically you install 2 things , a firefox addon and a system specific xreferesh server. the addon behaves like a client and refreshes the page when you save a html/css/js in your editor Fireshot An excellent plugin to take screenshots and edit them all easily in the plugin.

Thursday, March 18, 2010

Fun with XML on Oracle - XMLTypes

To register a schema in oracle do below:
1. drop directory XMLDIR;
2. create directory XMLDIR as 'C:\';
3. select * from ALL_DIRECTORIES
4.
DBMS_XMLSCHEMA.registerSchema(
SCHEMAURL => 'C:\oracle9i\admin\TEST\utl_file\test.xsd',
SCHEMADOC => bfilename('XMLDIR','test.xsd'),
CSID => nls_charset_id('AL32UTF8'));
5. desc DBMS_XMLSCHEMA confirms that registerSchema exists

Gotchas:
error: ORA-01031: insufficient privileges


Wednesday, March 17, 2010

Clip chain - copy mulitple words at one go!

Clip Chain:
The separator can be changed as often as you'd like while building the text chain—Caps Lock+Esc resets the separator to the default (nothing).

Use the Caps Lock+C shortcut to copy the currently selected text and Caps Lock+V to paste Once the chain has been pasted using Caps Lock+V, the chain is moved to the clipboard and reset.

To paste the chain again, use the standard Ctrl+V shortcut. The chain can also be reset at any time by pressing Caps Lock+Backspace.

More : http://lifehacker.com/5337238/clipchain-copies-multiple-text-strings-for-easy-pasting