Java Connector to SugarCRM Webservices

This would a small post will less explanation and more of code snippets (Too  busy to write description and code has proper comments).

Here is my effort to minimize research work in getting started with sugar CRM webservice invocation in java

Original code was taken from https:/ /github.com /amusarra/SugarCRMJavaSOAPClient  and added more functions to it

/**
 *
 */
package com.northalley.sugarcrm;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.ServiceFactory;

import org.apache.axis.AxisFault;

import com.sugarcrm.www.sugarcrm.Entry_value;
import com.sugarcrm.www.sugarcrm.Field;
import com.sugarcrm.www.sugarcrm.Get_entry_list_result_version2;
import com.sugarcrm.www.sugarcrm.Get_entry_result_version2;
import com.sugarcrm.www.sugarcrm.Link_field;
import com.sugarcrm.www.sugarcrm.Link_name_to_fields_array;
import com.sugarcrm.www.sugarcrm.Module_list;
import com.sugarcrm.www.sugarcrm.Name_value;
import com.sugarcrm.www.sugarcrm.New_module_fields;
import com.sugarcrm.www.sugarcrm.New_set_entry_result;
import com.sugarcrm.www.sugarcrm.SugarsoapBindingStub;
import com.sugarcrm.www.sugarcrm.SugarsoapLocator;
import com.sugarcrm.www.sugarcrm.User_auth;

/**
 * This implements basic methods which are used commonly
 *
 * @author ashwin kumar
 */
public class SugarCRMSoapDemoClient {
	private static final String END_POINT_URL = "http://localhost/SugarCE/service/v2/soap.php?wsdl";
	private static final String USER_NAME = "admin";
	private static final String USER_PASSWORD = "sugarcrm";
	private static final String APPLICATION_NAME = Class.class.getName();
	private static final Integer TIMEOUT = 6000;

	/**
	 * Main Program
	 *
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String sessionID = null;

		try {
			// Create a URL end point for the client
			URL wsdlUrl = null;
			if (END_POINT_URL.isEmpty()) {
				wsdlUrl = new URL(new SugarsoapLocator()
						.getsugarsoapPortAddress()
						+ "?wsdl");
			} else {
				wsdlUrl = new URL(END_POINT_URL);
			}

			System.out.println("URL endpoint created successfully!");

			// Create Service for test configuration
			ServiceFactory serviceFactory = ServiceFactory.newInstance();
			Service service = serviceFactory.createService(wsdlUrl,
					new SugarsoapLocator().getServiceName());

			System.out.println("Service created successfully");
			System.out.println("Service Name:"
					+ service.getServiceName().toString());
			System.out.println("Service WSDL:"
					+ service.getWSDLDocumentLocation().toString());

			// Trying to create a stub
			SugarsoapBindingStub binding = new SugarsoapBindingStub(wsdlUrl,
					service);
			binding.setTimeout(TIMEOUT);
			System.out.println("Stub created successfully!");

			/**
			 * Try to login on SugarCRM
			 *
			 * 1) Prepare a MD5 hash password 2) Prepare a User Auth object 3)
			 * Execute login
			 */

			// 1. Prepare a MD5 hash password
			MessageDigest messageDiget = MessageDigest.getInstance("MD5");
			messageDiget.update(USER_PASSWORD.getBytes());

			// 2. Prepare a User Auth object
			User_auth userAuthInfo = new User_auth();
			userAuthInfo.setUser_name(USER_NAME);
			userAuthInfo.setPassword((new BigInteger(1, messageDiget.digest()))
					.toString(16));

			try {
				// 3. Execute login
				Entry_value loginResult = binding.login(userAuthInfo,
						APPLICATION_NAME, null);
				System.out.println("Login Successfully for " + USER_NAME);
				System.out.println("Your session Id: " + loginResult.getId());
				sessionID = loginResult.getId();
			} catch (RemoteException ex) {
				System.out.println("Login failed. Message: " + ex.getMessage());
				ex.printStackTrace();
			}
			// binding.
			// binding.get_available_modules(session);
			// retreiveEntriesByModule(sessionID, binding, "Accounts",new
			// String[]{"name","description"},0,10);
			retreiveEntriesByModule(sessionID, binding, "Leads", new String[] {
					"name", "description", "account_name", "campaign_name",
					"salutation", "first_name", "last_name", "full_name",
					"title", "department", "email1", "email2" }, 0, 10);
			retreiveEntriesByModule(sessionID, binding, "Campaigns",
					new String[] { "name", "description", "assigned_user_name",
							"status", "campaign_type", "expected_cost" }, 0, 10);
			// retreiveModuleFields(sessionID, binding);
			// retreiveModules(sessionID, binding);
			// createAndRetreiveContact(sessionID, binding);

			/**
			 * Logout
			 */
			try {
				binding.logout(sessionID);
				System.out.println("Logout Successfully for " + USER_NAME);
				sessionID = null;
			} catch (RemoteException ex) {
				System.out.println("Login failed. Message: " + ex.getMessage());
				ex.printStackTrace();
			}

		} catch (MalformedURLException ex) {
			System.out.println("URL endpoing creation failed. Message: "
					+ ex.getMessage());
			ex.printStackTrace();
		} catch (ServiceException ex) {
			System.out.println("Service creation failed. Message: "
					+ ex.getMessage());
			ex.printStackTrace();
		} catch (AxisFault ex) {
			System.out.println("AxisFault. Message: " + ex.getMessage());
			ex.printStackTrace();
		}
	}

	/**
	 * Sample to show how to do creation operation using webservice
	 *
	 * @param sessionID
	 * @param binding
	 */
	private static void createAndRetreiveContact(String sessionID,
			SugarsoapBindingStub binding) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */
		HashMap<String, String> nameValueMap = new HashMap<String, String>();
		nameValueMap.put("first_name", "Suresh");
		nameValueMap.put("last_name", "Paladugu");
		nameValueMap.put("title", "IT Senior Consultant");
		nameValueMap.put("description", "Test Client SOAP Java");
		nameValueMap.put("email1", "suresh.paladugu@gmail.com");

		// Creating a new Name_value array and adding each map entry as 'name'
		// and 'value'
		Name_value nameValueListSetEntry[] = new Name_value[nameValueMap.size()];
		int i = 0;
		for (Entry<String, String> entry : nameValueMap.entrySet()) {
			Name_value nameValue = new Name_value();
			nameValue.setName(entry.getKey());
			nameValue.setValue(entry.getValue());
			nameValueListSetEntry[i] = nameValue;
			i++;
		}

		// Trying to set a new entry
		New_set_entry_result setEntryResponse = null;
		try {
			setEntryResponse = binding.set_entry(sessionID, "Contacts",
					nameValueListSetEntry);
		} catch (RemoteException e) {
			System.out.println("Set entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Set entry was successful! Contacts Id: "
				+ setEntryResponse.getId());

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;

		// Trying to get entry
		try {
			getEntryResponse = binding.get_entry(sessionID, "Contacts",
					setEntryResponse.getId(), select_fields,
					link_name_to_fields_array);
		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Get entry was successful! Response: ");

		// Getting the fields for entry we got.
		Entry_value[] entryList = getEntryResponse.getEntry_list();
		for (int k = 0; k < entryList.length; k++) {
			Entry_value entry = entryList[k];
			Name_value[] entryNameValueList = entry.getName_value_list();
			for (int j = 0; j < entryNameValueList.length; j++) {
				Name_value entryNameValue = entryNameValueList[j];
				// Outputting only non empty fields
				if (!entryNameValue.getValue().isEmpty()) {
					System.out.println("Attribute Name: '"
							+ entryNameValue.getName() + "' Attribute Value: '"
							+ entryNameValue.getValue() + "'");
				}
			}
		}
	}

	/**
	 *
	 * TO get list of values /rows for a given modules based on selection
	 * criteria
	 *
	 * @param sessionID
	 * @param binding
	 * @param moduleName
	 *            TODO
	 * @param select_fields
	 * @param l
	 * @param offset
	 */
	private static void retreiveEntriesByModule(String sessionID,
			SugarsoapBindingStub binding, String moduleName,
			String[] select_fields, int offset, int rowCount) {
		Link_name_to_fields_array[] link_name_to_fields_array = null;

		Get_entry_result_version2 getEntryResponse = null;
		Get_entry_list_result_version2 entryListResultVersion2 = null;

		// Trying to get entry
		try {
			/*
			 * getEntryResponse = binding.get_entry(sessionID,moduleName, null,
			 * select_fields, link_name_to_fields_array);
			 */
			entryListResultVersion2 = binding.get_entry_list(sessionID,
					moduleName, "", "", offset, select_fields,
					link_name_to_fields_array, rowCount, 0);
			// getEntryResponse = binding.get_entries(sessionID, moduleName,
			// null, new String[]{"name","description"},
			// link_name_to_fields_array);

		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Get entry was successful! Response: ");

		// Getting the fields for entry we got.
		Entry_value[] entryList = entryListResultVersion2.getEntry_list();
		for (int k = 0; k < entryList.length; k++) {
			Entry_value entry = entryList[k];
			Name_value[] entryNameValueList = entry.getName_value_list();
			System.out.println();
			for (int j = 0; j < entryNameValueList.length; j++) {
				Name_value entryNameValue = entryNameValueList[j];
				// Outputting only non empty fields
				if (!entryNameValue.getValue().isEmpty()) {
					System.out.print(entryNameValue.getName() + ":"
							+ entryNameValue.getValue() + "    ;   ");
				}
			}
		}
	}

	/**
	 *
	 * To list out all fields of a given module
	 *
	 * @param sessionID
	 * @param binding
	 * @param moduleName
	 */
	private static void retreiveModuleFields(String sessionID,
			SugarsoapBindingStub binding, String moduleName) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;
		New_module_fields moduleFields = null;
		// Trying to get entry
		try {
			moduleFields = binding.get_module_fields(sessionID, moduleName,
					select_fields);
		} catch (RemoteException e) {
			// System.out.println("Get entry failed. Message: " +
			// e.getMessage());
			// e.printStackTrace();
		}
		// System.out.println("Get entry was successful! Response: ");

		if (moduleFields != null) {
			for (Field field : moduleFields.getModule_fields()) {
				System.out.print(field.getName() + ",");
			}

			System.out.println("--Link Fields");
			/**
			 * Now get Link Fields
			 */

			for (Link_field linkField : moduleFields.getLink_fields()) {
				System.out.print("[" + linkField.getName() + " : "
						+ linkField.getBean_name() + " : "
						+ linkField.getRelationship() + "],");
			}
		}

	}

	/**
	 * To list out all modules aavailable to given user
	 *
	 * @param sessionID
	 * @param binding
	 */
	private static void retreiveModules(String sessionID,
			SugarsoapBindingStub binding) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;
		Module_list moduleList = null;
		// Trying to get entry
		try {
			moduleList = binding.get_available_modules(sessionID);
		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		// System.out.println("Get entry was successful! Response: ");

		for (String moduleName : moduleList.getModules()) {
			System.out.println("\n" + moduleName + "{");
			retreiveModuleFields(sessionID, binding, moduleName);
			System.out.println("}");
		}

	}

}

Project code has been checked into

https://linkwithweb.googlecode.com/svn/trunk/CRM/SugarCRM/JavaSOAPClient/SugarCRMClient

List of all fields by module is also located at

https://linkwithweb.googlecode.com/svn/trunk/CRM/SugarCRM/ModuleWiseFieldsAndLinkedFieldsList.txt

Same can also be extracted by running above program

Njoy working with SugarCRM..

Fell free to contact me if any questions

jsoup HTMLParser and Parsing Dzone Links using CSS Selectors in Java

I was working on a task to parse some of Amazon web-services. There are lots of ways to parse it Using DOM/SAX/Stax .  All of them require some amount of coding. I wanted a quick fix and i finally landed on to JSoup an opensource HTML Parser ( Other html parser i like is HTMLParser) . In this article i’m going to explain how i’m going to parse DZone HTML links in java.

I’ll be retreiving description’s of all links in Dzone using the code

Note: This is not the best way to read links from Dzone ( You can use rss feed’s instead).  This tutorial is to take you through css selectors for Java

All DZone pagination queries looks like this

http://www.dzone.com/links/?type=html&p=2

i used an opensource java library to parse this and extract link text description (jsoup)

Here is sample tags we have in dzone response

<a name="link-613399">
</a>

<div class="linkblock frontpage " id="link-613399">
	<div id="thumb_613399" class="thumb">
		<a onmouseup="track(this, 'twitter4j_oauth_on_android', ''); "
			href="http://www.xoriant.com/blog/mobile-application-development/twitter4j-oauth-on-android.html">
			<img width="120" height="90"
				src="http://cdn.dzone.com/links/images/thumbs/120x90/613399-1307624607000.jpg"
				class="thumbnail" alt="Link 613399 thumbnail"
				onmouseover="return OLgetAJAX('/links/themes/reader/jsps/nodecoration/thumb-load.jsp?linkId=613399', OLcmdExT1,
 300, 'bigThumbBody');"
				onmouseout="OLclearAJAX(); nd(100);" />
		</a>
	</div>
	<div id="hidden_thumb_613399">

	</div>
	<div class="tools">
	</div>
	<div class="details">
		<div class="vwidget" id="vwidget-613399">
			<a id="upcount-613399" href="#" class="upcount"
				onclick="showLoginDialog(613399, null); return false">7</a>

			<a id="downcount-613399" href="#"
				onclick="showLoginDialog(613399, null); return false;" class="downcount">0</a>
		</div>
		<h3>
			<a onmouseup="track(this, 'twitter4j_oauth_on_android', ''); "
				href="http://www.xoriant.com/blog/mobile-application-development/twitter4j-oauth-on-android.html"
				rel="bookmark"> Twitter4j OAuth on Android</a>
		</h3>
		<p class="voteblock">
			<a href="/links/users/profile/811805.html">
				<img width="24" height="24"
					src="http://cdn.dzone.com/links/images/std/avatars/default_24.gif"
					class="avatar" alt="User 811805 avatar" />
			</a>
		</p>
		<p class="fineprint byline">
			<a href="/links/users/profile/811805.html">RituR</a>
			via
			<a href="/links/search.html?query=domain%3Axoriant.com">xoriant.com</a>
		</p>
		<p class="fineprint byline">
			<b>Promoted: </b>
			Jun 08 / 17:27. Views:
			520, Clicks: 266
		</p>
		<p class="description">
			OAuth is an open protocol
			which allows the users to share their private information and assets
			like photos, videos etc. with another site...&nbsp;
			<a href='/links/twitter4j_oauth_on_android.html'>more&nbsp;&raquo;
			</a>
		</p>
		<p class="fineprint stats">
			<a
				href="http://twitter.com/home?status=RT+%40DZone+%22Twitter4j+OAuth+on+Android%22+http%3A%2F%2Fdzone.com%2FTBxR"
				class="twitter">Tweet</a>
			<a href="/links/twitter4j_oauth_on_android.html" class="comment">0
				Comments</a>
			<span class="linkUnsaved" id="save-link-613399"
				onclick="showLoginDialog(613399); return false;">Save</span>
			<span class="linkUnshared" id="share-link-613399"
				onclick="showLoginDialog(613399); return false;">Share</span>
			Tags:
			<a href="/links/tag/mobile.html" class="tags" rel="tag">mobile</a>
			,
			<a href="/links/tag/standards.html" class="tags" rel="tag">standards</a>
		</p>

	</div>
</div>

 

To get description we have to get data from element “P” with class “description” which is actually present in DIV with class “details” Here is how we can do that in java

 

/**
 * 
 */
package com.linkwithweb.parser;

import java.io.File;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/****************************************************************
 * Description
 * jsoup elements support a CSS (or jquery) like selector syntax to find matching elements, that allows very powerful and robust queries.
 * 
 * The select method is available in a Document, Element, or in Elements. It is contextual, so you can filter by selecting from a specific element, or
 * by chaining select calls.
 * 
 * Select returns a list of Elements (as Elements), which provides a range of methods to extract and manipulate the results.
 * 
 * Selector overview
 * tagname: find elements by tag, e.g. a
 * ns|tag: find elements by tag in a namespace, e.g. fb|name finds <fb:name> elements
 * #id: find elements by ID, e.g. #logo
 * .class: find elements by class name, e.g. .masthead
 * [attribute]: elements with attribute, e.g. [href]
 * [^attr]: elements with an attribute name prefix, e.g. [^data-] finds elements with HTML5 dataset attributes
 * [attr=value]: elements with attribute value, e.g. [width=500]
 * [attr^=value], [attr$=value], [attr*=value]: elements with attributes that start with, end with, or contain the value, e.g. [href*=/path/]
 * [attr~=regex]: elements with attribute values that match the regular expression; e.g. img[src~=(?i)\.(png|jpe?g)]
 * : all elements, e.g. *
 * Selector combinations
 * el#id: elements with ID, e.g. div#logo
 * el.class: elements with class, e.g. div.masthead
 * el[attr]: elements with attribute, e.g. a[href]
 * Any combination, e.g. a[href].highlight
 * ancestor child: child elements that descend from ancestor, e.g. .body p finds p elements anywhere under a block with class "body"
 * parent > child: child elements that descend directly from parent, e.g. div.content > p finds p elements; and body > * finds the direct children of
 * the body tag
 * siblingA + siblingB: finds sibling B element immediately preceded by sibling A, e.g. div.head + div
 * siblingA ~ siblingX: finds sibling X element preceded by sibling A, e.g. h1 ~ p
 * el, el, el: group multiple selectors, find unique elements that match any of the selectors; e.g. div.masthead, div.logo
 * Pseudo selectors
 * :lt(n): find elements whose sibling index (i.e. its position in the DOM tree relative to its parent) is less than n; e.g. td:lt(3)
 * :gt(n): find elements whose sibling index is greater than n; e.g. div p:gt(2)
 * :eq(n): find elements whose sibling index is equal to n; e.g. form input:eq(1)
 * :has(seletor): find elements that contain elements matching the selector; e.g. div:has(p)
 * :not(selector): find elements that do not match the selector; e.g. div:not(.logo)
 * :contains(text): find elements that contain the given text. The search is case-insensitive; e.g. p:contains(jsoup)
 * :containsOwn(text): find elements that directly contain the given text
 * :matches(regex): find elements whose text matches the specified regular expression; e.g. div:matches((?i)login)
 * :matchesOwn(regex): find elements whose own text matches the specified regular expression
 * Note that the above indexed pseudo-selectors are 0-based, that is, the first element is at index 0, the second at 1, etc
 * See the Selector API reference for the full supported list and details.
 * 
 * @author Ashwin Kumar
 * 
 */
public class HTMLParser {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			File input = new File("input/dZoneLinks.xml");
			Document doc = Jsoup.parse(input, "UTF-8",
					"http://www.dzone.com/links/?type=html&p=2");

			Elements descriptions = doc.select("div.details > p.description"); // get all description elements in this HTML file
			/*
			 * Elements pngs = doc.select("img[src$=.png]");
			 * // img with src ending .png
			 * 
			 * Element masthead = doc.select("div.masthead").first();
			 */
			// div with

			// Elements resultLinks = doc.select("h3.r > a"); // direct a after h3
			/**
			 * Iterate over all descriptions and display them
			 */
			for (Element element : descriptions) {
				System.out.println(element.ownText());
				System.out.println("--------------");
			}

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

}

Mavenized code has been checked in to svn at following location

http://code.google.com/p/linkwithweb/source/browse/trunk/Utilities/HTMLParser

Njoy parsing anything easily using jsoup

 

Javascript RSA Encryption and Java Decryption

Many of us have been working with Javascript since long time but when ever i ask people how to send encrypted data, the only answer is to use SSL . But this article shows how to send encrypted data even when we don’t have ssl enabled. This can come in to handy in many scenario’s

I used jCryption and Javascript Library to encrypt in Javascript and BouncyCastle Library on Javabackend to decypt,

Here is the flow in the example

  1. First Generate  RSA keys on server end ( Store in session).
  2. Send public key to client (javascript)
  3. Store keys in javascript variable
  4. In All subsequent requests use this key to encrypt data and send to server
  5. Use keys stored in session  to decrypt data and send response to server

Keys generation utility class in Java

package com.linkwithweb.encryption;

import java.io.IOException;
import java.security.KeyPair;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EncryptionServlet
 */
public class EncryptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public EncryptionServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("generateKeypair") != null) {

			JCryptionUtil jCryptionUtil = new JCryptionUtil();

			KeyPair keys = null;
			if (request.getSession().getAttribute("keys") == null) {
				keys = jCryptionUtil.generateKeypair(512);
				request.getSession().setAttribute("keys", keys);
			}

			StringBuffer output = new StringBuffer();

			String e = JCryptionUtil.getPublicKeyExponent(keys);
			String n = JCryptionUtil.getPublicKeyModulus(keys);
			String md = String.valueOf(JCryptionUtil.getMaxDigits(512));

			output.append("{\"e\":\"");
			output.append(e);
			output.append("\",\"n\":\"");
			output.append(n);
			output.append("\",\"maxdigits\":\"");
			output.append(md);
			output.append("\"}");

			output.toString();
			response.getOutputStream().print(
					output.toString().replaceAll("\r", "").replaceAll("\n", "")
							.trim());
		} else {
			response.getOutputStream().print(String.valueOf(false));
		}
	}

}

All client code is there in index.jsp and framework.js

Javascript Function that gets keys from server and stores in javascript variable

/**
 * Get Security keys from server so that we can encrypt request in future
 */
function getKeys() {
	$.jCryption.getKeys("EncryptionServlet?generateKeypair=true", function(
			receivedKeys) {
		keys = receivedKeys;
	});
}

On login button clicked here is how you encrypt and send request to server

/**
 * Called on Login Button clicked
 */
function onLoginButtonClicked() {
	var user = $("#login_user").val();
	var password = $("#login_password").val();
	$.jCryption.encrypt(user, keys, function(encrypted) {
		encryptedUser = encrypted;
		$.jCryption.encrypt(password, keys, function(encryptedPasswd) {
			encryptedPassword = encryptedPasswd;
			/**
			 * As both userName and password are encrypted now Submit login
			 */
			submitLoginRequest();
		});
	});
}

/**
 * Submit Login request
 */
function submitLoginRequest() {
	sendAjaxRequest("LoginServlet", {
		username : encryptedUser,
		password : encryptedPassword
	}, function(data) {
		if (data.length > 0) {
			$("#login_status").empty();
			$("#login_status").append(data);
		}
	});
}

And below is svn URL to download sample source code  https://linkwithweb.googlecode.com/svn/trunk/Utilities/jCryptionTutorial

Next version of tutorial will be from flex to java. Njoy reading and playing with Encryption code

OAuth using Scribe with Yahoo API

This is Sequence of my previous post but now with yahoo

I have downloaded Scribe example source code to get Authenticated with yahoo. But the default example was not working. After doing some 4 hours of research i found out that the author had forgot to send a request to yahoo api’s to get GUID which is inturn used to get user profile data. I have modified code to fix that and here is the working code

package org.scribe.examples;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.YahooApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class YahooExample {
	private static String PROTECTED_RESOURCE_URL = "http://social.yahooapis.com/v1/user/GUID/profile?format=json";

	public static void main(String[] args) {
		OAuthService service = new ServiceBuilder()
				.provider(YahooApi.class)
				.apiKey("dj0yJmk9TXZDWVpNVVdGaVFmJmQ9WVdrOWMweHZXbkZLTkhVbWNHbzlNVEl5TWprd05qUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMw--")
				.apiSecret("262be559f92a2be20c4c039419018f2b48cdfce9").build();
		Scanner in = new Scanner(System.in);

		System.out.println("=== Yahoo's OAuth Workflow ===");
		System.out.println();

		// Obtain the Request Token
		System.out.println("Fetching the Request Token...");
		Token requestToken = service.getRequestToken();
		System.out.println("Got the Request Token!");
		System.out.println();

		System.out.println("Now go and authorize Scribe here:");
		System.out.println(service.getAuthorizationUrl(requestToken));
		System.out.println("And paste the verifier here");
		System.out.print(">>");
		Verifier verifier = new Verifier(in.nextLine());
		System.out.println();

		// Trade the Request Token and Verfier for the Access Token
		System.out.println("Trading the Request Token for an Access Token...");
		Token accessToken = service.getAccessToken(requestToken, verifier);
		System.out.println("Got the Access Token!");
		System.out.println("(if your curious it looks like this: "
				+ accessToken + " )");
		System.out.println();

		// Now let's go and ask for a protected resource!
		System.out.println("Now we're going to access a protected resource...");
		OAuthRequest request1 = new OAuthRequest(Verb.GET,
				"http://social.yahooapis.com/v1/me/guid?format=xml");
		service.signRequest(accessToken, request1);
		Response response1 = request1.send();
		System.out.println("Got it! Lets see what we found...");
		System.out.println();
		System.out.println(response1.getCode());
		System.out.println(response1.getBody());

		PROTECTED_RESOURCE_URL = PROTECTED_RESOURCE_URL.replaceAll("GUID",
				parseYahooGUIDResposne(response1.getBody()));
		System.out.println("PROTECTED_RESOURCE_URL    "
				+ PROTECTED_RESOURCE_URL);
		// Now let's go and ask for a protected resource!
		System.out.println("Now we're going to access a protected resource...");
		OAuthRequest request = new OAuthRequest(Verb.GET,
				PROTECTED_RESOURCE_URL);
		service.signRequest(accessToken, request);
		request.addHeader("realm", "yahooapis.com");
		Response response = request.send();
		System.out.println("Got it! Lets see what we found...");
		System.out.println();
		System.out.println(response.getCode());
		System.out.println(response.getBody());

		System.out.println();
		System.out
				.println("Thats it man! Go and build something awesome with Scribe! :)");

	}

	/**
	 *
	 */
	private static String parseYahooGUIDResposne(String data) {
		// get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			// Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			// parse using builder to get DOM representation of the XML file
			Document dom = db.parse(new ByteArrayInputStream(data.getBytes()));

			Element rootElement = dom.getDocumentElement();
			return getGUID(rootElement);

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (SAXException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return null;
	}

	/**
	 * I take an employee element and read the values in, create
	 * an Employee object and return it
	 */
	private static String getGUID(Element guidEl) {

		// for each <employee> element get text or int values of
		// name ,id, age and name
		String name = getTextValue(guidEl, "value");
		// System.out.println("Name:   "+name);

		return name;
	}

	/**
	 * I take a xml element and the tag name, look for the tag and get
	 * the text content
	 * i.e for <?xml version="1.0" encoding="utf-8"?><guid xmlns="http://social.yahooapis.com/v1/schema.rng"
	 * xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
	 * yahoo:uri="http://social.yahooapis.com/v1/me/guid"><value>4QWOBUCQHETEL34LSRUKJEV5W4</value></guid> xml snippet if
	 * the Element points to employee node and tagName is 'name' I will return John
	 */
	private static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}

	/**
	 * Calls getTextValue and returns a int value
	 */
	private static int getIntValue(Element ele, String tagName) {
		// in production application you would catch the exception
		return Integer.parseInt(getTextValue(ele, tagName));
	}

}

In Next post i would provide a sample webapp where OAuth is used to authenticate with Yahoo/Google/Facebook. Njoy networking

Converting Documents with openoffice to Differrent Formats in Java

There is lots of requirements in most commercial projects to convert documents in various formats . For example

HTML —–> Pdf
Doc —–> Pdf
PPT —–> Images

etc

Openoffice has created a very versatile office software which is opensource and can be used in conversion of documents from one format to another

Here is one such example that Converts HTML to PDF. I used JodConverter which is one of the best libraries around which wraps complex openoffice interations with simple object oriented methods

/**
 * 
 */
package com.linkwithweb.converter;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.ConnectException;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFamily;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/**
 * Prerequisites
 * %OPENOFFICE_HOME%/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
 * 
 * @author Ashwin Kumar
 * 
 */
public class OpenOfficeConverter {
	// connect to an OpenOffice.org instance running on port 8100
	private OpenOfficeConnection connection = null;

	/**
	 * @param oHTMLText
	 * @param oOutputStream
	 */
	public void convertFromHTMLToPDF(String oHTMLText,
			OutputStream oOutputStream) {
		try {
			DocumentFormat inputDocumentFormat = new DocumentFormat("HTML",
					DocumentFamily.TEXT, "text/html", "html");
			inputDocumentFormat.setExportFilter(DocumentFamily.TEXT,
					"HTML 	(StarWriter)");
			DocumentFormat outputDocumentFormat = new DocumentFormat(
					"Portable	Document Format", DocumentFamily.TEXT,
					"application/pdf", "pdf");
			outputDocumentFormat.setExportFilter(DocumentFamily.TEXT,
					"writer_pdf_Export");
			DocumentConverter oDocumentConverter = new OpenOfficeDocumentConverter(
					connection);
			oDocumentConverter.convert(
					new ByteArrayInputStream(oHTMLText.getBytes()),
					inputDocumentFormat, oOutputStream, outputDocumentFormat);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 
	 */
	public void openConnection() {
		try {
			if (connection == null || !connection.isConnected())
				connection = new SocketOpenOfficeConnection(8100);
			connection.connect();
		} catch (ConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public void openConnection(String host, int port) {
		try {
			if (connection == null || !connection.isConnected())
				connection = new SocketOpenOfficeConnection(host, port);
			connection.connect();
		} catch (ConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public void closeConnection() {
		// close the connection
		try {
			if (connection != null && connection.isConnected())
				connection.disconnect();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

Now to Use above Method Here is sample Code

/**
 * 
 */
package com.linkwithweb.converter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Ashwin Kumar
 * 
 */
public class HTMLToPDFConverter {

	public static void main(String[] args) {

		String strHindiHTML = "Hello hi tehrere<h1>heading</h1>";
		OpenOfficeConverter oOpenOfficeConverter = new OpenOfficeConverter();
		oOpenOfficeConverter.openConnection();
		OutputStream out = null;
		try {
			out = new FileOutputStream("test.pdf");

			oOpenOfficeConverter.convertFromHTMLToPDF(strHindiHTML, out);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Throwable th) {
			// TODO Auto-generated catch block
			th.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		oOpenOfficeConverter.closeConnection();
		/*
		 * ByteArrayOutputStream oByteArrayOutputStream = new ByteArrayOutputStream();
		 * 
		 * ByteArrayInputStream oByteArrayInputStream = new ByteArrayInputStream(
		 * oByteArrayOutputStream.toByteArray());
		 */
	}

}

Below is sample Maven Configuration to Build the project


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.linkwithweb.documents</groupId>
	<artifactId>DocumentConverter</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>DocumentConverter</name>
	<description>DocumentConverter</description>
	<dependencies>
		<dependency>
			<groupId>com.artofsolving</groupId>
			<artifactId>jodconverter</artifactId>
			<version>2.2.1</version>
		</dependency>
		
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.1</version>
		</dependency>		

	</dependencies>

	<build>
		<finalName>DocumentConverter</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>com.artofsolving</groupId>
				<artifactId>jodconverter-maven-plugin</artifactId>
				<version>2.2.1</version>
				<configuration>
					<sourceDirectory>${basedir}/src/site/resources</sourceDirectory>
					<outputDirectory>${project.reporting.outputDirectory}</outputDirectory>
					<include>**/*.odt</include>
					<outputFormat>pdf</outputFormat>
				</configuration>
				<executions>
					<execution>
						<id>convert </id>
						<phase>site</phase>
						<goals>
							<goal>convert</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<properties>
		<org.easymock.version>2.3</org.easymock.version>
		<org.springframework.version>2.5.6</org.springframework.version>
		<commons.lang.version>2.1</commons.lang.version>
		<log4j.version>1.2.14</log4j.version>
		<org.freemarker.version>2.3.15</org.freemarker.version>
		<manifest.file>src/main/resources/META-INF/MANIFEST.MF</manifest.file>
	</properties>
</project>

Attached is sample Project. Rename it to .rar file

DocumentConverter(Rename Extension to .rar)

Building Tree From SQL Database with Java5 Generics

There are multiple ways of storing Tree structure in database. The most prominent and not so efficient way is

key parentkey
1 0
2 1
3 2
4 3

Lots of people generally have requirement where in they have to build tree given any node in the whole chain. The above tree as you is a multidimentional tree as in there can be 0-n parents and 0-n children for any given node. If we have build it in C or C++ we would have taken an approach of Multi-Linked List.

It Has become much simpler in java with advent of Generic in Java 5. I ‘m going to show you a very generic version of buildign tree which can be used any where

Basic element of any tree is the Node


import java.util.ArrayList;
import java.util.List;

/**
 * Represents a node of the Tree class. The Node is also a container, and
 * can be thought of as instrumentation to determine the location of the type T
 * in the Tree.
 * 
 * @author kumara
 */
public class Node {

	public T data;
	public List<Node> children;
	public List<Node> parents;

	/**
	 * Default ctor.
	 */
	public Node() {
		super();
	}

	/**
	 * Convenience ctor to create a Node with an instance of T.
	 * 
	 * @param data
	 *            an instance of T.
	 */
	public Node(T data) {
		this();
		setData(data);
	}

	/**
	 * Return the children of Node. The Tree is represented by a single
	 * root Node whose children are represented by a List<Node>. Each of
	 * these Node elements in the List can have children. The getChildren()
	 * method will return the children of a Node.
	 * 
	 * @return the children of Node
	 */
	public List<Node> getChildren() {
		if (this.children == null) {
			return new ArrayList<Node>();
		}
		return this.children;
	}

	/**
	 * Sets the children of a Node object. See docs for getChildren() for
	 * more information.
	 * 
	 * @param children
	 *            the List<Node> to set.
	 */
	public void setChildren(List<Node> children) {
		this.children = children;
	}

	/**
	 * Returns the number of immediate children of this Node.
	 * 
	 * @return the number of immediate children.
	 */
	public int getNumberOfChildren() {
		if (children == null) {
			return 0;
		}
		return children.size();
	}

	/**
	 * Adds a child to the list of children for this Node. The addition of
	 * the first child will create a new List<Node>.
	 * 
	 * @param child
	 *            a Node object to set.
	 */
	public void addChild(Node child) {
		if (children == null) {
			children = new ArrayList<Node>();
		}
		children.add(child);
	}

	/**
	 * Inserts a Node at the specified position in the child list. Will *
	 * throw an ArrayIndexOutOfBoundsException if the index does not exist.
	 * 
	 * @param index
	 *            the position to insert at.
	 * @param child
	 *            the Node object to insert.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void insertChildAt(int index, Node child)
			throws IndexOutOfBoundsException {
		if (index == getNumberOfChildren()) {
			// this is really an append
			addChild(child);
			return;
		} else {
			children.get(index); // just to throw the exception, and stop here
			children.add(index, child);
		}
	}

	/**
	 * Remove the Node element at index index of the List<Node>.
	 * 
	 * @param index
	 *            the index of the element to delete.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void removeChildAt(int index) throws IndexOutOfBoundsException {
		children.remove(index);
	}
	
	
	
	/**
	 * Return the parents of Node. The Tree is represented by a single
	 * root Node whose parents are represented by a List<Node>. Each of
	 * these Node elements in the List can have parents. The getparent()
	 * method will return the parents of a Node.
	 * 
	 * @return the children of Node
	 */
	public List<Node> getParents() {
		if (this.parents == null) {
			return new ArrayList<Node>();
		}
		return this.parents;
	}

	/**
	 * Sets the parents of a Node object. See docs for getparent() for
	 * more information.
	 * 
	 * @param parents
	 *            the List<Node> to set.
	 */
	public void setParents(List<Node> parent) {
		this.parents = parent;
	}

	/**
	 * Returns the number of immediate parents of this Node.
	 * 
	 * @return the number of immediate parents.
	 */
	public int getNumberOfParents() {
		if (parents == null) {
			return 0;
		}
		return parents.size();
	}

	/**
	 * Adds a child to the list of children for this Node. The addition of
	 * the first child will create a new List<Node>.
	 * 
	 * @param child
	 *            a Node object to set.
	 */
	public void addParent(Node parent) {
		if (parents == null) {
			parents = new ArrayList<Node>();
		}
		parents.add(parent);
	}

	/**
	 * Inserts a Node at the specified position in the child list. Will *
	 * throw an ArrayIndexOutOfBoundsException if the index does not exist.
	 * 
	 * @param index
	 *            the position to insert at.
	 * @param child
	 *            the Node object to insert.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void insertParentAt(int index, Node parent)
			throws IndexOutOfBoundsException {
		if (index == getNumberOfChildren()) {
			// this is really an append
			addParent(parent);
			return;
		} else {
			parents.get(index); // just to throw the exception, and stop here
			parents.add(index, parent);
		}
	}

	/**
	 * Remove the Node element at index index of the List<Node>.
	 * 
	 * @param index
	 *            the index of the element to delete.
	 * @throws IndexOutOfBoundsException
	 *             if thrown.
	 */
	public void removeParentAt(int index) throws IndexOutOfBoundsException {
		parents.remove(index);
	}	
	
	
	/**
	 * @return
	 */
	public T getData() {
		return this.data;
	}

	/**
	 * @param data
	 */
	public void setData(T data) {
		this.data = data;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(this.data.toString());
/*		sb.append("{").append(getData().toString()).append(",[");
		int i = 0;
		boolean addComma = false;
		for (Node e : getParents()) {
			if (i > 0) {
				addComma = true;
				sb.append(",");
			}
			sb.append(e.getData().toString());
			i++;
		}
		
		i = 0;
		for (Node e : getChildren()) {
			if (addComma || i > 0) {
				sb.append(",");
			}
			sb.append(e.getData().toString());
			i++;
		}
		
		sb.append("]").append("}");*/
		return sb.toString();
	}
}

And tree is List of Node’s

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Represents a Tree of Objects of generic type T. The Tree is represented as a
 * single rootElement which points to a List<Node> of children. There is no
 * restriction on the number of children that a particular node may have. This
 * Tree provides a method to serialize the Tree into a List by doing a pre-order
 * traversal. It has several methods to allow easy updation of Nodes in the
 * Tree.
 * 
 * @author kumara
 */
public class Tree {

	private Node rootElement;

	/**
	 * Default ctor.
	 */
	public Tree() {
		super();
	}

	/**
	 * Return the root Node of the tree.
	 * 
	 * @return the root element.
	 */
	public Node getRootElement() {
		return this.rootElement;
	}

	/**
	 * Set the root Element for the tree.
	 * 
	 * @param rootElement
	 *            the root element to set.
	 */
	public void setRootElement(Node rootElement) {
		this.rootElement = rootElement;
	}

	/**
	 * Returns the Tree as a List of Node objects. The elements of the
	 * List are generated from a pre-order traversal of the tree.
	 * 
	 * @return a List<Node>.
	 */
	public List<Node> toList() {
		List<Node> list = new ArrayList<Node>();
		walk(rootElement, list);
		return list;
	}

	/**
	 * Returns a String representation of the Tree. The elements are generated
	 * from a pre-order traversal of the Tree.
	 * 
	 * @return the String representation of the Tree.
	 */
	public String toString() {
		return toList().toString();
	}

	/**
	 * Walks the Tree in pre-order style. This is a recursive method, and is
	 * called from the toList() method with the root element as the first
	 * argument. It appends to the second argument, which is passed by reference
	 * * as it recurses down the tree.
	 * 
	 * @param element
	 *            the starting element.
	 * @param list
	 *            the output of the walk.
	 */
	private void walk(Node element, List<Node> list) {
		for (Node data : element.getParents()) {
			walk(data, list);
		}
		list.add(element);
		for (Node data : element.getChildren()) {
			walk(data, list);
		}
	}

	public String toBranch(List branches) {
		return toBranches(branches).toString();
	}

	public List<Node> toBranches(List branches) {
		List<Node> list = new ArrayList<Node>();
		List pathList = new ArrayList();
		branch(rootElement, list,pathList,branches);
		return list;
	}

	private void branch(Node element, List<Node> list,List pathList,List branches) {
		for (Node data : element.getParents()) {
			parentBranch(data, list,pathList);
		}
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);
		
		for (Node data : element.getChildren()) {
			childBranch(data, list,pathList,branches);
			pathList.remove(pathList.size()-1);
		}

		if(element.getChildren().isEmpty()){
			printArray(pathList,branches);
		}
		//System.out.println(path);
	}
	
	
	/**
	 * @param element
	 * @param list
	 * @param pathList
	 */
	private void childBranch(Node element, List<Node> list,List pathList,List branches) {
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);
		for (Node data : element.getChildren()) {
			childBranch(data, list,pathList,branches);
			pathList.remove(pathList.size()-1);
		}
		
		if(element.getChildren().isEmpty()){
			printArray(pathList,branches);
		}
	}
	
	
	/**
	 * @param element
	 * @param list
	 * @param pathList
	 */
	private void parentBranch(Node element, List<Node> list,List pathList) {
		for (Node data : element.getParents()) {
			parentBranch(data, list,pathList);
		}
		// Add to path
		pathList.add(element.getData().toString());
		list.add(element);

	}
	
	
	/**
	 * @param array
	 */
	private void printArray(Collection array,List branches){
		StringBuffer sb = new StringBuffer();
		for(String pathElement :array){
			sb.append(pathElement).append(",");
		}
		branches.add(sb.toString());
		//System.out.println(sb.toString());
	}
}

Lets create a Task class for which we will build a tree


import java.io.Serializable;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * @author kumara
 * 
 */
public class GenericTask implements Serializable {
	private Long id = 0L;
	private Long parentId = 0L;
	
	public GenericTask() {
        super();
    }

	public GenericTask(Long taskId) {
		this();
		setId(taskId);
	}

	public GenericTask(Long taskId,Long parentTaskId) {
		this();
		setId(taskId);
		setParentId(parentTaskId);
	}
	
	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the parentId
	 */
	public Long getParentId() {
		return parentId;
	}

	/**
	 * @param parentId
	 *            the parentId to set
	 */
	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		/*return ReflectionToStringBuilder.reflectionToString(this,
				ToStringStyle.DEFAULT_STYLE);*/
		//return "["+id+","+parentId+"]";
		return id+"";
	}
}


Above code is Generic code which can be implemented any where. For example let us assume we have some tasks for which we have to build this tree. We will just implement Tree and Node for that task like this



/**
 * Non-generic subclass of Tree
 * 
 * @author kumara
 */
public class TaskTree extends Tree {
	public TaskTree() {
		super();
	}
}


/**
 * Non-generic subclass of Node
 * 
 * @author kumara
 */
public class TaskNode extends Node {
	public TaskNode() {
		super();
	}
}

Now the task is to load data from Database to javaObjects. We shall use TaskDAO to do that


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.jdbc.support.rowset.SqlRowSet;

/**
 * Dao for the Task POJO.
 * 
 * @author kumara
 */
public class TaskDAO extends AbstractDAO {

	private String childColumnName = "";
	private String parentColumnName = "";
	private String tableName = "";

	private final static Logger log = Logger
			.getLogger(TaskDAO.class.toString());

	public TaskDAO() {
	}

	/**
	 * @return the childColumnName
	 */
	public String getChildColumnName() {
		return childColumnName;
	}

	/**
	 * @param childColumnName
	 *            the childColumnName to set
	 */
	public void setChildColumnName(String childColumnName) {
		this.childColumnName = childColumnName;
	}

	/**
	 * @return the parentColumnName
	 */
	public String getParentColumnName() {
		return parentColumnName;
	}

	/**
	 * @param parentColumnName
	 *            the parentColumnName to set
	 */
	public void setParentColumnName(String parentColumnName) {
		this.parentColumnName = parentColumnName;
	}

	/**
	 * @return the tableName
	 */
	public String getTableName() {
		return tableName;
	}

	/**
	 * @param tableName
	 *            the tableName to set
	 */
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	/**
	 * Remove a Task object from the database.
	 * 
	 * @param task
	 *            the Task to remove.
	 */
	public void remove(GenericTask task) {
	}

	/**
	 * Saves a Task to the database if it is a new one, else updates it.
	 * 
	 * @param task
	 *            the Task to insert or update.
	 * @return the task id.
	 */
	public Long saveOrUpdate(GenericTask task) {
		return 1L;
	}

	/**
	 * Returns the Task pointed to by the task id. Returns a NULL if the Task is
	 * not found in the database.
	 * 
	 * @param taskId
	 *            the task id to look up.
	 * @return the Task object corresponding to the id.
	 */
	public GenericTask get(Long taskId) {
		return new GenericTask(taskId);
	}

	/**
	 * Returns all the children of the Task which has the specified parents id.
	 * 
	 * @param parentId
	 *            the id of the parents Task.
	 * @return a List of Tasks which are children of the Task specified.
	 */
	@SuppressWarnings("unchecked")
	public List findByParentId(Long parentId) {
		if(parentId == null){
			return Collections.EMPTY_LIST;
		}
		
		try {
			getJdbcTemplate().execute(
					"set lockmode session where readlock = nolock");
		} catch (Exception e) {
			
		}
		
		String sql = "SELECT * FROM " + getTableName() + " WHERE "
				+ getParentColumnName() + " = " + parentId;
		SqlRowSet resultSet = (SqlRowSet) getJdbcTemplate().queryForRowSet(sql);

		List returnList = new ArrayList();
		while (resultSet.next()) {
			GenericTask genericTask = new GenericTask(
					resultSet.getLong(getChildColumnName()));
			genericTask.setParentId(resultSet.getLong(getParentColumnName()));
			returnList.add(genericTask);
		}

		return returnList;
	}

	/**
	 * Returns all the Parents of the Task which has the specified child id.
	 * 
	 * @param childId
	 *            the id of the child Task.
	 * @return a List of Tasks which are parent of the Task specified.
	 */
	@SuppressWarnings("unchecked")
	public List findByChildId(Long childId) {
		if(childId == null){
			return Collections.EMPTY_LIST;
		}
		
		try {
			getJdbcTemplate().execute(
					"set lockmode session where readlock = nolock");
		} catch (Exception e) {
			
		}
		
		String sql = "SELECT * FROM " + getTableName() + " WHERE "
				+ getChildColumnName() + " = " + childId;
		SqlRowSet resultSet = (SqlRowSet) getJdbcTemplate().queryForRowSet(sql);

		List returnList = new ArrayList();
		while (resultSet.next()) {
			GenericTask genericTask = new GenericTask(
					resultSet.getLong(getChildColumnName()));
			genericTask.setParentId(resultSet.getLong(getParentColumnName()));
			returnList.add(genericTask);
		}

		return returnList;
	}

}


Now Lets build Tree using TaskTreeDAO


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author kumara
 *
 * Data Access Object for the TaskTree object. This is not a true Dao, since it
 * delegates to the TaskDao object for any database operations.
 */
public class TaskTreeDAO {

	private static final Logger log = Logger.getLogger(TaskTreeDAO.class
			.toString());

	public TaskTreeDAO() {
		super();
	}

	private TaskDAO taskDao;

	public void setTaskDao(TaskDAO taskDao) {
		this.taskDao = taskDao;
	}

	/**
	 * Saves a TaskTree object.
	 * 
	 * @param taskTree
	 *            a TaskTree object.
	 */
	public void saveOrUpdate(TaskTree taskTree) {
		List<Node> tasks = taskTree.toList();
		// save the tree in reverse order, starting from the leaf nodes
		// and going up to the root of the tree.
		int numberOfNodes = tasks.size();
		for (int i = numberOfNodes - 1; i >= 0; i--) {
			Node taskElement = tasks.get(i);
			GenericTask task = taskElement.getData();
			// taskDao.saveOrUpdate(task);
			Long parentId = task.getId();
			for (Iterator<Node> it = taskElement.getChildren()
					.iterator(); it.hasNext();) {
				Node childElement = it.next();
				GenericTask childTask = childElement.getData();
				childTask.setParentId(parentId);
				// taskDao.saveOrUpdate(childTask);
			}
		}
	}

	/**
	 * Gets a single TaskTree by id. This is the head of a recursive method call
	 * to getRecursive().
	 * 
	 * @param id
	 *            the id of the TaskTree.
	 * @return a TaskTree for that id.
	 */
	public TaskTree get(Long id) {
		TaskTree taskTree = new TaskTree();
		Node rootElement = new Node(new GenericTask(id,id));
		getRecursiveChildren(rootElement, taskTree);
		getRecursiveParents(rootElement, taskTree);
		taskTree.setRootElement(rootElement);
		
		return taskTree;
	}

	/**
	 * Recursively descends the Tree and populates the TaskTree object.
	 * 
	 * @param taskElement
	 *            the root Node.
	 * @param tree
	 *            the TaskTree object to populate.
	 */
	private void getRecursiveChildren(Node taskElement, TaskTree tree) {
		List children = taskDao.findByParentId(taskElement
				.getData().getId());
		List<Node> childElements = new ArrayList<Node>();
		for (Iterator it = children.iterator(); it.hasNext();) {
			GenericTask childTask = it.next();
			Node childElement = new Node(childTask);
			childElements.add(childElement);
			childElement.addParent(taskElement);
			getRecursiveChildren(childElement, tree);
		}
		taskElement.setChildren(childElements);
	}

	
	/**
	 * Recursively descends the Tree and populates the TaskTree object.
	 * 
	 * @param taskElement
	 *            the root Node.
	 * @param tree
	 *            the TaskTree object to populate.
	 */
	private void getRecursiveParents(Node taskElement, TaskTree tree) {
		List parents = taskDao.findByChildId(taskElement
				.getData().getParentId());
		List<Node> parentElements = new ArrayList<Node>();
		for (Iterator it = parents.iterator(); it.hasNext();) {
			GenericTask parentTask = it.next();
			Node parentElement = new Node(parentTask);
			parentElements.add(parentElement);
			parentElement.addChild(taskElement);
			getRecursiveParents(parentElement, tree);
		}
		taskElement.setParents(parentElements);
	}	
	
	/**
	 * @param id
	 * @return
	 */
	public TaskTree buildTree(Long id) {
		TaskTree taskTree = new TaskTree();
		Node rootElement = new Node(taskDao.get(id));
		getRecursiveChildren(rootElement, taskTree);
		getRecursiveParents(rootElement, taskTree);
		taskTree.setRootElement(rootElement);
		return taskTree;
	}
}


And some Utility Classes as i use Spring-JDBC here


import org.springframework.jdbc.core.JdbcTemplate;

import endoworks.dwutility.framework.util.ServiceLocator;
import endoworks.dwutility.framework.util.spring.SpringInitilizer;

/**
 * @author kumara
 * 
 */
public class AbstractDAO {
	private static SpringInitilizer springInitilizer = null;

	static {
		springInitilizer = new SpringInitilizer();
	}
	private JdbcTemplate jdbcTemplate;

	/**
	 * @return the jdbcTemplate
	 */
	public JdbcTemplate getJdbcTemplate() {
		if (jdbcTemplate == null) {
			jdbcTemplate = (JdbcTemplate) ServiceLocator
					.getService("jdbcTemplate");
		}
		return jdbcTemplate;
	}
}

A class to load/Initialize spring beans


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Ashwin
 * 
 */
public class SpringInitilizer {

	private static ApplicationContext context = null;

	static {
		context = new ClassPathXmlApplicationContext(
				new String[] { "applicationContext-dbMigrate.xml" });
	}
}

And finally data base table can be of form

create table test (key integer,parentkey integer);

Njoy creating any tree easily

Signature Capture In Java

Want to create paint like application where we can capture signature in java. Here is sample code to do it


/**
 * 
 */
package com.ashwin;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

/**
 * @author Ashwin
 * 
 */
public class SignatureCapture extends JApplet {

	public BufferedImage image = null;
	private JPanel canvas = new JPanel();
	private JPanel colorPanel = new JPanel();
	private Point lastPos = null;
	private Button captureButton = new Button("Capture");
	private Graphics gc;
	Graphics2D imageG = null;

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.applet.Applet#init()
	 */
	@Override
	public void init() {
		// TODO Auto-generated method stub
		super.init();

		setSize(600, 200);

		image = new BufferedImage(getWidth(), getHeight(),
				BufferedImage.TYPE_INT_ARGB);

		// get the image Graphics object
		imageG = image.createGraphics();
		colorPanel.setLayout(new GridLayout());
		canvas.setSize(getWidth(), getHeight());

		captureButton.setSize(100, 50);
		getContentPane().add(captureButton);
		getContentPane().add(canvas, BorderLayout.CENTER);
		setVisible(true);

		// get the Graphics Context
		gc = canvas.getGraphics();
		canvas.setBackground(Color.GRAY);
		gc.setColor(Color.GRAY);
		gc.fillRect(0, 0, image.getWidth(), image.getHeight());
		gc.setColor(Color.BLACK);

		imageG.setBackground(Color.GRAY);
		imageG.setColor(Color.GRAY);
		imageG.fillRect(0, 0, image.getWidth(), image.getHeight());
		imageG.setColor(Color.BLACK);

		captureButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent a) {
				try {
					Container cp = getContentPane();
					final Component comp = cp.add(new JSplitPane(
							JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(
									new JTextArea()), new JScrollPane(
									new JTextArea())));
					// cp.add(canvas);

					File filetoSave = new File("c:\\temp\\test4.jpeg");

					// If the file does not exist or the user gives permission,
					// save image to file.

					ImageWriter writer = null;
					ImageOutputStream ios = null;

					try {
						// Obtain a writer based on the jpeg format.

						Iterator iter;
						iter = ImageIO.getImageWritersByFormatName("jpeg");

						// Validate existence of writer.

						if (!iter.hasNext()) {
							return;
						}

						// Extract writer.

						writer = (ImageWriter) iter.next();

						// Configure writer output destination.

						ios = ImageIO.createImageOutputStream(filetoSave);
						writer.setOutput(ios);

						// Set JPEG compression quality to 95%.

						ImageWriteParam iwp = writer.getDefaultWriteParam();
						iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
						iwp.setCompressionQuality(0.95f);

						// Write the image.

						writer.write(null, new IIOImage((BufferedImage) image,
								null, null), iwp);
					} catch (IOException e2) {
						e2.getMessage();
					} finally {
						try {
							// Cleanup.

							if (ios != null) {
								ios.flush();
								ios.close();
							}

							if (writer != null)
								writer.dispose();
						} catch (IOException e2) {
						}
					}

				} catch (Exception e) {
					System.err.println(e);
				}
			}
		});

		canvas.addMouseMotionListener(new MouseMotionListener() {
			public void mouseDragged(MouseEvent m) {
				// the mouse(pen) was dragged, so the pixels at coords found in
				// MouseEvent m must be updated with current color
				Point p = m.getPoint();
				gc.drawLine(lastPos.x, lastPos.y, p.x, p.y);
				imageG.drawLine(lastPos.x, lastPos.y, p.x, p.y);
				lastPos = p;
			}

			public void mouseMoved(MouseEvent m) {
			}
		});
		canvas.addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
			}

			public void mousePressed(MouseEvent e) {
				lastPos = e.getPoint();
			}

			public void mouseReleased(MouseEvent e) {
				lastPos = null;
			}

			public void mouseEntered(MouseEvent e) {
			}

			public void mouseExited(MouseEvent e) {
			}
		});
	}

	/**
	 * 
	 */
	public SignatureCapture() {
	}

	public static void main(String[] args) {
		SignatureCapture p = new SignatureCapture();
	}
}

Properties Loader a Helper Class

Listed is the code for Property Loader a Helper class to load properties both from a file and from system.
This

  1. We can load file each time to read a property using getProperty(key) Method
  2. We can read properties loaded when class is loaded and are can be read from system properties where it is set
  3. It also has utility where we can Cast Property Values to Custom Type like Long/Int..etc
  4. It has implementation of adding parameters dynamically in property file by placing some placeholders


import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @author Ashwin Gets System variables that were loaded at server startup from
* the server.properties file
*/
public class PropertyLoader {
private static final Log log = LogFactory.getLog(PropertyLoader.class);
private static boolean initializedFromFile = false;

/**
* Get the Property From Server.properties. This is used when we want to
* read property from file each and every time
*
* @param key
* @return
*/
public static String getProperty(String key) {
Properties props = new Properties();
InputStream stream = PropertyLoader.class
.getResourceAsStream("/server.properties");
try {
props.load(stream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return props.getProperty(key);
}

/**
* This is used when we just want to load all properties loaded and are sure
* that those dont change while server is running thereby reducing load of
* reading from file
*
* Get the value of the key passed.
*
* @param key
* the token
* @return the value if there is one, otherwise null
*/
public static final String getSystemString(String key) {
String value = null;
try {
value = System.getProperty(key);

} catch (NullPointerException e) {
// ignore just return null;
}
return value;
}

/**
* Gets the boolean value if the string equalsIgnoreCase true, otherwise
* false.
*
* @param key
* the token
* @return true if the value is ignorecase true all other values including
* null return false.
*/
public static final boolean getBoolean(String key) {
String token = getSystemString(key);
if (token == null) {
return false;
}
if (token.equalsIgnoreCase("true")) {
return true;
}
return false;
}

public static final void loadSystemProperties() throws IOException {
loadSystemProperties("/server.properties");
}

/**
* Give the classpath qualified name of the filename to load, e.g.
*
*

	 *  /config.properties
	 * 

*
* @param file
* the classpath qualified filename of the file to load
*/
public static final void loadSystemProperties(String file)
throws IOException {
Properties props = new Properties();
InputStream stream = PropertyLoader.class.getResourceAsStream(file);
props.load(stream);

Iterator iterator = props.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = props.getProperty(key);
System.getProperties().setProperty(key, value);
}
initializedFromFile = true;
}

/**
* Sets the property and returns the previous value
*
* @param key
* @param value
*/
public static final String setSystemProperty(String key, String value) {
if (!initializedFromFile) {
log
.warn("Attempting to set System Property "
+ key
+ " to "
+ value
+ " but the file System Properties have not yet been read.");
}
return System.setProperty(key, value);
}

/**
* Replaces all config parameters in the string with the actual values.
* Parameters are in the form ${PARAM_NAME}. If a parameter tag is
* encountered, and the corresponding value cannot be retrieved, an
* exception will be generated.
*/
public static void resolveParameterTags(StringBuffer sb) {
int basePos = 0;
String rstr = sb.toString();
final String tagStartToken = "${";
final String tagEndToken = "}";
int pos = rstr.indexOf(tagStartToken);

while (pos >= 0) {
int endPos = rstr.indexOf(tagEndToken, pos);

if (endPos < 0) {
String msg = "Parameter tag not closed: " + rstr;
throw new IllegalArgumentException(msg);
}

String pName = rstr.substring(pos + tagStartToken.length(), endPos);
String parameterValue = getSystemString(pName);

if (parameterValue == null || "".equals(parameterValue)) {
String msg = "Missing configuration parameter " + pName
+ " for tag " + rstr;
throw new IllegalArgumentException(msg);
}

// replace the parameter
sb.replace(basePos + pos, basePos + endPos + tagEndToken.length(),
parameterValue);

// point base position to the rest of the string
basePos = basePos + pos + parameterValue.length();
rstr = sb.substring(basePos);
pos = rstr.indexOf(tagStartToken);
}
}

public static long getLong(String key, long i) {
String token = getSystemString(key);
if (token == null) {
return i;
}
return Long.parseLong(token);
}

public static int getInt(String key, int i) {
String token = getSystemString(key);
if (token == null) {
return i;
}
return Integer.parseInt(token);
}

public static void loadSystemProperties(ServletContext servletContext,
String file) throws IOException {
// TODO Auto-generated method stub
Properties props = new Properties();
InputStream stream = servletContext.getResourceAsStream(file);
props.load(stream);

Iterator iterator = props.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = props.getProperty(key);
System.getProperties().setProperty(key, value);
}
initializedFromFile = true;

}
}