Friday Dec 04, 2009

Drawing TrueType Fonts Using Java

The various fonts that are displayed in any raster image of a display device or a printer requires a font engine to render them. TrueType fonts are a specific kind of font format that  are widely used by Mac and Windows machines. These are  binary files with the extension .ttf and could be converted to human-readable files using utilities like fonttools (in Ubuntu). A typcal human-readable truetype font file would look like an XML file with data to draw all the characters of a font. The is XML file could be parsed and drawn as an image output using Java's Graphics2D API.

 Any  character (or the glyph in broader  terms) to be rendered is represented as a set of contours . Each contour is a path formed by straight lines and Bezier curves, that are in turn connected by a set of points in the x-y co-ordinate space (read as raster space for the display). In addition to the x and y co-ordinates, the points also have a boolean value indicating if the points are either on-curve or off-curve. An on-curve point is part of the contour while the off curve point is a control point of the Bezier curve. A single control point indicates a quadratic Bezier curve while two control points indicate a cubic Bezier curve.

To draw the glyph using Java, the Graphics 2D API (java.awt.\*) could be used. Each point is represented using java.awt.geom.Point2D.  The contour is represented using java.awt.geom.GeneralPath  and the lines and Bezier curves are drawn using the methods lineTo(), quadTo() and curveTo() to represent straight lines, quadratic and cubic Bezier curves respectively.

 Here are the code snippets for the methods:

private static void drawLine(GeneralPath.Double path, Point2D point1, Point2D point2)   {

      path.moveTo(point1.getX() , point1.getY());          

      path.lineTo(point2.getX(), point2.getY());
    }

    private static void drawBezQuadCurve(GeneralPath.Double path, Point2D point1, Point2D controlPoint, Point2D point2) {

path.moveTo(point1.getX() , point1.getY());  

           path.quadTo(controlPoint.getX() , controlPoint.getY() , point2.getX() , point2.getY() );
    }


    private static void drawBezCubicCurve(GeneralPath.Double path, Point2D point1, Point2D ctrlPt1, Point2D ctrlPt2, Point2D point2) {

         path.moveTo(point1.getX() , point1.getY());   

         path.curveTo(ctrlPt1.getX() , ctrlPt1.getY() , ctrlPt2.getX() , ctrlPt2.getY() , point2.getX() , point2.getY());
    }

A contour is constructed from this path using java.awt.geom.Area  . The different contours of a particular glyph are eXlusive ORed before they are filled to provide an exact replica of the font glyph:

            if (contourArea == null) {
                contourArea = new Area(glyfPath);
            } else {
                contourArea.exclusiveOr(new Area(glyfPath));

            }

The algorithm for drawing the glyph must be able to clearly distinguish the lines, quadratic and cubic Bezier curves and draw them accordingly. 


Saturday Mar 21, 2009

The Source is Out There...

Having worked for a couple of years  now in the open source software realm, I guess it would be worthwhile to key down my reminiscences, and with the Open Source Mela Blogging Contest instigating a reason to write, here are some nuggets of what I consider my experience with the open source software . 

It would do this post better justice if initially,  I speak-not from an open-source software developer's perspective...So let me impersonate someone who spends their free time trying to hack some written code or write some hackneyed code for the benefit of the body and soul or at times for the larger benefit of the brethren. What  would this kind of passion-driven programmer turn to at first attempt, for his software needs ranging from an IDE to a server to any framework? Free open source software or premium paid secret sauce software? Its clearly the former..And if that free-lance  software developer is reasonably good at what he does, he is likely to produce another innovative piece of open source software , exploring the existing ones and fitting a few right ones in the right places..For this precise reason - freedom to innovate, open source software is priceless...in the exact sense of the word..

To the astute novice programmer,  the code that is open is a free practical tutorial not just for familiarizing himself with  "professional" software, but also clarifying issues, participating in the community and contributing more to the existing source. So the student community is  likely to get more familiar with the open source software while in school, and if old habits do die hard, the students are likely to stay in touch with these when they graduate to professional programmers. So, open source software does have the pedagogical edge too..

To the open-source software developer,  community participation in terms of issues and forum questions not only help in free testing of the "unexplored areas in unknown avenues", but also to open that normally closed perspective to new suggestions..And of course, it helps in making new interesting friends..Trust me :)

So all said and done, what of the revenue factor?How valuable or vulnerable are the original software developers to the open-source software product which has a strong community base? These are some hard questions which require strategic answers that might make or break the open-source software product. But being open-source is like being infectious..It has to spread  across vendors, sooner or later, unless of course, you are bolstered by a strong immune system. So, if the  cardinal factors which  might help such an open-source product survive the test of revenue and the test of time are decisively addressed, this does seem the way for the industry to go...The source is out there..Go, Seek it!!

Tuesday Mar 10, 2009

VirtualBox in LAN

If you would like to make a Linux virtual machine (created using say Sun's VirtualBox)  connect to your LAN to which the host machine is a part of, you could follow these steps:

(0) Create the virtual machine and install the guest OS (I installed Ubuntu).

(1) Install bridge-utils and uml-utilities on the guest OS:

         sudo apt-get install bridge-utils uml-utilities

(2) Edit /etc/network/if-pre-up.d/uml-utilities to change:

     chown root:uml-net /dev/net/tun

      to      chown root:vboxusers /dev/net/tun

(3) Change the VirtualMachine settings from NAT (the default) to Host Interface in the Network settings tab of the GUI.

(4) Restart the networking service

     sudo /etc/init.d/networking restart

After this, the virtual  machine can be accessed from any other machine on the LAN using ssh or vnc if these services are available on the guest OS. For more advanced configuration including TUN/TAP settings, this link might be useful.



Monday Sep 01, 2008

WSRP Consumer in Liferay

    The OpenPortal WSRP Consumer has been integrated with Liferay Portal, and is available in the stable and community builds of WebSynergy. This blog post would illustrate the basic features of this integration. All the features that are available with the Sun's implementation of WSRP 2.0 with the OpenPortal Portlet Container have been integrated with Liferay and consequently with WebSynergy as well. The admin portlets now have the modified look and feel. Here are some screenshots showcasing the Consumer Admin Portlet in WebSynergy.

The WSRP Consumer Admin Portlet:

LR Consumer Admin Portlet

Creating a Consumer:


Viewing the Details of a Consumer: 


As can be observed, this admin portlet supports the major functionalities in WSRP 2.0 Consumer creation - OutOfBand Registration (using RegistrationHandle), Leasing, Registration Properties amongst others. Producer Integration and Producer Admin Portlet are expected to be integrated with Liferay  in the next stable release of WebSynergy.


Thursday Aug 07, 2008

MBR Repair Utility for Windows

Recently I had the privilege of corrupting the MBR of my laptop. The modus operandi - I formatted the Solaris partition from my Windows boot. That consequently corrputed the grub and the Master Boot Record. Only later did I discover that a lot of people I knew had done this quite frequently. A typical solution for this problem was to boot from a live Windows CD, launch the Revocery Console, and run the fixmbr utility. (For Windows versions previous to 2000, the fdisk utility could be used as well, but for the newer versions, this utility was scrapped, since Recovery Console was provided).

An atypical but useful solution would be to boot Windows from any live CD (I used Belenix), boot Windows from the command prompt, and run this Mbrfix utility. You don't need to have a Windows Live CD or Recovery Console. This atypical solution was provided by an extremely resourceful and benevolent colleague, and it worked.

Tuesday Jun 17, 2008

Leasing for Remote Portlets

WSRP 2.0 offers Leasing of Portlets as part  of the specification. Leasing is the process by which a Consumer registers with a Producer for a specified time period, after which the Consumer Registration is rendered invalid. Lifetime is an optional parameter in the Registration offered by V2 producers. The OpenPortal WSRP project (Sun's open source implementation of WSRP ) has implemented this feature using the Open Source Portlet Container 2.0 . Check this wiki page for more information on portlet leasing.

A quick guide to Leasing with Open WSRP and PC 2.0 

1. Download and install PC 2.0 and WSRP  . For instructions on download, refer to the install instructions

2. Create a V2 producer (supporting Inband Registration) using the Producer Admin Portlet. Publish a few portlets and enable the Producer.

3. Create a V2 consumer. Check the Lifetime Supplied checkbox. Specify the Valid No of Days, Hours and Minutes, say 0,0,15. This means that the Registration is valid only for the next 15 minutes. Click the Consumer to view the time until which Registration is valid.

4. Create  a remote portlet in a window for the Consumer. Check the remote portlet before and after the Registration cut -off time. After the lifetime expires, the remote portlet would not be rendered.

Lifetime


Monday May 19, 2008

What's the site running on?

To get to know the details of a site, like the operating system, hardware, server, IP addresses of the servers among others, check out Netcraft

For instance, here are the details of this site:  http://blogs.sun.com/nithya

unknown Sun-Java-System-Web-Server/7.0 19-May-2008 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Apr-2008 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 18-Feb-2008 72.5.124.56 SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 17-Feb-2008 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 15-Feb-2008 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Jan-2008 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 4-Nov-2007 72.5.124.56 SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 25-Oct-2007 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 14-Oct-2007 72.5.124.56 SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 13-Oct-2007 72.5.124.56 SUN MICROSYSTEMS

Thursday May 15, 2008

Websites Offering Web Services APIs

Here is a list of web service APIs offered by popular companies that are available for integration with customized applications. Popular ones include the services offered by Yahoo, Google, Amazon, Remember The Milk, Second Life amongst others...

 

Tuesday May 13, 2008

JavaScript Debugging with FireBug

Firebug is the browser debugger, available as a firefox add-on. Client-side debugging, which becomes particularly important in Ajax applications with extensive JavaScript, is made much simpler with this add-on feature. Some of the features offered are 

1. Http Monitoring and Inspection - The HTTP Requests, Responses, Headers, Response times (along with their Ajax XMLHttpRequest counterparts) can be viewed and monitored.

2. Breakpoint Debugging - Breakpoints can be set and the code flow can be stepped in , stepped out or stepped over.

3. Console Logging - In firefox browsers, an implicit object called console is made available, Log statements can be inserted using console.log("Logged")

4. DOM Inspection - The HTTP DOM tree can be inspected down to the smallest elements

5. Profiling - console.profile() and console.profileEnd() methods could be used to analyse the time elapses within code blocks..

Firebug can be opened in the same browser tab as the HTML page or a different tab. Its as simple to use as it sounds too :). Open Firebug (preferably in the same browser tab), explore the tabs, go to say script tab, the entire Javascript of the HTML page is made available here. Set the breakpoints, and refresh the browser. The requests, headers can be seen and  the debugging cursor stops at the first breakpoint. Step over, step in, step out , monitor and inspect the Javascript objects and HTML objects. If you are still stuck, insert log statements and check them in the console...Go, debug the bugs..

 With Firebug, client side debugging seems to have truly evolved...

Monday May 12, 2008

Expense Reports Widget

    The expense-report widget, that is delivered as a part of the Project WebSynergy bundle, models a typical workflow scenario  where SAW (Simple API for Workflow) could be used. In an organization, employees raise expense reports and submit them to the managers to be approved or rejected. Once submitted, the report triggers a workflow process(in a workflow engine like JavaCAPS), and becomes a pending task for the associated manager. When the manager approves/rejects the report, the report goes to the next step in the workflow process.

This widget has been integrated with a simple JavaCAPS workflow process. If a workflow engine is unavailable, the SAW calls to the  Workflow engine can be disabled using the preferences. If the call to the workflow engine is enabled without configuring the engine, it results in a system error.
 

In addition to Workflow, this widget has the following features: 

  •  JMaki - Uses JMaki Yahoo Datatable
  •  Usage of ServeResource feature of JSR286 portlets for Ajax requests (For Displaying Report Details)
Using the widget:

An Expense Report is a report comprising details of the expenses (like Business Travel, Relocation, BroadBand Bills Claim) incurred by an employee that he could reclaim from the organisation with the manager approval. The typical claim process works like this:
Creating a New Expense Report
1. Employee (say Paul) logs in to websynergy, navigates to the sunspace tab to the expense report widget, and creates a new expense report, providing details of individual items of the report.
2. He can choose to either save the report or submit the report on creation.
Viewing Reports Summary
3. On login, Paul can view the summary of Saved(to be submitted by him) Reports and Pending(to be approved by the manager) Reports that are raised by him.
4. On clicking a particular Report ID, he can view the details of the report including the individual item details (Viewing Report details is done without a page refresh through Ajax calls).
Submitting Saved Reports
5. When he views a Saved Report Detail, he has an option to Submit it. When a report is submitted, a workflow process is triggered in JCAPS through a web service call.
Manager Login
6. When Paul's manager (Mary)logs in, she can see a list of pending reports that he has raised (in the first table) and a list of pending reports raised by her reportees (second table), waiting for his approval.
7. The list of Pending tasks is obtained from the JCAPS through SAW API
Approval and Rejection of Reports
8. On clicking on any report that is waiting for her approval, she can view the details of the report (without page refresh) and approve or reject it.

Here is a step-by-step screencast showcasing the widget.

Friday Mar 07, 2008

WSRP on Tomcat 5.5

WSRP (Web Services for Remote Portlets) is a protocol specification using which portlets are published and consumed as web services.This enables portlets that are deployed on any container to be rendered in the local container as long as the containers are configured for WSRP.  The major components that make up the WSRP architecture are:

1. Producer - For exposing the portlets as web services, managing consumer registration apart from the others

2. Consumer - For rendering the remote portlets similar to the local portlets in the container

3. Producer/Consumer Administrative Portlets - These provide the UI for managing the administration of the producer and consumer

4. WSRP Test Driver - An environment for deploying, testing remote portlets

5. WSRP Administrative Interface - These consist of Mbeans that perform administrative tasks that the admin portlets use.

For a more detailed understanding of WSRP, refer to this article.

Currently WSRP can be configured on Tomcat 5.5 and Portlet Conainer 2.0 in addition to Glassfish Application server. Here are the instructions.

 Resources for WSRP:

1. The WSRP java.net page

2. Rajesh's blog



Sunday Mar 02, 2008

Intepreted or Compiled?

Here are some of the commonplace jargons about Java that distinguish it from the rest of the object oriented languages...It is interepreted, It is platform independent, it is dynamically linked and extensible, it can transport the state of objects across networks, it has a robust architecture..et cetera...These are certainly some of the reasons that make Java what it is today(though some of these features have some performance  trade-offs too). One important feature that is associated with the Java brand is "Intepreted, Not Compiled"

There are many good articles that elucidate the difference between interpretation and compilation . This post is but a redundant synopsis of the many discrete articles...

The technical distinction between interpretation and compilation becomes clearer if the semantic(linguistic) distinction between these types of translations is understood. Lets suppose you are given a Spanish document and you intend to translate it to English. You employ two kinds of translators for this -  one an interpreter and another a compiler. The interpreter takes the first Spanish line, translates it to English, voices it aloud to you, proceeds to the next line and so on. So if there are references to a previously read paragraph or line, he does the translation again for them. A compiler on the other hand takes the entire document, translates it to English, and hands over the document to you.

Langauge compilers and interpreters are but similar. In case of Java, the java compiler compiles the java code to bytecode. The bytecode is intepreted  by the JVM and yes, it is line by line interpretation. So as it is obvious, this kind of intrepretation makes Java inherently slow. Here is an overview of the most popular interpretors/compilers for java

Enter JIT Compilers

JIT compilers operate on the Java bytecode, not the source code. So essentially, they are a part of the JVM. They are meant for translating the bytecode one method at a time to a form of native code so that the program executes faster than the usual interpretation.The translated code is stored in cache and is resused during program execution.This implies that JIT compilers do require more RAM attached to the JVM.   JIT compilation is usually done on a separate thread from the application execution thread, so that the application does not have to wait for this compilation.

Enter Adaptive Compilers

JIT compilers  were causing memory issues since they stored all natively compiled methods in cache, Adaptive Optmized compilers where introduced. These compile only those sections of the bytecode that are most frequently accessed into the native code and store them. They give better performance results compared to JIT compilers

Enter AOT compilers

AOT (Ahead of Time) compilers are meant for producing a monolithic executable for a specific platform from the bytecode and are used  predominantly in embedded systems. They use static linking as against the traditional java dynamic linking, require more ROM as against RAM as in case of JIT compilers, since they store the compiled machine code in ROM/flash memory. So AOT compilers are best sutiable for systems where dynamic extensions are not used, but have performance issues with the traditional interpretation techniques/JIT compilation.

So now, is Java compiled or interpreted? The answer is probably, it is a bit of both....

And what makes Java platform neutral? Try this analogy ; Java bytecode is the machine code if the JVM is the OS. In other words, bytecode is the machine code that the JVM expects. So as long as you have the JVM , java bytecodes (that is the java class file) can run on any OS ( Solaris or Linux or Mac or Windows or the mobile phone or a toaster). The JVM is highly platform dependent though. Another feature of the bytecode is that it follows the big-endian representation of bytes for all OS , since it is the JVM that interprets it.

Thursday Feb 28, 2008

How Mutable is an Immutable class?

The  common interview question - What is an immutable class and how would you write an immutable class in Java?

The common interview answer - An immutable class is one whose instance, once created, cannot be modified. The infamous example is the String class. To implement an immutable class, we mark the class final, lest it is extended by any other class, mark the member variables private and remove the setters.

The 'Not-So-Common' addendum to the question - Assume that the getter returns an object reference and the developer modifies the reference. Dosen't that mean that the original supposedly immutable class is modified?

 (eg)  Assume we try to implement an immutable class A as follows:

public final class A {
    private B b;
    public A(B b)
    {
        this.b = b;
    }
    public B getB()
    {
        return b;
    }
}

class B {
    int i;
    public B() {
     }
    public B(int i) {
        this.i = i;
    }
    public void set(int i) {
        this.i = i;
    }
    public int get() {
        return i;
    }
}

Class A is final and has no setter. It is supposedly immutable, However it has a reference to an object B. If someone does the following:

        B b = new B(5);
        A t = new A(b);
        B b1 = t.getB();
        System.out.println(t.getB().get());
//prints 5
        b.set(6);
        System.out.println(t.getB().get());
//prints 6
        b1.set(7);
        System.out.println(t.getB().get());
//prints 7

So since we have the references to the B object (i) that is passed to the constructor and (ii) that is obtained from the getter, Class A is not completely immutable. While these references are modified externally, the object that A has is modified, thus rendering A mutable.

The actual question : How can A be made completely immutable?

A possible (usually expected) answer: In the constructor of the immutable class, have make copies of the objects that are passed and store the copied objects, not the passed object reference.Similarly in the getter of the immutable class, make a copy of the to-be-returned object and return the copy, not the stored object.

So the actual immutable code would look something like:

public final class Test {
    private B b;
    public Test(B b1)
    {
        this.b = new B();
        this.b.set(b1.get());
    }
    public B getB()
    {
        B b1 = new B();
        b1.set(this.b.get());
        return b1;
    }

Now, on running

        B b = new B(5);
        A t = new A(b);
        B b1 = t.getB();
        System.out.println(t.getB().get());
//prints 5
        b.set(6);
        System.out.println(t.getB().get());
//prints 5
        b1.set(7);
        System.out.println(t.getB().get());
//prints 5

Now that class was a little less mutable :)

Tuesday Feb 26, 2008

Java Debugging with Netbeans

    Debugging can be quite a wearing experience, especially if it has to be done aidlessly. Nevertheless it is a quintessential technique for Software "bug-fixers". Netbeans offers some good  features which could help in debugging server, applet or command-line processes. Breakpoints, watches, call stack navigation and such additional features help in seeing the code under the hood. This post is a primer on Debugging with Netbeans

     The basic idea of debugging is that there are two processes - one a Serversocket that listens on a specific port and another that attaches itself to that port during the debugging process.Netbeans offers both kinds of sockets  - (i) A "SocketAttach" that attaches to the port  at which  the java process/server process listens to and a (ii) "SocketListen" that listens at the specific port to which another process (say an applet) would attach to.

Steps for Server Process Debugging

This is probably the most widely used form of debugging.

1. Start the server in the debugging mode. (For Glassfish, this is done by setting the debug-enabled flag to true in <DOMAIN-DIR>/config/domains.xml and restarting the server. Note the port no at which the server is listening)

2. In the Netbeans IDE, open the code base which is in sync with the deployed server code.

3. Goto Run-> Attach Debugger -> Choose ServerAttach mode. The NB IDE attaches to the socket opened by the server in this case.

4. Provide details of the server host and port

5. Set breakpoints in the code and launch the application. The thread stops at the breakpoints, and the code could be stepped over or stepped into to debug further.

Steps for Java Command Line Debugging

1. To debug a java command line process, run the command in the debug mode:

java -Xdebug -Xrunjdwp:transport=dt_socket,address=<portNo>,server=y,suspend=y ABCProg

2. Open the code base in Netbeans and Attach the debugger in the SocketAttach mode, provide the host and port information

Steps for Applet Debugging

1. For Applet debugging, go to the Java ControlPanel (In Unix, it is <JAVA_HOME/bin/ControlPanel, in Windows, ControlPanel -> Java). Navigate to the Java tab - View Settings - Edit the Java Runtime settings. Furnish this information:

-agentlib:jdwp=transport=dt_socket,address=<hostName>:<portNo>

This makes the browser JRE open a socket connection while launching the applet.

2. Open the NB code base and attach the debugger in the SocketListen mode by furnishing the host and port information.

 

Happy Debugging!!!

Monday Dec 24, 2007

An Ajax Based Yahoo Suggest and Search Portlet

Recently I got to try the Yahoo Search API . Yahoo offer many REST based service APIs which could be consumed for web-applications. Tried to develop a JSR 286 portlet (Portlet spec v2.0) that uses Ajax and serveResource feature of JSR286 specification to make aysnchronous API calls to the portlet which in turn makes calls the Yahoo REST services through Apache HttpClient. Since the result of the REST calls are JSON based, it is not difficult to extrace the suggest or search results.

From the Portlet Perspective, the XMLHttpRequest from the VIEW Jsp sends a resourceURL with the search keywords as the input parameters to the portlet.The portlet implements the ResourceServingPortlet interface, and thus implements the abstract method serveResource, in which calls to the REST services are made. The response type is set as 'application/json' and the resultant JSON object is embedded in the resourceResponse. The onReadyStateChange action handler of the JSP processes this JSON response and displays the search results.

To the end user, the portlet offers a search box, which offers suggestions as the user keys down letters, (with each keypress, aysnchronous REST calls are made to the yahoo related search API  and the resultant suggestions are displayed as a dropdown and when the Search button is pressed with a specific user-entered or user-selected keyword, aynschronous calls are made to retrieve the search results similar to the previous case. 

Though this portlet was initially a product of academic interest, it could be further developed to adapt to Google and other custom search engines, which Im currently trying to enhance.  The pre-requisites are a Portlet V 2.0 portlet container (Sun's OSPC 2.0 could be used) and Apache HttpClient.

 This portlet is available for download and use here

 

 

About

nitkal

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks