Image

Javadoc from Eclipse

  1. Project > Generate Javadoc
  2. For Javadoc command field: browse & point javadoc.exe (found in \\JDK_dir\bin)
  3. In the next split pane check the project/package/class you need to generate the doc for
  4. Browse & point the Destination directory to which you would like to get the javadoc
  5. Click Finish
  6. Open the index.html (from your destination folder which you pointed in 4.)

 

Kudos You are done with your documentation, now it’s a code with its manual 🙂

Singleton Explained

There are handful of ways to define a Singleton class in Java. They aren’t that difficult yet, doing it the correct way matters. Here I have listed 3 ways of doing it. However, only the 3rd which uses on-demand holder acronym is preferred as the singleton instance created here is thread-safe & is unique.

Trivia 1: Why we don’t import classes like System, Integer and String?
Ans: The package java.lang.*; is implicitly imported.

Trivia 2: Can main method of a java program reside in an abstract class?
Ans: Yes it can! See the Driver class below.

1. Eager Singleton

package design.com.hamzeen;

public class EagerSingleton {
	private static EagerSingleton ins = new EagerSingleton();

	public static EagerSingleton getInstance() {
		return ins;
	}

	private EagerSingleton() {
	}
}

2. Lazy Singleton

package design.com.hamzeen;

public class LazySingleton {
	private static LazySingleton ins;

	public static LazySingleton getInstance() {
		if (ins == null) {
			ins = new LazySingleton();
		}
		return ins;
	}

	private LazySingleton() {
	}
}

3. Singleton Holder

package design.com.hamzeen;

public class SingletonHolder {
	public static SingletonHolder getInstance() {
		return Holder.ins;
	}

	private static final class Holder {
	  private static final SingletonHolder ins = 
				new SingletonHolder();
	}

	private SingletonHolder() {
	}
}

The Driver and Output

package design.com.hamzeen;

public abstract class Driver {

	public static void main(String[] args) {
	  EagerSingleton a1 = EagerSingleton.getInstance();
	  EagerSingleton a2 = EagerSingleton.getInstance();
	  System.out.println(a1.toString());
	  System.out.println(a2.toString());

	  LazySingleton b1 = LazySingleton.getInstance();
	  LazySingleton b2 = LazySingleton.getInstance();
	  System.out.println(b1.toString());
	  System.out.println(b2.toString());

	  SingletonHolder c1 = SingletonHolder.getInstance();
	  SingletonHolder c2 = SingletonHolder.getInstance();
	  System.out.println(c1.toString());
	  System.out.println(c2.toString());
	}
}

design.com.hamzeen.EagerSingleton@15db9742
design.com.hamzeen.EagerSingleton@15db9742
design.com.hamzeen.LazySingleton@6d06d69c
design.com.hamzeen.LazySingleton@6d06d69c
design.com.hamzeen.SingletonHolder@7852e922
design.com.hamzeen.SingletonHolder@7852e922

An insight into observer pattern

One of the things which I often encounter these days is design patterns. If I’m to give a head first to design patterns, they articulate solutions to some of the commonly occurring design problems with related to software development. Hence, it promotes design reusability just as Object-Oriented Programming (OOP) encourages code reusability. The Observer, which is classified as a behavioral pattern can become quite handy in case of handling events (event-driven) specially, if your project adopts Model View Control (MVC) architecture.

At the heart of Observer pattern are Source and its Observers. The idea behind the pattern is to allow multiple observers (which can be views such as windows, web pages or any other simple UI element like a label) to be able to listen to its Model, known as the Source by registering to it. The relationship between the source and the observers is hence, known as publish-subscribe relationship.

An apt situation to employ Observer would be, modifying a certain field on a window while couple of more windows which also utilize the same field are kept opened. One would expect this modification to instantaneously take effect on all of the windows which utilize the particular field. This characteristic can easily be ensured with Observer. A simplified implementation of the pattern in java can be found below.

View1.java

import java.util.Observable;
import java.util.Observer;

public class View1 implements Observer
{
  public void update(Observable o, Object arg)
  {
    System.out.println("View 1: " + arg.toString());
  }
}

View2.java

import java.util.Observable;
import java.util.Observer;

public class View2 implements Observer
{
  public void update(Observable o, Object arg)
  {
    System.out.println("View 2: " + arg.toString());
  }
}

UserData.java

import java.util.Observable;

public class UserData extends MyObservable{
  private String name;
  private Long id;

  public UserData(){
    this.name = "";
    this.id = (long)0;
  }

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
    setChanged();
    notifyObservers(name);
  }

  public Long getId()
  {
    return id;
  }

  public void setId(int id)
  {
    this.id = (long)id;
    setChanged();
    notifyObservers(id);
  }
}

TestMain.java

public class TestMain
{
  public static void main(String[] args)
  {
    UserData data = new UserData();
    View1 view1 = new View1();
    View2 view2 = new View2();
    data.addObserver(view1);
    data.addObserver(view2);

    data.setName("Lenard");
  }
}

Lumar – A new dimension to reality browsing.

After being in labs for couple of decades, Augmented Reality has become a highly popular phenomenon in recent times. Specially, Mobile Augmented Reality platforms promise to transform geographical information systems to give them a new look that will make such applications more meaningful and entertaining to use.

One of the finest examples of this would be Reality Browsing where geo-tagged data from various sources such as Wikipedia, Panoramio, Twitter, Flickr and etc are overlayed real-time over a video. Along with the inclusion of compass, GPS receiver, accelerometer and video camera which have become common features on most modern smart phones, reality browsing has already entered mainstream and continues to grow.

Explorer View

Explorer View


Ground View

Ground View

Lumar, a reality browser for android smart phones will become the world’s first speech powered browser of its kind. Now it is available for public downloads via Android Market. The first release candidate contains layers such as Wikipedia, Twitter and Buzz. It also features a unique stations layer where it can show all major bus and railway stations around you. The video below gives a glimpse of how Lumar operates. Enjoy!

Developing a Desktop Widget in JAVA

This widget will be developed using Eclipse SWT. Hence assuming you already have java and eclipse, you will also require to download Eclipse SWT zip. Which you can download on,

http://www.eclipse.org/swt/

Though to develop this particular widget you will not require a expertise knowledge in Eclipse SWT. You can go through,

http://www.eclipse.org/swt/eclipse.php

in order to get started with SWT. But it’s not really necessary here and you can still go through this even if you are an absolute starter in SWT. And still you will have a fair knowledge on SWT at the end of this post. If you wanna have more of SWT, you can go through,

http://www.eclipse.org/swt/snippets/

Which should cover all what you need to know about SWT. Let’s get to the business end of life.

1. Open up your eclipse and create new project and name it with whatever name you wish (In my case it was “WidgetPro”).

2. Now again go to file menu and select import. And under general select “select archivecheck box (it will not be selected by default) and browse to point the downloaded “swt-3.x*.zip”.

3. Create a new folder inside your project’s src (source). And name it “images”. Download the following images and place them inside the folder which you just created.


N.B. Your widget will take the shape of the first image.

4. Now you can create new class, name it “GSearchWidget”. And paste the following code into it.

import java.awt.TextField;

import org.eclipse.swt.*;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.layout.*;

import java.awt.Frame;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Lonely Coder
 * @date 12/05/2009
 * https://hamzeen.wordpress.com
 * 
 * @since 3.2
 */
public class GSearchWidget {
	public static void main(String[] args) {

	final Display display = new Display();
	String currentDirectory = System.getProperty("user.dir");
	final Image image = new Image(display, "images/searchBox.png");
	final Image icon = new Image(display, "images/ico.png");
	Color green = display.getSystemColor(SWT.COLOR_DARK_GREEN);
	GC gc = new GC(image);
	// final Image image = display.getSystemImage(SWT.ICON_INFORMATION);
	final Shell shell = new Shell(display, SWT.NO_TRIM);
	shell.setText("G Search.");
	display.setAppName("G App.");
	shell.setImage(icon);
	shell.setAlpha(480);
	shell.setLocation(800, 20);
	shell.setToolTipText("Lonely Coder Labs.");
	Region region = new Region();
	final ImageData imageData = image.getImageData();

	if (imageData.alphaData != null) {
		Rectangle pixel = new Rectangle(0, 0, 1, 1);
		for (int y = 0; y < imageData.height; y++) {
			for (int x = 0; x < imageData.width; x++) {
				if (imageData.getAlpha(x, y) == 255) {
					pixel.x = imageData.x + x;
					pixel.y = imageData.y + y;
					region.add(pixel);
				}
			}
		}
	} else {
		ImageData mask = imageData.getTransparencyMask();
		Rectangle pixel = new Rectangle(0, 0, 1, 1);
		for (int y = 0; y < mask.height; y++) {
			for (int x = 0; x < mask.width; x++) {
				if (mask.getPixel(x, y) != 0) {
					pixel.x = imageData.x + x;
					pixel.y = imageData.y + y;
					region.add(pixel);
				}
			}
		}
	}
	shell.setRegion(region);

	Listener l = new Listener() {
	int startX, startY;

	public void handleEvent(Event e) {
		if (e.type == SWT.KeyDown && e.character == SWT.ESC) {
			shell.dispose();
		}
		if (e.type == SWT.MouseDown && e.button == 1) {
			startX = e.x;
			startY = e.y;
		}
		if (e.type == SWT.MouseMove && (e.stateMask & SWT.BUTTON1) != 0) {
			Point p = shell.toDisplay(e.x, e.y);
			p.x -= startX;
			p.y -= startY;
			shell.setLocation(p);
		}
		if (e.type == SWT.Paint) {
			e.gc.drawImage(image, imageData.x, imageData.y);
		}
		}
	};
		shell.addListener(SWT.KeyDown, l);
		shell.addListener(SWT.MouseDown, l);
		shell.addListener(SWT.MouseMove, l);
		shell.addListener(SWT.Paint, l);

		shell.setSize(imageData.x + imageData.width, imageData.y
				+ imageData.height);

		final Text txt = new Text(shell, SWT.WRAP | SWT.BORDER);
		txt.setBounds(20, 20, 100, 20);
		
		txt.addListener (SWT.Verify, new Listener () {
			public void handleEvent (Event e) {
				String string = e.text;
				System.out.println(e.text);
			}
		});

		
		Button go = new Button(shell, SWT.PUSH);
		go.setBackground(shell.getBackground());
		go.setText("Search");
		go.pack();
		go.setLocation(125, 18);
		go.setFocus();

	go.addListener(SWT.Selection, new Listener() {
	public void handleEvent(Event e) {
	
	//System.out.println("Clicked" + txt.getText());
	try {
	URL query = new URL("http://www.google.com/
        search?q=" + txt.getText());
	Runtime.getRuntime().exec("rundll32 url.dll,File
        ProtocolHandler " + query);
	} catch (MalformedURLException mue) {
		System.out.println("Ouch - a MalformedURLException happened.");
		mue.printStackTrace();
		System.exit(1);
	} catch(IOException io){
		System.out.println("Exception");
		//throw Exception("");
	}
	txt.setText("");
	}
			
	});

		Button b = new Button(shell, SWT.PUSH);
		b.setBackground(shell.getBackground());
		b.setText("X");
		b.pack();
		b.setLocation(190, 5);
		b.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event e) {
				shell.close();
			}
		});

		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		region.dispose();
		image.dispose();
		display.dispose();
	}
}

That’s it you have just completed the widget. Hit the run button and enjoy it. This widget is a good example of a desktop application interacting directly with a web page. To make it more interesting I have also given some transparency. With include and exclude features of SWT developing transparent applications becomes seamlessly easy. Here Firefox was opened explicitly. Since, in ma case, the default browser was found to be Internet Explorer and I wanted to view results in Firefox.

Nice to be back with a post after a while. Hope you enjoyed it, thank you.

Reassign the “standard” output stream

Today ma biggest task was to digg into redirecting/reassigning the standard output stream to a file(text file). In our case we actually wanted stop anything and everything from being sent to the standard output or the console (command prompt [in windows!!]) as usual coz later we want to check all those output against an expected output file and look for any changes.

Initially I thought it’s going to be a tough task and will take hours. But fortunately it was not the case, It was fairly simple! here I share a simple code to exploit it. I’m sorry the code is not that tidy.


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Lonely {

private File fl = null;

public Lonely() {
try {
fl = new File("stdOut.txt");
fl.canWrite();
System.setOut(new PrintStream(fl));
System.out.println("Writing..");

} catch (Exception e) {
e.printStackTrace();
}
}

private void printOut() {
System.out.println("Hi everyone");
}

public static void main(String[] args) {
Lonely l = new Lonely();
l.printOut();
System.out.println("have a nice day!");
}
}

Logging with Log4J

It’s assumed that most of the applications developed these days, keep track of their errors and failures via a log file. It turns out to be really handy when it comes to optimizing the app in a later stage.

Project that I’m working these days is also not an exception to it. From its next phase we are planning to integrate error logging. In our case we actually want to externalize all the errors and failures and warnings to a file. So that we may refer it to study the defects and bugs on it that might required to be catered in later versions of the project.

And they say never to use System.out.println to address errors. Simply because it doesn’t give you a mechanism to reference it at a later point unless you manually write it down or get screen shots then and there.

Anyway now we may look at how to get started with error logging in java with popular logging tool, Log4J by Apache Software Foundation (ASF). I’m really sorry if you are not into java probably then this is not for you.

PreRequisites
  • Java
  • An IDE (I use Eclipse so does my project)
  • Log4J (extract the archive file)

Hoping java and eclipse are installed and they are ready to go, now you can open up your eclipse IDE.

  • Create a new Project, name it whatever name you like. (In my case it was Log4JPro).
  • Add a new folder in your project’s root folder (better to name it lib just as a convention).
  • Insert the extracted lib file to the above created folder.
  • Add log4j-xxxxxx.jar file to the classpath of your project.

That’s it now you are almost there. But this actually the most important part of all. What you need to do here is setting up a small configuration file called log4j.properties. This is where you set virtually everything you need to customize with log4j goes in.

There are lots of properties that you can start configuring which will include the type of output you need, the formatting of the report, the maximum size of it (some times), and even the mode of writing (if it’s a file) whether you want to over write the previous file or to append to it and so on and so forth.

Below I’ll just give an example log4j.properties file as a starting point. This configure log4j to give a html output. And already there are more than handful of properties customized on it. And play around with it once you start working with it.

Most importantly this file should reside in the root of your project if you are using eclipse it should be placed in your src (source folder). here is an example properties file.

log4j.rootCategory=,dest3
log4j.category.TestLogging=DEBUG, dest3

log4j.appender.dest2=org.apache.log4j.RollingFileAppender
#log4j.appender.dest2.layout=org.apache.log4j.HTMLLayout
log4j.appender.dest2.Threshold=ERROR
log4j.appender.dest2.File=log4j.log
log4j.appender.dest2.Append=false
log4j.appender.dest2.MaxFileSize=100KB
log4j.appender.dest2.MaxBackupIndex=2

log4j.appender.dest3=org.apache.log4j.DailyRollingFileAppender

log4j.appender.dest3.File=LabLog.html
# Control the maximum log file size
# Rollover log file at the start of each week
log4j.appender.dest3.DatePattern=’.’yyyy-ww

log4j.appender.dest3.layout=org.apache.log4j.HTMLLayout
log4j.appender.dest3.layout.LocationInfo=true
log4j.appender.dest3.layout.Title=ISD Log

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p | %d | %F | %L | %m%n

Below given is an example code and a screen shot of the generated html file of it. Hope you enjoyed it!

/**
* @class LogApp.java
* @author Lonely Coder
* @date 09/30/2008
*/

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LogApp {

private static Logger logger = Logger.getLogger(LogApp.class);

public LogApp() {

}

public static void main(String[] args) {

long time = System.currentTimeMillis();

logger.info(“This is an Information..”);
logger.warn(“This one is just a Warning!”);

logger.log(Level.TRACE, “And a trace message using log() method.”);
long logTime = System.currentTimeMillis() – time;

logger.debug(“Time taken to log the previous messages: ” + logTime
+ ” milli secs”);

try {
String str = “log4j”;
char concat = str.charAt(6);
System.out.println(concat);
} catch (Exception e) {
logger.error(“Error in main() method:”, e);
}

}
}

log4j example log in html