Wednesday, November 4, 2009

Read data from web page

Let us look at sample code for reading data from a given url

//
// Create an url object
URL url = new URL("http://www.someUrl.com");
//
// Open connection to the url
URLConnection conn= url.openConnection();
//
// Open input stream to read
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
//
// read the content
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
//
// Do something with inputLine .
}




Wednesday, September 30, 2009

Some Google AdSense Secrets


For all who are planning to become millionaires by using Google Adsense - here some simple tips

Thursday, July 9, 2009

Using Dynamic model in Hibernate

When using Hibernate we are not forced to have POJOs alawsys for representing persistent entities. Hibernate also supports Dynamic models like Maps and DOM4J trees.

In plain english what this means is - we need to have only a mapping file (.hbm.xml) and no pojo class is required. However be careful when using this feature , as it may undergo change in the future releases.

Here we will see how to use the Hashmap for dynamic model.

Our table is
TEST_EMPLOYEE
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id | varchar(255) | NO | PRI | | |
| name | varchar(255) | YES | | NULL | |
| emailId | varchar(255) | YES | | NULL | |
+---------+--------------+------+-----+---------+-------+

Lets have a look at the curresponding mapping file -


<hibernate-mapping>
<class entity-name="com.check.Employee" table="TEST_EMPLOYEE" polymorphism="implicit" lazy="false">

<id name="id" type="string">
<column name="id" null="true">
</column></id>

<property name="name" column="name" type="string">
<property name="emailId" column="emailId" type="string">

</property></property></class>
</hibernate-mapping>

Check the use of "entity-name", this is required for dynamic model. We need not specify any class name here.

Sample code for CRUD operations.
Here HibernateHandler is a utility class used for managing sessionFactory.











01 public void createEmp(String id) {

02 Map emp = new HashMap();

03 emp.put("id", id);

04 emp.put("name", "emp_" + id);

05 emp.put("emailId", "emailId_" + id);

06

07 Session sess = HibernateHandler.getSession();

08 HibernateHandler.beginTransaction();

09 sess.save("com.check.Employee", emp);

10 HibernateHandler.commitTransaction();

11 HibernateHandler.closeSession();

12 }

13 public void readEmpUsingId(String id) {

14 Session sess = HibernateHandler.getSession();

15 Map empRead = (Map) sess.load("com.check.Employee", id);

16 System.out.println(empRead);

17 HibernateHandler.closeSession();

18 }

19 public void readUsingQuery(String mailId) {

20 String hsql = "from com.check.Employee where emailId = :emailId";

21 Session sess = HibernateHandler.getSession();

22 HibernateHandler.printStats();

23 Query q = sess.createQuery(hsql);

24 q.setString("emailId", mailId);

25 List data = q.list();

26 Map emp = (Map) data.get(0);

27 System.out.println(emp);

28 HibernateHandler.closeSession();

29 HibernateHandler.printStats();

30 }

31 public void updateEmpSimpleId(String id) {

32 Session sess = HibernateHandler.getSession();

33 HibernateHandler.beginTransaction();

34 Map empRead = (Map) sess.load("com.check.Employee", id);

35 System.out.println(empRead);

36 empRead.put("emailId", empRead.get("emailId")+"_updated");

37 System.out.println(empRead);

38 HibernateHandler.commitTransaction();

39 HibernateHandler.closeSession();

40 }

41 public void readEmpUsingObject(String id) {

42 HashMap emp = new HashMap();

43 emp.put("id", id);

44 emp.put("name", "emp_" + id);

45

46 Session sess = HibernateHandler.getSession();

47 Map empRead = (Map) sess.load("com.check.EmployeeCompo", emp);

48 System.out.println(empRead);

49 HibernateHandler.closeSession();

50 }





Here "readEmpUsingObject" is used for reading object with composit id.
Curresponding mapping file will contain -

<composite-id >
<key-property name="id" type="string" column="id" />
<key-property name="name" type="string" column="name" />
</composite-id>

Tuesday, June 30, 2009

Apache Wicket - How to run and get response from JavaScript

If you dont know what is Wicket - you are realling missing something. It is a b'ful framework from Apache which will make our life very much easier when doing web application development.
You can read more about Apache Wicket here

Here let us check how to invoke Javascript from a Wicket component and how receive/handle response. Assume the requirement is having a webpage where we will load some control using Javascript(For example - Google Earth ;) ) , and once the javascript execution is completed the page should do something.

01 public class MyPage extends WebPage {
02 /**
03 * Def constructor.
04
05 */

06 public MyPage() {
07 //
08 // Create and add a panel.
09 final JSPanel panel = new JSPanel("jsPanel");
10 panel.setOutputMarkupId(true);
11 add(panel);
12 }

Here we are creating a webpage and adding a panel to that. The panel is the place where we will
display the GoogleEarth through loading JavaScript.

But before going to the panel let us check how to get a call back from the JavaScript.
For acheiving this we will add an AjaxBehavior to the panel

01 public MyPage() {
02 ...
03 //
04 // Add an Ajax behaviour, this will be called by the javaScript
05 // when the streaming is completed.

06
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
07 protected void respond(final AjaxRequestTarget target) {
08 //
09 // Read the parameters send by JavaScript
10 Map map = ((WebRequestCycle)RequestCycle.get()).getRequest().getParameterMap();
11 Set keys = map.keySet();
12 Iterator it = keys.iterator();
13 while(it.hasNext()) {
14 String key = (String) it.next();
15 String[] value = (String[]) map.get(key);
16 }
17 }
18 };
19 panel.add(behave);
20 }


Curresponding html files are simple enough.

Now lets look at the JSPanel. Here we need to call the javascrip onLoad of the page. This is acheived through RenderHead method.


01 public class JSPanel extends Panel implements IHeaderContributor {
02 /**
03 * Def constructor.
04
05 */

06 public GEPanel(String id) {
07 super(id);
08 }

09
public void renderHead(IHeaderResponse response) {
10 //
11 // Check the behavior to get the callback URL
12 List list = getBehaviors();
13 String url = "";
14 if (list != null && list.size() > 0) {
15 AbstractDefaultAjaxBehavior beh = (AbstractDefaultAjaxBehavior) list.get(0);
16 url = beh.getCallbackUrl().toString();
17 }
18 String methodCall = "Your JS Method call";
19 response.renderOnLoadJavascript(methodCall);
20 }
21 }


Lets look at the relevant javascript now

function init(urlVal) {
url = urlVal;
//
//Create an instance of GE.
google.earth.createInstance("map3d", initCallback, failureCallback);
}

function initCallback(object) {
//
// Show GE and move camera to decired location.
ge = object;
ge.getWindow().setVisibility(true);
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
...
ge.getView().setAbstractView(lookAt);
...
//
// Make a call to the wicket callback url from here
var arg = "&key=" + value;
var wcall = wicketAjaxGet(url + arg , function() { }, function() { });
}

That is it. Let me know if you need the complete sample code for this.

Java code displayed as html here is using a tool HTML4Java, you can check it here http://www.toolbuddy.org/html4java.htm








Saturday, June 20, 2009

Capturing Image From Google Earth


Please note that images from Google Earth may be copy right protected, so you should carefully check before using such images.

Easiest way is - if you have a stand alone Google Earth application, start it and move to the decired location. This can be done through opening a KML file. Then use a screen capture program to take the screen shot (Or just use PrintScrn button)

What if there is no stand alone application available? Google static maps comes to the rescue.
Just load the url in a browser it will load the curresponding image.

Let us see how to do this from Java .

Use a url string.

String url = "http://maps.google.com/staticmap?center=%LAT%,%LON%&zoom=%ZOOM%&size=512x512&maptype=satellite&key=%KEY%";
Replace the place holders
%LAT% - Latitude
%LON% - Longitude
%ZOOM% - Zoom level
%KEY% - Google map key

//
// Load the image from url.
url = new URL(uri);
BufferedImage bi = ImageIO.read(url);
ImageIO.write(bi,"PNG",new File("image.PNG"));