Thursday, January 20, 2011

javascript debugging in internet explorer(IE8 +)

Press Shift-F12 after your web page is loaded. This will bring up Developer tools window. Select the "script" tab. If you have more than one js files, they will be listed in a drop down painted just adjacent to start/stop debugger button. Scroll down to the line where you wish to add the breakpoint in the code. Clicking the white column by the col number will add the break point. At this point, hit start debugger button. Your parent window might refresh.

Happy js debugging!

Labels: ,

Tuesday, July 14, 2009

Why will Google Chrome OS not take over Microsoft Windows?

The single most important thing an OS does is hardware abstraction. While Linux xyz and macs have mastered in many areas like security, look and feel, speed, etc, Windows still remain unchallenged when it comes to device support. And how do they do that? By not having or supporting a common standard for device drivers! Go to a computer shop and purchase your favorite gadget; be it the coolest graphics card, 64 bit sound blaster, a simple USB skype phone or any other internal/external h.w. that you can think, to the bare minimum it will run out of the box(with some installations) on your windows PC! And that's the power of Windows. Like many others, I myself periodically tried different flavors of Linux over the past decade, but every time I did that I had to compromise on some h.w. support or the other. Recently I installed the newest coolest version of SUSE on my old box connected to 16:9 format TV via DVI and supporting graphics card, only to learn that there are no available drivers for my graphics card in the linux world. After lot of hacking and several attempts, I finally gave up and switched back to Windows :(. While SUSE worked out of the box and did most of the stuff better than Windows, it didn't support the 16:9 format on my graphics card(due to lack of supporting driver).

One single thing that Google should do to successfully capture the OS market is provide out of the box support to Microsoft's Device Drivers or provide some magical way to port the device driver s.w. into its new operating system. Current day Linux flavors are at least 100 times better in almost every area of OS features(including look and feel I must say) compared to Windows. There is no doubt that Google will make a great and innovative product, but what is more important is h.w. support, adaption and market penetration. Google can persuade manufacturers of nwe h.w. to support its OS, but what about the trillions of already manufactured equipments that are powered on all over the planet? Google should learn a lesson from Linux's struggle to capture Windows user base over the past decade. Remember, most ppl no longer use Windows because they like it, but because it just works out of the box!

For non configurable machines like Mobile phones, netbooks or even laptops, google OS or even Android with some improvement would be a great fit and work for most use cases out of the box. But for desktops, I still feel, google should nail the device driver requirements first.

@Official Google Blog: Introducing the Google Chrome OS

Wednesday, July 08, 2009

wild card search in eclipse

While eclipse's simple search is good enough for most purpose; You can make use of wild cards to enhance your search results. For example adding dots in your search text will ignore that many characters and match rest of the string.


Example:
text: The quick brown FOX jumps over the lazy DOG
search for: f.x
will match: FOX

text: The quick brown FOX jumps over the lazy DOG
search for: b..wn
will match: brown


text: The quick brown FOX jumps over the lazy DOG
search for: q...k
will match: quick


Now say you dont know the number of characters either. In this case you can make use of start to match any number of characters.

Example:

text: The quick brown FOX jumps over the lazy DOG
search for: the.*fox
will match: The quick brown FOX


text: The quick brown FOX jumps over the lazy DOG
search for: the.*brown.*over
will match: The quick brown FOX jumps over

Labels:

Wednesday, June 03, 2009

Session expiration issue in Web 2.0 applications

Traditional web applications consists of thin html based client that makes request to a thick server for most of its user activities. Thick server or application servers will typically associate a "session object" for each of its client. These session-objects will have a "time out" window that keeps track of user inactivity. If the user is inactive for certain time interval, (s)he should be logged off from the system and server resources should be reclaimed. Servers typically have background threads that keep track of inactive sessions and flush them off as and when timeouts happen. This works great on the server side. However, session termination message is passed on to the client browser only when a new request is made after the time-out interval is elapsed.

This approach might not always work in case of web2.0 or ajax or thick client based applications where lot of data/processing exists on the client. Client might continue to work on locally loaded data without making a server call even after the time out interval. Example: user modifies form fields or type in lot of text in an textarea while session time out has already happened on the server. User might end up loosing all the information when he actually hits the save button. Even worse is the security scenario: A user might have left his computer unattended, machine unlocked and browser window open with the web application running in it. Server might have logged off the user and cleared his session information, but some(pre loaded) data is still visible/available in his browser window. Ideally all this data should had been cleared the moment session time out happened.

The big issue here is http protocol's stateless nature. Sessions are tracked between a browser and the server with an internal token exchange mechanism. This token or session id is not part of the http protocol. Http by its very nature will only transport packages(request/response) from source to destination. With that said, servers cannot communicate with browsers at will. If that was possible, we could have send a session time out message to the browser as and when it occurred. Unfortunately there is no standard protocol between browser/server to achieve this.

Sending messages from the server to client is called "server push". In web2.0 world it is also called "reverse ajax". There are different ways to achieve this:

Client polling: Client(browser application) pings the server every pre determined interval to see if server has any data/message that needs to be pushed. Orbitz, Priceline, etc use this mechanism for there long running search queries . Unfortunately this will not work in our scenario where we need to communicate session time out information. Every time the client hits server, session gets renewed!

Piggyback: In this technique, server piggy back or append its message/data(if available) with every request that is received from the client. This method is better than client polling in terms of performance or bandwidth utilization. However it has same problem for our session timeout issue. Moreover piggyback mechanism cannot be used for instant/immediate server push. Server has to wait for that next client request in order to pass an message or event information.

Comet or Comet like: Comet is actually an umbrella term for techniques that work on long running transactions between the client browser and server. Idea is simple: Browser sends a request; server never returns a response; instead it keeps the connection open by sending KEEP-ALIVE messages; whenever the server wish to communicate data/message, it utilizes this open channel. This method works for our scenario, this is how we handle the session time outs:
  • When the user logs in for the very first time, browser sends a request to the server which is never responded. Only KEEP-ALIVE flags are send back to browser. To do this, you will require 1 Server thread per user session that will sleep until time out happens. To receive session time out event, this thread will have to register a session time out listener/handler with the server.
  • You might want to inform the user about inactivity and give him a change to save his session. To do this, you need to create a custom session time out job that will trigger a time out event just before the actual time out. Actual time out parameter value can be read from the session itself. When the custom time out job event happens, you should compare inactivity time with job's activity period. If the comparison result is false, some activity happened since the job was last scheduled. Job should be rescheduled with new timeout interval. If the comparison result is true, no activity has happened for the job time frame. You should now alert the user with a message(You will be logged off in x seconds, click Continue to save your session) and Continue button. If user hits the continue button, a server call should be made and job should be rescheduled with new session time out interval. If the user fails to hit continue in x seconds, you should log him/her off automatically and also display a user friendly message, informing him/her of the timeout event. You will have to create a client side timer for the exact(excluding the n.w. latency time) delta time for which his session will be active at time of displaying the very first message.
  • This approach works like charm if implemented properly. However there are some issues. Browsers typically spawn maximum 2 concurrent request threads per server session. By blocking one request on the server, browser has only one more request thread in its hand for communication. This means, two images cannot be downloaded at the same time; t files cannot be uploaded at the same time; etc. Browser will synchronize all the events.
  • Another issue: On the server you will require extra resources to handle this form of communication. You will require at least 1 thread and scheduled job per active user session.
Server push technology comes with lot of promises. You can push data to the client, as and when it is produced on the server. However this entire approach require proper design and good implementation. There are several open and commercial libraries available that could assist you achieve server push. As discussed above, this technique also has its pitfalls which should be considered before diving into it.

It needs mention that webservices which operate over the same http channel already have this concept in form of "WS Callbacks". I am positive that server push or reverse ajax or server callbacks will be standardized and incorporated by the browser/server providers in near future. Till then, we will keep discovering new solutions!

Labels: , ,

Wednesday, May 27, 2009

Calculating the number of characters that can fit a div or td element

Here is the problem...
I have an div or td element that has fixed width. I need to find the number of characters that could possibly fit its width/length. Character width is different for different characters. As an example "l" might require 2px, but "W" might require 6! With that said, simple division calculation might now always work. One solution is to clip the div area using css. This will truncate the text that is outside of specified width. Example:


<span style="white-space: nowrap;text-indent:10px;overflow:hidden;width:32px;">od oifh sdof od fdo fso dfosdffusdoifouiofusdoisoif</span>


Above code will truncate any text that is over 32 px. However it will not work for td elements.


Only possible way to truncate text over a specified px width in td element is to actually calculate the number of visible characters. Following code will help you find the exact pixel length of any text inside a div:


<div id="sourceDiv" style="position:absolute; z-index:-1">lll</div><br>
<input type="button" value="Check Size" onclick="var box = document.getElementById('sourceDiv'); alert(box.clientWidth + ' x ' + box.clientHeight);" />



Next step is to calculate px width of every possible character you expect to be displayed in your div/td/span. You can either calculate this at the very beginning and cache the results for future use, or you can compute it on demand. To compute individual character width, make an js array of all possible characters. loop through this, and in each iteration replace the sourceDiv's innerhtml to the character in array. Read the width and store it in another array. Now you have an array or map of all possible characters. You should be able to write a simple function that will calculate the number of characters that would be required to fill up a fixed width div/td/span from a input string/text!

Labels: ,

Thursday, May 14, 2009

Paper: Software Engineering Process using Agile Methodology

Abstract:

Agile software development practices offer compelling advantages like
streamlined processes, less “paper work”, high quality, creativity in work,
shorter delivery cycles, and above all customer satisfaction. Proper adoption and
implementation of agile processes is a challenge in itself. Automated tools and
practices like Continuous Integration, Test Driven Development, etc can largely
simplify agile adoption.

Software Engineering Process Using Agile

Download this paper free: @original link

Labels: , , ,

Monday, April 06, 2009

Loading a non java file from jar

Scenario: You have a configuration or text or any other non java file of that kind. You have to package your application(apis) as jar(executable or non executable) for the client to use. However if the non java files used by your application are static(cannot change at runtime or by the user), you might want to package them as part of your archive. Here is the code to do exactly that:

public static InputStream loadFileFromJar(String fName){
return Constants.class.getClassLoader().getResourceAsStream(fName);
}

We all know that getResourceAsStream() method of ClassLoader will load any file from available classpath. However in case of jar(some times) the classloader could be different. So we play a small trick: We first load a class(could be even a dummy blank class) from the jar and acquire the handle to that classloader. Now we can be assured that this classloader will have access to all the resources inside the jar.

One more thing: You should keep your file either in base of the jar or in a relative folder.

Labels: , , ,

Friday, March 20, 2009

Java code to delete entire folder structure with files in it

Ever tried file.delete() and wondered why your non empty directory is not deleted? Irony with java's api is that it returns a boolean when we expect it to either delete or fail! Here is a simple recursive function that will do the trick of deleting any file or folder with or without nested structure.

If you use this method in your application, do so at your own risk. I have not tested it for boundary conditions...
public static void deleteResource(File file){
if (file != null)
if (file.isFile())
file.delete();
else if (file.isDirectory()){
File[] resources = file.listFiles();
if (resources.length == 0)
file.delete();
else {
for (File resource: resources)
deleteResource(resource);
deleteResource(file);
}
}
}

Labels: , , , , ,

Running multiple tomcat as service on same machine?

Often while hosting tomcat server test instances, due to lack of hardware you are required to host multiple instances of your tomcat server software on same physical box. Moreover tomcat is so lightweight, it makes all the sense in the world to host multiple tomcats on the same machine. Unfortunately Tomcat installation wizard does not provide you the option to configure your "listening port" number. (Default is 8080). This is how I configured my tomcat instances:

  • Download the zip of your favourite tomcat version from tomcat.apache.org. Do not download the exe, use a zip. This is the key!
  • Unzip the software and copy it into multiple folders indicating multiple server instance. Use some naming convention for ease of identification. I append the http port number to directory name.
  • You will have to change at least 3 port numbers: 8080, 8005, 8009. (for tomcat 5.5 and 6)
  • While deciding on new port numbers, follow a naming convention. For example, if I had four instances running on the same machine, my port numbers would be: 5580/5505/5509, 6680/6605/6609 and 7780/7705/7709.
  • Now do search in multiple files and "replace all " to replace all port number references. Editplus does a good job!
  • Registering your servers as service: Navigate to the bin folder of your tomcat installation. Run the command service.bat install . It is again a good idea to append your port number in the service name. Perform this exercise with all your instances.
  • Open your services console. You can start/stop tomcat here.

Labels: , , , , , , ,

Saturday, October 25, 2008

Idea: Self playing media

Here is an idea which might not be new but at least not very popular.

The Idea:
"A framework that would allow media to play itself."

Background
Media, namely music and video exist in various formats. Each format has its own advantage and drawback. While some are more popular, others little less, some are free, other propriety. These digital media files are played by a piece of software/hardware called "Media Players". Every new media player, and its newer version try to play the most recent format and provide host of other features. It is very easy to upgrade a software based media player to play that new format which promises lower compression, high quality and other goodies. But things get bad when it comes to hardware. You are always stuck with a dumb box of electronics with no build in intelligence and upgrade capability. This box can understand only those media formats that were hardwired in it at time of manufacture. And the worse thing is you payed for this dumbness which will finally end up as a landfill!!!

My Idea:
- Create a generic framework that would allow Self Playing Media(SPM for simplicity) files to play themselves.
- SPM files are executables that contain inside them the actual media as well as the software(set of insructions) to decode and play the media.
- Considering the fact that media files(at least video) easily scale from Mbs to Gbs, it should be fairly trivial to package a few KB of software that comply with a standard interface and has the capability to play just the media it is packaged with.
- The framework I am talking about is really a thin abstraction layer between the underlying hardware and the SPM this hardware will play. In hardware based players, this framework or SPM player will exist as the hardware firmware.
- It will provide SPM a interface to the hardware features and a area where SPM can execute its media.
- This Framework by itself will not have the capability to play any particular format.
- Framework will provide a screen buffer. When SPM writes itself to this screen buffer, the framework will make sure that it is rendered on the screen(TV/display).
- Framework will also provide call back methods. For example play/pause/ffd/rwd on a player will be intercepted by the framework and passed on as method call backs to the SPM, which will convert them into appropriate actions.
- Media publishers can now include proprietary encoding, compressions and features without worrying much about the end user hardware/software capabilities. All they need to mention is "Plays in SPM compatible player"
- As a user of software based media player, what it really means is that you will never have to download a codec or any extra files to support the new media that you just downloaded.
- Commercial media can have advanced features like authentication, licensing and security built in!

Analogy to this concept:
- Flash movie exported as exe can play in windows based computer without requiring a browser or flash player.
- A ziped file exported as exe can unzip itself on any windows based computer without requiring the winzip application installed.
- A java application can play on any computer/device that supports jvm(java virtual machine a framework to run java applications)
- Java Media Framework is an well designed framework for media in java(FYI: external link). But JMF was build with applets and desktop based java in mind. Moreover SPM like concept is still alien.

With embedded java/linux and relevant industry standards, SPM and SPM based framework is very possible with today's technology. It was actually possible yesterday had the big players taken the initiative.

Imagine, if such concept had been envisioned when the first Audio/Video CD/DVD player was build, we would have (at least in theory) used a 10 year old VCD/DVD player to play the modern divx and mpeg encoded formats!

Labels:

Friday, June 06, 2008

Accessing JBoss server over the network

It is so easy to get started with jboss, but so difficult to customize it to do simple day to day stuff. For instance, you can start jboss by simply running the run.bat and access your fav Hello World or any other sample app at http://:/. Then you add a cool new feature and try to share this link with your colleague/friend/boss. Since you are smart, you change localhost with your local ip. Now you email the link and wait for appreciation. But what you end up getting is a reply that says: "this link doesn't work!" . Welcome to the world of jboss where you literally pay a price for using open source s.w. in form of time spend to find the right configuration.

By default jboss will accept all incoming requests if the domain name is localhost or ip 127.0.0.1. Anything other than this will throw a 404. There are two ways to get around this:
1. -b flag
When you run jboss, run it with the -b flag. Your command like might look something like this:
>run.bat -b 0.0.0.0
This will instruct jboss to accept incoming requests from any of its domain controller or ip addresses. You can also do ipconfig on your server box and specify the server's Ip address in place of 0.0.0.0.

2. jboss.bind.address
Above method will not work if you are running jboss as windows service. In that case you will have to explicitly configure this option in a property file.
locate the file: ...\default\conf\jndi.properties
Add the following line to it: jboss.bind.address=

Finally, you can check the jmx console to see if the changes are accepted!

Friday, January 05, 2007

like jira but free!

Are you working with open source tools?
Is your configuration management tool svn/subversion?
If you answer yes, then you might consider using jira and twiki in your project.
Jira, a very nice tool to use comes with a price tag.
So for users like me, who love the word "free" aka "open source" (better then free), here is a tool that offer many jira like features while integrating a wiki in it.

Here is a quick look at features:
- wiki like collaboration
- subversion integration
- Ticket/bug tracking

@link to website
@ rubyonrails uses it

Saturday, November 25, 2006

Tools to clean/analyse your junk code

While we all write the "best code in the world", only few of us actually take the pain review/analyse it for improvements(for the obvious reason that best cannot be improved!).


Fortunately java world provide a bunch of tools to analyze your source code and provide recommendations to clean them. Eclipse and java development has evolved to a point where most of the development related activities can be acheived from a single IDE with plugins.

Source code analyzers typically work using a set of rules. These rules can be modified, changed, etc based upon requirements. Every tool comes bundled with its own set of rules. Rules belong to categories. You can execute rules/categories selectively or all of them on your source code. Recommendations are then presented in tabular form. You then have a choice of fixing it on your own or allowing the tool to fix it. Caution: Some rules might alter the logic of your source code, so make sure you are aware of the changes before you execute them. Popularity of a tool depends on the effectiveness of the rules and the number of rules in it.

Here are some interesting tools:

Eclipse Refactor:
Right click your source in eclipse and check the options under "source" and "refactor". You can do lot of things like "correct indentation", "format" and other cleanups. This is a good way to make your code look clean and green.

PMD:(free)

PMD scans Java source code and looks for potential problems like:

  • Possible bugs - empty try/catch/finally/switch statements
  • Dead code - unused local variables, parameters and private methods
  • Suboptimal code - wasteful String/StringBuffer usage
  • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops
  • Duplicate code - copied/pasted code means copied/pasted bugs
You can either use the default(around 200) rules or write your own rules using xpath/java.
AppPerfect (commercial)
  • Applies over 600 high-value coding rules, including optimization, portability, i18n and coding standards, while analyzing your source code
  • Automatically fixes many of the violations
  • Support for JDK 1.5-specific syntax and keywords
  • Comprehensive reports including custom report designer and export of reports in PDF, Excel and HTML formats
  • Command line invocation to integrate with build scripts (including ANT-based built scripts)

Eclipse Metrics(free)
Checks for:

Other links:
@Eclipse source code analyzer
@Cyclomatic complexity
@Maven plugin for reporting
[Checkstyle, FindBugs, PMD, Lint4j, JavaNCSS, JCoverage, Cobertura, Emma, Clover, Tasks List]

Tuesday, November 21, 2006

"do you know"

All static methods are automatically final!

Instances of the class Class represent classes and interfaces in a running Java application.


Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Changing log4j properties at run time

I had a requirement where the log4j property file generated should have a unique id appended to it. This id is generated inside the running application. One simple way of doing it is: Make use of system variables inside the log4j properties file:
log4j.appender.R.File=
d:/mylogs/servicelogger[%d{MYAPPENDER}].log
After you have done this, make sure you set MYAPPENDER in the system environment.

Another way of doing this is: read the log4j properties inside the application, locate the specific property(in our case: log4j.appender.R.File). Change this property and instantiate log4j using this new set of properties. Here is the code to do this:
prop.load(new FileInputStream(logPropertyFile));
String userLogFName = (String)prop.getProperty("log4j.appender.R.File");
prop.remove("log4j.appender.R.File");
prop.setProperty("log4j.appender.R.File", newFName);
org.apache.log4j.PropertyConfigurator.configure(prop);
this.serviceLogger = new
Log4JLogger(org.apache.log4j.Logger.getLogger(DTM_LOG4J_CATEGORY_NAME));

Monday, November 13, 2006

soapUI: Tool to ease your Webservices development

I have often used altova tools to ease my XML and webservices(SOAP) development. Also, bea users have witnessed how easy it is to use an IDE to simplify rudimentary webservices/soap/WSDL related tasks. Well, soapui makes life much simpler for SOA developers. Here is quick look at soapUI features:

soapUI has a broad set of features that greatly ease the development, integration and testing of webservices;

Web Service Inspection and Invocation

The following features for inspecting and invoking web services are currently available:
  • Imported WSDL:s are shown as a hierarchy view of interfaces (PortTypes) and their operations
  • Automatic generation of requests from associated schema (both with/without optional schema elements)
  • Manage unlimited number of requests for each operation
  • Manage multiple service endpoints for each interface
  • Support for Basic, Digest, WS-Security and NTLM authentication
  • Support for Attachments; MTOM, SOAP with Attachments, Inline files
  • Support for both SOAP 1.1 and SOAP 1.2
  • Syntax highlighting editor with undo/redo, formatting, etc.
  • HTTP wire log shows actual requests sent and received

Web Service Development and Validation

The following features are available for development of Web Services:

Web Service Functional Testing

The following features for functional testing web services are currently available:

Web Service Load Testing

The following features for load testing web services are currently available:


@link

Thursday, October 12, 2006

java: Always override hashCode() when you override equals

Why override equals() and hashCode()?

What would happen if Integer did not override equals() and hashCode()? Nothing, if we never used an Integer as a key in a HashMap or other hash-based collection. However, if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same Integer instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

The interface contract for Object requires that if two objects are equal according to equals(), then they must have the same hashCode() value. Why does our root object class need hashCode(), when its discriminating ability is entirely subsumed by that of equals()? The hashCode() method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such as Hashtable, HashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive. Having every Java object support hashCode() allows for efficient storage and retrieval using hash-based collections.

@article

Tuesday, September 05, 2006

Troubled with malware and spywares?

Here are two more weapons for your Computer security arsenal:
Prevx
CCleaner

I have found both these tools extremely helpful especially if your computer is affected by popups, malwares, spyware, etc. Prevx is by far the best anti-malware, anti-spyware tool I have ever used. Its much better the spybot and likes. What makes prevx a better tool is the fact that it is not very popular yet. Remember, hackers will try to hack into the most popular and widely used software. The only drawback of prevx is that it is not free. You can try the full version free for 30 days. After 30 days only the detection part of the s.w. will be enabled.

CCleanse is another handy tool and yes it is free! This is from their website:

CCleaner is a freeware system optimization and privacy tool. It removes unused files from your system - allowing Windows to run faster and freeing up valuable hard disk space. It also cleans traces of your online activities such as your Internet history. But the best part is that it's fast (normally taking less that a second to run) and contains NO Spyware or Adware! :)
So if you suspect malicious contents on your computer, immediately install and run these tools! And if you have not already retired your IE browser, do so! Majority of attacks happen thro your internet browser. So it is extremely important to use a safe browser. I will strongly recommend Mozilla Firefox over IE. (Do not install extensions if you care for the startup speed) You can stop most if not all adware/spyware attacks if you switch to Firefox. Firefox is the way to go!

@prevx
@Ccleaner
@Firefox

More:
@spybot search and destroy

Labels: , , ,

Redirecting eclipse console output to log file

There is a way to redirect the console text into a log/text file under eclipse. If you are running a web-based application, possibility is that you already have a .log file configured some where. You can simply open this log file and look for messages.

In case of pure java application however, most of the output is showin in the eclipse console unless you configure a redirect.

Pull up the "Debug" or "Run" dialogs where you configured your main class. Select the java application you want to run. If you dont have an entry under "java applications", you might have to create one. On the right hand side of the screen, select the "Common" tab. Check the "File" checkbox and mention a physical path+filename in the input textbox. You are all set! Open the specified file in your fav text editor.

Tuesday, August 22, 2006

The non OO part of J2EE

GUI development has always been a pain. Looking back, the most commercially successfull, and easy to use tool for GUI based application development was Visual Basic. It had an easy form creator where you can drag drop your widgets and create your own application UI in minutes. Once you are done with it, you can simply tie some application logic to each form button.. u have your application ready!

Then came the web based era of application development where UI was interpreted as HTML and rendered by a web browser. Application logic would run decoupled in a middleware server. Microsoft was quick to launch its new technology based on IIS(web server) called ASP.

java kept developing in the background. Java's concept was simple: Object Oriented, open source and platform independent. For UI based application development, java had awt and then swing. Everything was object oriented.. Eventually swing evolved, new tools were introduced that made it easy to develop forms using java-swing(vb style). In the mean time Java based web technology(asp or .net equivalent) developed independent to swing into the massive J2EE framework. J2EE does everything one would expect from a good middleware framework but for the UI part.

I must say Java couldnt keep its promise of "object orinted" when it comes to the web/html part of J2EE. JSP(an answer to asp) was deviced as java embeded in html which will generate html based UI's at run time to be displayed in the user browser. JSP is (html + java) highly non object oriented. JSP discussion is incomplete without the underlying java counter part: servlets. Servlets are object oriented but I must say it is difficult if not impossible to design UI based forms using servlets. The main problem here is "browser based html" and the decoupling between browser and the middle ware application.

This complexity was addressed using different design patterns, frameworks etc. For instance STRUTS the popular framework to seperate UI, navigation and business logic. And then JSF to remove the disadvantages of STRUTS and to provide a better standard for tool developers. Its all good but where are the objects? For instance, JSF which defines user element placement has become more XML oriented then object oriented.

With evey new standard and framework introduction in the J2EE(web tier) world, we are only moving away from complete object orientation. If you want to know what an complete object oriented application is, and what the advantages are, then just create an application using Java-Swing. In the java-swing world you can create the entire application using the plane old java classes(completely OO) and may be few property files to store customaziable information external to the application code!

So web part of J2EE is bad? I dont have an answer. This is just an evolution, it had to evolve this way. May be the sane thoughts tossed during the evolution didnt win the votes of sponsorers over what is practical.

I would like to propose here one such "sane" but not very practical thought for web based appliaction development:
Create your entire application as an pure java-swing based app. Then create a layer on top of it which will convert the java based swing forms into browser based html pages. Let this layer take care of navigation and other other conversion logistics. We have a simplified framework!


I ran across an commerical application that does just this!
@link to webcreme
This might sound more like an integration tool that must be used to expose the existing java application to web based clients.

But if this concept is explored properly and if the application is designed properly, I think we have a new era of Java web based development.

Feb 13:
@GWT
@Java2Script, RCP to RIA

javadocs in Windows help format?

Ever thought of converting or reading your javadocs in a PDF or windows help file(chm)? Not a bad idea hun? Well check this:
@Commercial tool that does it all
@javadocs in chm
[tbd]@free tool

Monday, August 14, 2006

Free enterprise collaboration platform: TWiki

What is TWiki?

TWiki, a flexible, powerful, and easy to use enterprise collaboration platform and knowledge management system. It is a Structured Wiki, typically used to run a project development space, a document management system, a knowledge base, or any other groupware tool, on an intranet or on the internet. Web content can be created collaboratively by using just a browser. Users without programming skills can create web applications. Developers can extend the functionality of TWiki with Plugins.

"We use TWiki internally to manage documentation and project planning for our products." said Eric Baldeschwieler, Director of Software Development of Yahoo! "Our development team includes hundreds of people in various locations all over the world, so web collaboration is VERY important to us. TWiki has changed the way we run meetings, plan releases, document our product and generally communicate with each other. We're great fans of your work!"

@link

Friday, August 11, 2006

Project build system

Krysalis Centipede is a project build system based on Apache Ant.
It's made to be easy, extensible and powerful.
You can just grab it and start building your project. Anything that is needed for a start is there, and the creation of personalized build targets is straightforward, because it's based on plain Ant. Centipede is un-intrusive, and gives you power without taking any. It also has an interactive target facility, so that the user can just run "build" and choose from a menu.
Link: @Centipede
Other links: @Maven | @Jira

Wednesday, August 09, 2006

Text based graphics: figlet

Ever wonder where the Graphics fonts made out of text come from while chatting in irc or channels alike?
Obviously thro s.w. Unless someone is sitting in N. pole providing his service @ 1c per character! :D

@link

How to run java application as Windows Service?

Procrun is the answer. And thankfully this product is from the open source company Apache.

Procrun is a set of libraries and applications for making Java applications to run on WIN32 much easier.

Prunsrv is a service application for running applications as services. It can convert any application to run as a service.

Prunmgr is a GUI application for monitoring and configuring procrun services.

FYI: Apache Tomcat service in win32 uses the procrun service.

@link

Thursday, August 03, 2006

Insert invisible frame at will

Ever thought of inseting a "hidden" frame in your page, where you can do magical things? Well we all do. Invisible frame is the magic wand for java developers. Well, now you can keep your source(html, jsp, jsf, etc) clean and insert this frame with a function call.

Code below will not only insert a invisible frame, but it will also return you its handle. If you wish you can pass a frame id of your choice, or be careless and the code will generate one.
<br /> /*<br /> *Add a invisible frame in your document and get a handle to it.<br /> *It is not necessary to specify the frame id.<br /> */<br /> var frameCount = 0;<br /> function getInvisibleFrameHandle(frameId)<br /> {<br /> var frameName,html;<br /><br /> if (!frameId)<br /> frameName="_invisibleFrame__" + (frameCount++);<br /> else<br /> frameName = frameId;<br /> if (document.getElementById(frameName))<br /> return document.frames[frameName];<br /> else<br /> appendDocument("<iframe id=" + frameName + " style="visibility: visible; height: 0pt; width: 100%;">");&amp;amp;lt;br&amp;amp;gt; return document.frames[frameName];&amp;amp;lt;br&amp;amp;gt; } &amp;amp;lt;/xmp&amp;amp;gt;</iframe><br /><br />

A generic js function to append text in HTML

Here is a simple js function to append whatever you feel like after your document(html) is loaded in the user browser.

/*
*Append HTML to document.
*WORKS IN ALL BROWSERS
*/

function appendDocument(html)
{
if (document.all)
document.body.insertAdjacentHTML('beforeEnd', html);
else if (document.createRange) {
var range = document.createRange();
range.setStartAfter(document.body.lastChild);
var docFrag = range.createContextualFragment(html);
document.body.appendChild(docFrag);
}
else if (document.layers) {
var l = new Layer(window.innerWidth);
l.document.open();
l.document.write(html);
l.document.close();
l.top = document.height;
document.height += l.document.height;
l.visibility = 'show';
}
}

Java code to create Reports using jasper and text data

Copy paste the code below in Editplus to understand it. It is pretty straight forward to read and understand.
"generateLabels" is a function that will take a string which is really a txt datasource for your designed jrxml file. I used ireports to design the jrxml.

jrxml will return a byte array that can be displayed(response.write) as embeded pdf(or any other format) in the user browser.


public byte[] generateLabels(String dataSource)

{ byte[] pdfBytes=null;

JasperDesign jrDesign;

JasperReport jrReport;

JasperPrint jrPrint;

try{

ByteArrayInputStream dataSourceByteInputStream = new

ByteArrayInputStream(dataSource.getBytes());

JRCsvDataSource jrCsvDs = new

JRCsvDataSource(dataSourceByteInputStream);

String[] header={"label", "details"};

jrCsvDs.setFieldDelimiter(',');

jrCsvDs.setRecordDelimiter(";");

jrCsvDs.setColumnNames(header);

InputStream jrStream =

FileUtil.readConfigFileFromClassPath(this.getClass(),"etc/label.jrxml").getByteStream();

Map parameters = new HashMap();

parameters.put("ReportTitle", "Labels");

jrDesign = JRXmlLoader.load(jrStream);

jrReport =

JasperCompileManager.compileReport(jrDesign);

jrPrint =

JasperFillManager.fillReport(jrReport,parameters,jrCsvDs);

JasperExportManager.exportReportToPdfFile(

jrPrint,"labels.pdf");

pdfBytes =

JasperExportManager.exportReportToPdf(jrPrint);

PdfReader pdfr = new PdfReader(pdfBytes);

ByteArrayOutputStream baos = new

ByteArrayOutputStream();

PdfStamper stamp = new PdfStamper(pdfr, baos);

stamp.addJavaScript(

"this.print({bUI: false, bSilent: false});\r");

stamp.close();

pdfBytes = baos.toByteArray();

}

catch(Exception ex)

{

ex.printStackTrace();

}

return pdfBytes;

}

Auto print on document load

Below is a simple process/hack to bypass the browser print dialog.
  • Generate a pdf for whatever(html or else) you want to print (This is typically done at the server. I use itext) using your fav api.
  • Once you have the pdf(from any source), you are 33% done.
  • Now we will ask the pdf to do something onLoad.
    • guess what "something" is: "Print"!
    • You can embed a piece of js in the pdf that will run at pdf load event.
    • In this js we will ask Acrobat reader to directly print the document to printer
  • Next you will have to load this pdf in an invisible iframe on your page, using javascript.
  • You are done! Trigger the invisible iframe load using either a button click or html-onLoad event. hurray your document is send straight to the printer!!!
  • This method works both in firefox and IE. It ha to, we are basically bypassing the browser security!
Here is the code that will embed javascript in the pdf document. Ofcourse, we will be using java and itext libs to do this.:

PdfReader pdfr = new PdfReader(pdfBytes);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

PdfStamper stamp = new PdfStamper(pdfr, baos);

stamp.addJavaScript("this.print({bUI: false, bSilent: false});\r");

stamp.close();



Loading pdf in an invisible frame is a easy task ... I would let you play arround with this code. Or may be I will post it if time permits!

How to extract a list values from URL

Assuming you are using java servlet, here is a simple method:

Sample:
http://localhost:8080/extract.do?ist=val1&ist=val2

for(String ist:req.getParameterValues("ist")) {

System.out.println("ist: " + ist);

}

Sunday, July 30, 2006

Ruby on Rail

A smart new way to create quick web applications.
Check some of the presentations, really cool stuff.

From the website:
Ruby on Rails is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.


@link

Cracking the pdf

Do you have a locked pdf?
Cannot extract the text?
Cannot print it?
Cannot modify it?
Well, here is a simple solution...

Bang your head over the wall ... :D Just kidding!
Follow these simple steps:

Download and install the latest version of GhostScript
Download and install the latest version of GSView


Thats it!
Open the "locked" pdf in GSView. You can now convert your original file into various types. One of the extension is "PDFWriter". You basically convert your original document(with all the security) into a basic converted document(without the protection).


Hurray, now you can do whatever u want to do with this documnt. Use your fav "free" program to convert the pdf to word, ppt, etc. Or you can mark, copy, extract the text or even print it, if it was disabled.

njoy and thank postscript... and ofcourse me for pointing you there!

Friday, April 21, 2006

Open source ajax

  • DWR - DWR (Direct Web Remoting) is a way of calling Java code on the server directly from Javascript in the browser. DWR consists of two main parts: JavaScript running in the user's browser to communicate with the server and dynamically update the webpage, and a Java Servlet running on the server that processes requests and sends responses back to the browser. DWR takes a novel approach to AJAX by dynamically generating JavaScript code based Java classes. Thus the web developer can use Java code from JavaScript as if it were local to the web-browser; whereas in reality the Java code runs in the web-server and has full access to web-server resources.
  • JSON-RPC-Java - JSON-RPC-Java is a dynamic JSON-RPC implementation in Java. It allows you to transparently call server-side Java code from JavaScript with an included lightweight JSON-RPC JavaScript client. It is designed to run in a Servlet container such as Tomcat and can be used with JBoss and other J2EE Application servers to allow calling of plain Java or EJB methods from within a JavaScript DHTML web application.
  • AjaxTags - The AJAX Tag Library is a set of JSP tags that simplify the use of Asynchronous JavaScript and XML (AJAX) technology in JavaServer Pages. This tag library fills that need by not forcing J2EE developers to write the necessary JavaScript to implement an AJAX-capable web form. The tag library provides support for live form updates for the following use cases: autocomplete based on character input to an input field, select box population based on selections made from another field, callout or balloon popups for highlighting content, refreshing form fields, and toggling images and form field states on/off.
  • Echo 2 - Echo2 is the next-generation of the Echo Web Framework, a platform for developing web-based applications that approach the capabilities of rich clients. The 2.0 version holds true to the core concepts of Echo while providing dramatic performance, capability, and user-experience enhancements made possible by its new Ajax-based rendering engine.
  • AjaxAnywhere - AjaxAnywhere is designed to turn any set of existing JSP components into AJAX-aware components without complex JavaScript coding.
  • ActiveMQ Ajax Support - Ajax support in ActiveMQ builds on top of the REST connector for ActiveMQ which allows any web capable device to send or receive messages over JMS. All the Ajax examples are currently using OpenRico.
  • Tacos - The Tacos library project provides components and ajax behaviour for the Tapestry java web application framework. Most of the library relies almost exclusively on Dojo.
  • WebWork 2.2 Awesome AJAX support built on top of DWR and Dojo. Form validation, tabbed panels, remotable forms, and remote divs. More AJAX components will be coming in subsequent releases.
  • Simple Web Framework - The Simple Web Framework (SWF) is an event based framework targeting Struts developers who want to build rich Web applications but do not want to migrate to JSF. The SWF is built upon the same Jakarta commons basis as Struts, but uses a different request processor (front controller.) The SWF event model supports XmlHttpRequest (as well as form/submit) based event posting, similar to VB.NET or JSF, with In place Page Updating (IPU) rather than page reloading.
  • Wicket 1.1 rc2 - Dojo, Scriptaculous and Wicket integration. The release consists of an Ajax handler, allowing you to create your own custom Wicket Ajax components based on the Dojo toolkit.
  • Taconite - The heart of Taconite is a parser that converts normal (X)HTML code into a series of JavaScript commands that dynamically create the content on the browser. This parser allows you, the developer, to write content in way that is natural -- as (X)HTML. You no longer have to crowd your pages with a slew of document.createElement and document.appendChild commands to dynamically create new content. The Taconite custom parser is implemented as a set of JSP custom tags, which can be used in any Java servlet container, or as a client-side JavaScript library, meaning it can be used in conjunction with virtually any server-side technology.
  • SWATO - Server side Java library can be deployed in Servlet 2.3+ compatible containers. Client side JavaScript library is base on Prototype. JSON based marshalling. Spring integration. Includes several reusable components like auto-suggest Textbox, Javascript templates and logging.
  • Zimbra - Zimbra is an open source server and client technology for AJAX based messaging and collaboration. The collaboration server is built using Java based technologies. The server features file based message storate, a SQL metadata storage, Lucene based search, clustering, replication, archiving and LDAP support.
  • Orbeon Presentation Server (OPS) Version 3.0 - OPS 3.0 features an XForms engine much improved over OPS 2.8's, significant improvements in the Page Flow Controller, and more. The XForms engine is now based on Ajax technologies. This makes the XForms engine much more responsive to user interaction than with OPS 2.8. The new Ajax-based XForms engine, present in OPS 3.0 and forward, is refered to as the Next Generation XForms engine or, in short, as XForms NG.
  • JsOrb - JsOrb includes code generators that build on demand JavaScript classes for your POJOs and as proxies to your business logic interfaces. The JavaScript classes have the same methods as your POJOs and business logic interfaces, so your JavaScript code ends up looking surprisingly similar to Java.
  • ZK - ZK is an event-driven, XUL-based, AJAX-embedded, all Java framework to enable rich user interfaces for Web applications. With ZK, you represent and manipulate RIA in XUL/HTML components all at the server similar to how you developed desktop apps. ZK includes an AJAX-based event-driven engine to automate interactivity, and a rich set of XUL-based components.
  • Rialto - Rialto is a cross browser javascript widgets library. It supports pure javascript development and JSP/taglib development. A JSF integration is planned.
  • JSP Controls Tag Library - JSP Controls Tag Library (the "Library") provides the lifecycle for portlet-like JSP components. The Library does not require a portal engine or other central controller. The components built with the Library can be used in any JSP-based application. The Library supports two request processing modes: Non-Ajax and Ajax. Pages composed with JSP Controls Tag Library look and behave the same way whether they run in Ajax mode or not.
  • OpenLaszlo - OpenLaszlo programs are written in XML and JavaScript and transparently compiled to Flash and DHTML. The OpenLaszlo APIs provide animation, layout, data binding, server communication, and declarative UI.

@link to main article

Tuesday, April 18, 2006

Wink, FREE screen recording tool

Wink is a Tutorial and Presentation creation software, primarily aimed at creating tutorials on how to use software (like a tutor for MS-Word/Excel etc). Using Wink you can capture screenshots, add explanations boxes, buttons, titles etc and generate a highly effective tutorial for your users. Here is a sample Flash tutorial created by Wink. Click the green arrow button to start viewing it. -------->
(More tutorials created by Wink users and companies can be found at the User Forums.)

This is a good example of how you can create tutorials in Wink, by capturing screenshots, mouse movements and specifying your own explanations with them. And all this in a standard Windows-based UI with drag-and-drop editing makes it very easy to create high quality tutorials/documentation.

It is estimated that Macromedia Flash Player is installed in more than 90% of the PCs. Using Wink you can create content viewable across the web in all these users' desktops. Similar applications sell for hundreds of dollars, while Wink is free with unrivaled features. So spread the word about Wink to your friends.

Winki @linki

Friday, April 07, 2006

Tools for Hibernate 2.x

The tools used for roundtrip development in Hibernate 2 provide support for transforming to

and from sourcecode (java), mappingfiles (hbm) and a database definition (ddl). Use the new tools for Hibernate 3.x.

The goal of these tools is to help support the usage of Hibernate in almost any kind of development scenario. For example, if you start with an existing (legacy) database, use the tools to generate Hibernate mapping files and Java source files. If you start with Java code, you can markup your classes with XDoclet tags and automatically generate Hibernate mapping files from your annotations. Of course, you can also generate a SQL database schema (DDL) automatically from a Hibernate mapping.

Note, that not all tools provide complete support for all features in Hibernate, as it is simply not possible to generate every output from every input (for example, a database schema doesn't have enough information to generate perfect Java classes).

@link

Sunday, April 02, 2006

WebScarab - Open Web Application Security

WebScarab is a tool designed for Web security professionals and Web developers. It allows the user to view the traffic between the Web browser and server, and modify it in transit. WebScarab is intended to become the tool of choice for serious Web debugging.

WebScarab is a framework for analysing applications that communicate using the HTTP and HTTPS protocols. It is written in Java, and is thus portable to many platforms. In its simplest form, WebScarab records the conversations (requests and responses) that it observes, and allows the operator to review them in various ways.

WebScarab provides a number of plugins, mainly aimed at the security functionality for the moment. Those plugins include:

  • Fragments - extracts Scripts and HTML comments from HTML pages as they are seen via the proxy, or other plugins

  • Proxy - observes traffic between the browser and the web server. The WebScarab proxy is able to observe both HTTP and encrypted HTTPS traffic, by negotiating an SSL connection between WebScarab and the browser instead of simply connecting the browser to the server and allowing an encrypted stream to pass through it. Various proxy plugins have also been developed to allow the operator to control the requests and responses that pass through the proxy.
    • Manual intercept - allows the user to modify HTTP and HTTPS requests and responses on the fly, before they reach the server or browser.

    • Beanshell - allows for the execution of arbitrarily complex operations on requests and responses. Anything that can be expressed in Java can be executed.

    • Reveal hidden fields - sometimes it is easier to modify a hidden field in the page itself, rather than intercepting the request after it has been sent. This plugin simply changes all hidden fields found in HTML pages to text fields, making them visible, and editable.

    • Bandwidth simulator - allows the user to emulate a slower network, in order to observe how their website would perform when accessed over, say, a modem.


  • Spider - identifies new URLs on the target site, and fetches them on command.

  • Manual request - Allows editing and replay of previous requests, or creation of entirely new requests.

  • SessionID analysis - collects and analyses a number of cookies (and eventually URL-based parameters too) to visually determine the degree of randomness and unpredictability.

  • Scripted - operators can use BeanShell to write a script to create requests and fetch them from the server. The script can then perform some analysis on the responses, with all the power of the WebScarab Request and Response object model to simplify things.

  • Parameter fuzzer - performs automated substitution of parameter values that are likely to expose incomplete parameter validation, leading to vulnerabilities like Cross Site Scripting (XSS) and SQL Injection.

  • Search - allows the user to craft arbitrary BeanShell expressions to identify conversations that should be shown in the list.

  • Compare - calculates the edit distance between the response bodies of the conversations observed, and a selected baseline conversation. The edit distance is "the number of edits required to transform one document into another". For performance reasons, edits are calculated using word tokens, rather than byte by byte.

  • SOAP - There is a plugin that parses WSDL, and presents the various functions and the required parameters, allowing them to be edited before being sent to the server.

@link