The Singhology's Blog

Algebra is fun. Why? Cuz it ends with “bra”

Posted in Uncategorized by jsinghfoss on September 5, 2011

What is Algebra? It helps you to find missing information or Unknown to be specific. In a real life scenario, the unknown could be the total cost of your next laptop after list price + taxes. Or it could be used to calculate for total interest paid after the end amortization period.

The unknown in general in Mathematics is denoted by “x”. But you could always use your own character. The x (or unknown) than becomes a variable.

What is a Math equation? The equation in Mathematics represents a sentence. Just like how we have in English language. The equation is what we use to figure out the value of unknown. For example, List Price + Tax = Total Price Paid

Please note we can always rearrange equations. For example, List Price = Total Price Paid – Tax

TIP: It helps to write out the entire sentence in English first and then pick information out of it.

The process of solving for the unknown involves isolating variable x from all values. At the end you will get a value like x = 10 or x = 2.33. When you have fully isolated the variable x you have solved the equation.

What is an inverse operation? The inverse operation takes place when we are trying to isolate the variable x. It is very important to maintain balance during the inverse operation. It is done by applying the same operator + number on both sides (and not just one). The inverse operation for addition is subtraction. And the inverse operation for multiplication is division.

You could always use the process of substitution to verify your calculation. It is done by substituting the value of x back into the equation.

The process of solving a problem using Algebra

1. Understand the problem statement – Retrieve all given information and create a sentence in English language. The sentence will include numbers that will help you to calculate the unknown value.

2. Create equation to solve for x

3. Figure out how to isolate the variable x

4. Manipulate the equation – You will apply inverse operation here

5. Rewrite the equation

6. Equation is solved you have found the value of x. You’ll get a value in a format x = 10, or x = 2.33.

7. You may use the process of substitution to verify your calculation

Unescape unicode \\ in Java String

Posted in Java by jsinghfoss on August 17, 2011

I ran into a problem where my unicode slashes (\\) were not escaped properly. I had the following unicode string in a java variable:

\\u0011\\u00FF\\u0000\\u0001

To get correct 4 bytes out of this unicode string you must use StringEscapeUtils.unescapeJava(unicodeString) available inside Apache’s Common Lang jar.

The method will correctly edit the above unicode string into:

\u0011\u00FF\u0000\u0001

So, on calling getBytes() on your new unescaped string you will get 4 bytes.

Tagged with: ,

GWT 2.2.0 RequestFactory + Spring 3.0.x Integration

Posted in Spring Framework, GWT by jsinghfoss on August 10, 2011

MOVED from old blog

I must say it’s been a while since my last post. Lately, I have been really busy with work and part-time projects that I could not even reserve a minute to come here. But anyways today I’m here to reveal some really good work that I was stuck on for almost a week now. In my project, I had decided to implement GWT 2.2.0 along with Spring 3.0.x. Talking about communication: one way to enable communication between client and server is to use GWT RPC mechanism. But RPC from what I have learned is more of a service oriented approach. My first need was to have something in place for CRUD functionality. For data oriented tasks such as CRUD, Google has invented something called RequestFactory (RF). After skimming the Google tutorial, RF sounded like the right approach for CRUDing data. With RF we can also control the amount of data client will present on the UI. Now since I’m using Spring, the challenge was to discover a way to integrate RF with Spring. I spent hours researching on how to do this but couldn’t find a way. That being said there’s enough material available on Google in regards to RPC + Spring integration. After few days of hard luck, I finally invented a solution on how to do this. I would also like to give credit to “niloc132” who’s usually on #gwt and helped with GWT.

TWITTER: Please give credits where due and you can follow me on twitter at @jsinghfoss.

LICENSE: You are free to use this solution for personal or commercial use. You can also modify the solution in any way. In case if you have enhanced the solution, please share with everyone. Provided as-is without any guaranty.

EDIT 4/27/2011 I have noticed few bugs in the below source-code. Once all the bugs are fixed, I will edit this post to include changes. So, stay tuned!

EDIT 5/5/2011 Modified GWTSpringEntityLocator class. Changes include: class does not implement ApplicationContextAware interface anymore, Create method creates an instance of the entity, Removed unused context (as well as set method).

RequestFactory + Spring INTEGRATION SOLUTION

STEP 1 - web.xml

Declare DispatcherServlet and map it to “/gwtRequest

<servlet>
  <servlet-name>singhsolution</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>singhsolution</servlet-name>
  <url-pattern>/gwtRequest</url-pattern>
</servlet-mapping>

The above code will intercept all incoming requests whose url pattern contains “/gwtRequest“.

STEP 2 - singhsolution-servlet.xml

Create a servlet mapping file by the name “singhsolution-servlet.xml“. It will contain information related to the servlets managed by Spring.

Inside this file we need to declare a SimplUrlHandlerMapping bean which will map a value to its appropriate controller. In our case, the controller is called “gwtRequestFactoryController“.

<bean>
		<property name="mappings">
			<value>
				/gwtRequest=gwtRequestFactoryController
 			</value>
		</property>
	</bean>

Before we declare our “gwtRequestController” we need to create few classes that will be used by the client to find appropriate entities and services managed by Spring.

STEP 3 - Create the following classes

GWTSpringServiceLayerDecorator
GWTSpringEntityLocator
GWTSpringServiceLocator

public class GWTSpringServiceLayerDecorator extends ServiceLayerDecorator
		implements ApplicationContextAware {
	private ApplicationContext context;
	@Override
	public <T extends Locator<?, ?>> T createLocator(Class<T> clazz) {
		return context.getBean(clazz);
	}
	@Override
	public Object createServiceInstance(Method contextMethod
			Method domainMethod) {
		// Check if the request needs a service locator
		Class<? extends ServiceLocator> locatorType = getTop()
				.resolveServiceLocator(contextMethod, domainMethod);
		assert locatorType != null;
		// Inject an instance of the locator itself,
		// and then get an instance from it
		ServiceLocator locator = context.getBean(locatorType);
		return locator.getInstance(domainMethod.getDeclaringClass());
	}
	@Override
	public Object invoke(Method domainMethod, Object... args) {
		Object response = super.invoke(domainMethod, args);
		try {
			if (response instanceof Callable) {
				return ((Callable<?>) response).call();
			} else {
				return response;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context = context;
	}
}

GWTSpringEntityLocator will be used to locate JPA entities managed by Spring configuration files.

public class GWTSpringEntityLocator<T extends HasVersionAndId> extends
		Locator<T, Long> {
	@Autowired
	EntityManager entityManager;

	@Override
	public T create(Class<? extends T> clazz) {
		try
		{
			return clazz.newInstance();
		} catch (InstantiationException e)
		{
		       throw new RuntimeException(e);
		} catch (IllegalAccessException e)
		{
			throw new RuntimeException(e);
		}
	}

	@Override
	public T find(Class<? extends T> clazz, Long id) {
		return entityManager.find(clazz, id);
	}
	@Override
	public Class<T> getDomainType() {
		// Unused, and if it becomes used, we're in trouble
		throw new UnsupportedOperationException();
	}
	@Override
	public Long getId(T domainObject) {
		return domainObject.getId();
	}
	@Override
	public Class<Long> getIdType() {
		return Long.class;
	}
	@Override
	public Object getVersion(T domainObject) {
		return domainObject.getVersion();
	}
}

GWTSpringServiceLocator will be used to locate services managed by Spring configuration files.

public class GWTSpringServiceLocator implements ServiceLocator,
		ApplicationContextAware {
	private ApplicationContext context;
	public Object getInstance(Class<?> clazz) {
		return context.getBean(clazz);
	}
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context = context;
	}
}

STEP 4

In this step, we’ll implement a hack that I have created which will manage our RequestFactoryServlet (i.e. Spring will manage our RequestFactoryServlet) containing our customServiceLayerDecorator implementation.

CustomServletWrappingController

Please note that this is an initial hack and I am sure there is room for improvement. The negative side of this hack is we will have to pretty much rewrite the entire ServletWrappingController class as it’s animmutable class. The “afterPropertiesSet” method is where my hack is implemented. The stock implementation of this method creates an instance of a servlet defined in the Spring configuration file. But in my hack I’ve replaced the following line:

this .servletInstance = (Servlet) this .servletClass.newInstance();

to

this.servletInstance = (Servlet) this.getApplicationContext().getBean("requestFactoryServlet");

IMPORTANT NOTE: So as you can see, we are not using the servlet class defined in our Spring configuration file and instead hard coding the Servlet that we intend to use. Clearly, the downside of this approach is your CustomServletWrappingController can only manage one servlet i.e. your RequestFactoryServlet.

Hey but this works!

public class CustomServletWrappingController extends ServletWrappingController {
	private Class servletClass;
	private String servletName;
	private Properties initParameters = new Properties();
	private String beanName;
	private Servlet servletInstance;
	/**
	 * Set the class of the servlet to wrap. Needs to implement
	 * <code>javax.servlet.Servlet</code>.
	 *
	 * @see javax.servlet.Servlet
	 */
	public void setServletClass(Class servletClass) {
		this.servletClass = servletClass;
	}
	/**
	 * Set the name of the servlet to wrap. Default is the bean name of this
	 * controller.
	 */
	public void setServletName(String servletName) {
		this.servletName = servletName;
	}
	/**
	 * Specify init parameters for the servlet to wrap, as name-value pairs.
	 */
	public void setInitParameters(Properties initParameters) {
		this.initParameters = initParameters;
	}
	public void setBeanName(String name) {
		this.beanName = name;
	}
	/**
	 * Overriden to implement our hack. It initializes the wrapped Servlet
	 * instance.
	 *
	 * @author jatinder-singh
	 * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		if (this.servletClass == null) {
			throw new IllegalArgumentException("servletClass is required");
		}
		if (!Servlet.class.isAssignableFrom(this.servletClass)) {
			throw new IllegalArgumentException("servletClass ["
					+ this.servletClass.getName()
					+ "] needs to implement interface [javax.servlet.Servlet]");
		}
		if (this.servletName == null) {
			this.servletName = this.beanName;
		}
		// We retrieve RF instance instead of using the one defined in
		// singhsolution-servlet.xml
		// Author: Jatinder Singh
		this.servletInstance = (Servlet) this.getApplicationContext().getBean(
				"requestFactoryServlet");
		this.servletInstance.init(new DelegatingServletConfig());
	}
	/**
	 * Invoke the the wrapped Servlet instance.
	 *
	 * @see javax.servlet.Servlet#service(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse)
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		this.servletInstance.service(request, response);
		return null;
	}
	/**
	 * Destroy the wrapped Servlet instance.
	 *
	 * @see javax.servlet.Servlet#destroy()
	 */
	public void destroy() {
		this.servletInstance.destroy();
	}
	/**
	 * Internal implementation of the ServletConfig interface, to be passed to
	 * the wrapped servlet. Delegates to ServletWrappingController fields and
	 * methods to provide init parameters and other environment info.
	 */
	private class DelegatingServletConfig implements ServletConfig {
		public String getServletName() {
			return servletName;
		}
		public ServletContext getServletContext() {
			return CustomServletWrappingController.this.getServletContext();
		}
		public String getInitParameter(String paramName) {
			return initParameters.getProperty(paramName);
		}
		public Enumeration getInitParameterNames() {
			return initParameters.keys();
		}
	}
}

If you are here you are pretty much there :) . Now edit your singhsolution-servlet.xml file to include all the beans you have created above.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean>
		<property name="mappings">
			<value>
				/gwtRequest=gwtRequestFactoryController
 			</value>
		</property>
	</bean>
	<bean id="gwtSpringServiceLayerDecorator" 		class="com.jsi.singhsolution.server.servlet.GWTSpringServiceLayerDecorator" />
	<bean id="defaultExceptionHandler" 		class="com.google.gwt.requestfactory.server.DefaultExceptionHandler" />
	<!-- RequestFactoryServlet bean is scoped as singleton. Injecting custom  		SpringServiceLayerDecorator. -->
	<bean id="requestFactoryServlet" 		class="com.google.gwt.requestfactory.server.RequestFactoryServlet" 		scope="singleton">
		<constructor-arg ref="defaultExceptionHandler" />
		<constructor-arg ref="gwtSpringServiceLayerDecorator" />
	</bean>
	<bean id="gwtSpringEntityLocator" 		class="com.jsi.singhsolution.server.servlet.GWTSpringEntityLocator" />
	<bean id="gwtSpringServiceLocator" 		class="com.jsi.singhsolution.server.servlet.GWTSpringServiceLocator" />
	<!-- IMPORTANT NOTE: CustomServletWrappingController is a hacked version  		of ServletWrappingController. The servlet class defined here will not be  		used. Please see CustomServletWrappingController for more information. -->
	<bean id="gwtRequestFactoryController" 		class="com.jsi.singhsolution.server.servlet.CustomServletWrappingController">
		<property name="servletClass">
			<value>com.google.gwt.requestfactory.server.RequestFactoryServlet
			</value>
		</property>
		<property name="servletName">
			<value>gwtRequest</value>
		</property>
	</bean>
</beans>

If you have followed my instructions carefully, you have created all the required classes including the hack that is needed for Spring to manage RequestFactoryServlet in its machinery.

RequestFactory in Action

I am going to assume you know a little bit of GWT. The below code will end up calling a Spring Service called UserDetailsService. Once the user is returned successfully we display its first name.

requestFactory.userDetailsRequest().getUserByUsername("singh").fire( new Receiver<UserEntityProxy>() {
					@Override
					public void onSuccess(UserEntityProxy user) {
						RootPanel.get("result").add(new HTML("Username was retrieved: " + user.getFirstName()));
					}
				});

How this hack can be improved?

If I could inject my custom ServiceLayerDecorator class in the RequestFactoryServlet class defined in the actual ServletWrappingController bean, will solve our issue of hardcoding the Servlet; and we won’t need a CustomServletWrappingController that we have currently in place.

I don’t really have a code sample for this yet but I may create one in future. If you think the above code can be improved, please drop a comment or email me at j.singh.developer@gmail.com.

 

Working on Android platform

Posted in Android by jsinghfoss on August 17, 2010

It’s 00:00 and I just finished reading Pro Android development  book. Working on this platform is a very seamless experience and things are easy to absorb and are obvious. There are so many resources and sample apps available that it has become so much easier for me to learn Android. From my experience it is more fun to learn if you have an actual device with you. I can run my sample apps on the device directly within seconds. It is much faster than running it on the emulator. It’s actually seconds as compared to minutes.

AppFuse – Fully Deployed & Working

Posted in AppFuse Light, Maven by jsinghfoss on July 30, 2010

After hours of work and research, I have finally deployed AppFuse on my hosting account. I have worked with all the builds of AppFuse and will stick with AppFuse light. There are number of reasons for this. First of all, my hosting provider doesn’t support Maven repository and therefore I cannot use anything that depends on Maven (I know there’s Maven Wagon, but don’t have enough time to test it). So AppFuse itself is out of the equation. There are few things that I like in AppFuse core and will move those  to AppFuse Light. So far my experience with AppFuse has been outstanding and have learnt a lot of things during the process (Sitemesh, I guess I will love it).

Spring Security – Sample App Now Available (JGrocery)

Posted in JGrocery by jsinghfoss on July 28, 2010

Last night, I quickly read through the Spring Recipes > Spring Security chapter and extended JGrocery sample application with Spring Security. I have committed the changes to my repository and it’s available for download. So that you can quickly run and see the application, I have provided a .war file under download section. The source code is available through source section of the repository.

It took me about 30 minutes to implement this module. The security module is very developer friendly and easy to use and implement. Spring security secures a web application at different levels including URL access level, the method invocation level, the view rendering level, and the domain object level.

Things that I am working on currently (and may extend JGrocery with these technologies): Hibernate, Spring Web Flow, AppFuse, ant, Maven

Click here to visit JGrocery Repository or use this link – http://code.google.com/p/jgrocery-v2/

AppFuse Deployment – Private Tomcat

Posted in AppFuse by jsinghfoss on July 27, 2010

Today, I spent my entire evening working with AppFuse. Really what my goals were: Deploy AppFuse to my local Tomcat Application Server and then deploy AppFuse on my hosting account. So the good news is – I made it :) Even though it’s running and the site is live but it’s not 100% complete (will do the other half later this week). I have noticed that there are not much resources available online for AppFuse deployment. So, I will post my complete work on this topic very soon. Stay tune!

Tagged with:

AppFuse on Eclipse – Solved mvn eclipse:eclipse

Posted in AppFuse by jsinghfoss on July 25, 2010

If you want to develop AppFuse on Eclipse, you will need to transform AppFuse project into Eclipse project. If you are following the AppFuse documentation, it will ask you to run “mvn eclipse:eclipse” in your project (where the pom.xml file is located). On running the above command, you will get a build error. And the way to solve this issue is to run the latest Eclipse plugin. Instead of “mvn eclipse:eclipse” use the below command:

mvn org.apache.maven.plugins:maven-eclipse-plugin:2.6:eclipse

Hope this will help others.

AppFuse – Maven Repository (?/.m2/repository/) Where?

Posted in AppFuse by jsinghfoss on June 26, 2010

As I said in my previous post that I am experimenting few things with AppFuse. I had few issues with AppFuse set-up on Eclipse. Thanks to this (Sonatype) web page which helped me to locate my Maven repository on Windows. On Windows Vista it’s – C:\Users\USER-NAME\.m2\repository

So now I finally have AppFuse environment set-up on my local computer. If you need help with AppFuse, leave a comment.

AppFuse Project

Posted in AppFuse by jsinghfoss on June 21, 2010

Lately, I have been working on a project where I have decided to use AppFuse Software and build on top of it. I had few issues while trying to get it to work but finally I had it working. I am still in the process of testing. Over the next few days, I will be testing its Security functionality and modularity.

BTW…I tried to integrate AppFuse 2.1.0-M1 with Eclipse but it didn’t work.  I have a feeling that I am missing something and will give it a another try.

Follow

Get every new post delivered to your Inbox.