what is moneky patching ?

Monkey-patching is the dangerous-yet-frequently-useful technique of re-opening existing classes to change or add to their behavior. The term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as you desire.

Do not confuse it with sub class and use, that is some thing which the compile time stuff in java and related languages. I can be though of as using filters or reflection to modify or tweek the run time behavior of a class.there are libraries like cglib (code generation library – which adds or intercepts the main class file) which helps to do that.

In monkey patching main class is called and you additional behaviour, however in subclass you have to explicitly call the sub class.

Restful Web Api

A RESTful web service (also called a RESTful web API/ end point url) is a simple web service implemented using HTTP and the principles of REST. It is a collection of resources, with four defined aspects:
the base URI for the web service, such as http://example.com/resources/
the Internet media type of the data supported by the web service. This is often JSON, XML or YAML but can be any other valid Internet media type.
the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE).
The API must be hypertext driven.

REST (representational state transfer) is an approach for getting information content from a Web site by reading a designated Web page that contains an XML (Extensible Markup Language)/JSON/Text or other MIME type file that describes and includes the desired content.

REST is an architecture style(not a protocol like SOAP – its uses HTTPS protocol) for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.

Note that your application can use REST services (as a client) without being a REST architecture by itself; e.g., a single-machine, non-REST program can access 3rd-party REST services.

JAR file using Java commands

Following are few commands that can be used to create/view/modify/execute a JAR file using Java command line utilities and JVM.

Create a JAR file

1
2
3
jar cf JAR_FILE_NAME FILE_NAMES_OR_DIRECTORY_NAME
e.g.
jar cf MyApp1.jar C:\JavaProject\MyApp

View contents of a JAR file

1
2
3
jar tf JAR_FILE_NAME
e.g.
jar tf MyApp1.jar

View contents with detail of a JAR file

1
2
3
jar tvf JAR_FILE_NAME
e.g.
jar tvf MyApp1.jar

Note that we have used v (verbose) option to see the detail of JAR.

Extract content of JAR file

1
2
3
jar xf JAR_FILE_NAME
e.g.
jar xf MyApp1.jar

Extract specific file from JAR file

1
2
3
jar xf JAR_FILE_NAME FILE_NAME(S)_FROM_JAR_FILE
e.g.
jar xf MyApp1.jar Test1.class

Update a JAR file

1
2
3
jar uf JAR_FILE_NAME FILE_NAMES_FROM_JAR_FILE
e.g.
jar uf MyApp1.jar Test1.class

Executing a JAR file

1
2
3
java -jar JAR_FILE_NAME
e.g.
java -jar MyApp.jar

Create an executable JAR file

In order to create an executable JAR, one of the classes that we include in our JAR must be a main class.
Create a text file called MANIFEST.MF using any text editor and copy following content in it.

1
2
Manifest-Version: 1.0
Main-Class: MyMainClass

Where MyMainClass is the name of the class that contents main method. Also note that you have to specify fully qualified class name here.
Use following command to create an executable JAR file.

1
jar cvfm MyApp.jar MANIFEST.MF FILE_NAMES_OR_DIRECTORY_NAME

How to avoid Java Code in JSP-Files

The use of scriptlets (those <% %> things) is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) over a decade ago. The major disadvantages of scriptlets are:

  1.     Reusability: you can’t reuse scriptlets.
  2.     Replaceability: you can’t make scriptlets abstract.
  3.     OO-ability: you can’t make use of inheritance/composition.
  4.     Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.
  5.     Testability: scriptlets are not unit-testable.
  6.     Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.

Oracle itself also recommends in the JSP coding conventions to avoid use of scriptlets whenever the same functionality is possible by (tag) classes. Here are several cites of relevance:

In the spirit of adopting the model-view-controller (MVC) design pattern to reduce coupling between the presentation tier from the business logic, JSP scriptlets should not be used for writing business logic. Rather, JSP scriptlets are used if necessary to transform data (also called “value objects”) returned from processing the client’s requests into a proper client-ready format. Even then, this would be better done with a front controller servlet or a custom tag.
How to replace scriptlets entirely depends on the sole purpose of the code/logic. More than often this code is to be placed in a fullworthy Java class.

#If you want to invoke the same Java code on every request, less-or-more regardless of the requested page, e.g. checking if an user is logged in, then implement a Filter and write code accordingly in doFilter() method. E.g.:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
if (((HttpServletRequest) request).getSession().getAttribute(“user”) == null) {
((HttpServletResponse) response).sendRedirect(“login”); // Not logged in, redirect to login page.
} else {
chain.doFilter(request, response); // Logged in, just continue request.
}
}
When mapped on an appropriate url-pattern covering the JSP pages of interest, then you don’t need to copypaste the same piece of code over all JSP pages.

#If you want to invoke some Java code to preprocess a request, e.g. preloading some list from a database to display in some table, if necessary based on some query parameters, then implement HttpServlet and write code accordingly in doGet() method. E.g.:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Product> products = productDAO.list(); // Obtain all products.
request.setAttribute(“products”, products); // Store products in request scope.
request.getRequestDispatcher(“/WEB-INF/products.jsp”).forward(request, response); // Forward to JSP page to display them in a HTML table.
} catch (SQLException e) {
throw new ServletException(“Retrieving products failed!”, e);
}
}
This way dealing with exceptions is easier. The DB is not accessed in the midst of JSP rendering, but far before the JSP is been displayed. You still have the possibility to change the response whenever the DB access throws an exception. In the above example, the default error 500 page will be displayed which you can anyway customize by an <error-page> in web.xml.

#If you want to invoke some Java code to postprocess a request, e.g. processing a form submit, then implement HttpServlet and write code accordingly in doPost() method. E.g.:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter(“username”);
String password = request.getParameter(“password”);
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute(“user”, user); // Login user.
response.sendRedirect(“home”); // Redirect to home page.
} else {
request.setAttribute(“message”, “Unknown username/password. Please retry.”); // Store error message in request scope.
request.getRequestDispatcher(“/WEB-INF/login.jsp”).forward(request, response); // Forward to JSP page to redisplay login form with error.
}
}
This way dealing with different result page destinations is easier: redisplaying the form with validation errors in case of an error (in this particular example you can redisplay it using ${message} in EL), or just taking to the desired target page in case of success.

#If you want to invoke some Java code to control the execution plan and/or the destination of the request and the response, then implement HttpServlet according the MVC’s Front Controller Pattern. E.g.:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
View view = new View(request, response);
Action action = ActionFactory.getAction(request);
action.execute(view);
view.navigate();
}
Or just adopt a MVC framework like JSF so that you end up with just a JSP/Facelets page and a Javabean class without the need for a HttpServlet.

If you want to invoke some Java code to control the flow inside a JSP page, then you need to grab an (existing) flow control taglib like JSTL core. E.g. displaying List<Product> in a table:

<%@ taglib uri=”http://java.sun.com/jsp/jstl/core&#8221; prefix=”c” %>

<table>
<c:forEach items=”${products}” var=”product”>
<tr>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>

# If you want to invoke some utility Java code directly in the JSP page (typically public static methods), then you need to define them as EL functions. There’s a standard functions taglib in JSTL, but you can also easily create functions yourself. Here’s an example how JSTL fn:escapeXml is useful to prevent XSS attacks.
<%@ taglib uri=”http://java.sun.com/jsp/jstl/functions&#8221; prefix=”fn” %>

<input type=”text” name=”foo” value=”${fn:escapeXml(param.foo)}” />

The Art of Programming

Behind every science there is an art and vice versa. 3 essential prerequisites required to fulfill it – curiosity, methodology & logic, utility with beauty.

1. Curiosity is essential to any stream of work. It helps us gather more information, widens our knowledge, and thereby deal with the problem in a much more creative way, bringing the science of the art alive.

2. Methodology and Logic – is critical when problem solving. And also, when handed over a task or project to undertake. Without putting down things in a methodological way, arranging the facts, one should not just “barge” into finding or providing solutions. This is what leads to bugs in the program due to haste (of course this is what helps make IT service industries increase their profits – add bugs, so only they can clean and add new bugs)

3. Utility with Beauty – No matter how small a task that has been assigned to you or how boring or repetitive it is. Perform and create each task with the same joy you would, as you do when listening repeatedly to your favorite tune or watching reruns of your favorite movie. This is the only way to create beauty. Remember, what you create will be utilized by others. Innovation is not just “something new”, but it has been created because there was a need for it. Hence, behind every line of code you write, that helps aid in the innovation of your product, keep the beauty of simplicity and its utility in mind. The more complex your code, the more the debugging and more the errors.

It’s a real art to compose meaningful error messages or to design flexible input formats which are not error-prone.”

How to change Maven local repository

Windows 7 becomes very slow once the profile size increases. For better performance it should be less than 2 GB. By default default location of maven repository is inside user directory which increases user profile size and makes the computer very slow. The better option is to configure maven respiratory out side the user directory and increase your windows 7 performance.  Follow this post, it might help :

Maven local repository is used to store all your projects’ dependency libraries (plugin jars and other files which downloaded by Maven), . In simple, when you use Maven to build your project, it will automatically download all dependency libraries into your Maven local repository.

Maven local repository is default to home directory :

Unix/Mac OS X – ~/.m2 on
Windows – C:\Documents and Settings\username\.m2 on Windows
Often times, you need to change the default location for maintainability purpose, after all, the .m2 is not a meaningful name.

1. Maven configuration file

Maven local repository is defined in the Maven’s configuration file, for example, {M2_HOME}\conf\setting.xml.
2. Edit it “setting.xml”

Find the following “localRepository” pattern, and define your new Maven local repository inside the “<localRepository>” element like this :

<settings>…
  <!– localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  –>

<localRepository>D:/maven_repo</localRepository>
… <settings>
3. Saved it

Done, your new Maven local repository is now changed to D:/maven_repo, all the future project’s dependency libraries or related files will be downloaded into this folder. See following folder :

<!– localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
/path/to/local/repo
–>

Google Plus Hangout: A Google Video Calling Service

Day by day, video calling is becoming very easy with online service. Just few days before, Google plus has offered a new feature as Hangout, where you can make video calling with your Gmail friends by just installing Google’s video chat plug-in in your computer. Connecting with Google plus Hangout, user can do face to face conversation as well as chat with up to 10 people at a time.

Google Plus Hangout: A Google Video Calling Service

Google+ Hangout has been started with the launch of Google plus on 29th June, 2011. It is a video calling feature where you can do group chat. You can chat with up to 10 people in single Hangout group chat session. It is best for group chat with friends or serious teams call at the office, but it is not good for one-on-one video chats because of a little complex setup and steps involved. It works on Windows, Mac and Linux too.

How it works:

To begin video calling service with Google plus Hangout, first of all you just need to install Google voice and video chat plug-in in your computer. Once you start installing, first save file on the window that appears. After then open plug-in file from download section and run it for installing. After installing voice and video chat plug-in, you can see video chat section in Hangouts, Gmail, iGoogle and Orkut. To start video chat with your friends, you need to attach web-cam with your computer. Google plus Hangout is available with high quality audio and video, so you can see and listen to your best one very clearly. Google plus hangouts is connected with YouTube so that you can share video within video chats very easily and quickly.

Pros:

  • Make video calling by only installing Google voice and video chat plug-in
  • Use Google+ Hangout without installing software
  • You can make video calling in Hangouts, Gmail, iGoogle and Orkut
  • Chat with up to 10 people at once

Cons:

  • Complicated for one-on-one video chats

To download the plug in follow the below link:

http://www.google.com/support/chat/bin/answer.py?answer=161993

 

OR download latest Chrome (it is bundled with all latest plugins)

you can invoke video and voice chat from google online chat window (gmail, igoogle, google+ etc) once this plugin is installed in your browser.

 

MVC Analogy – (Model View Controller)

Sometime to under stand a concept more deeply, analogy really helps. we can relate concepts with something we already know and can imagination. Mike has given me a good example of Bank working as MVC.

Just image the functionality of todays bank and see how its work flow is MVC.

Initial thinking – you can think of data as gold or money kept in the safe of a bank. One cannot access the locker/safe or a bank directly. His access is controller by some mechanism.

You go to bank “May i help you counter” and request for money withdraw. The receptionist puts you request in a queue and gives you a token and redirects to a particular counter. Here receptionist acts as Controller.
When you reach that counter the guy there asks for you Id proof account number and other details as per bank rules for verification. This guy acts as Model which has some set of rules to interact with database.
The guy provides you the money from your safe ie the data from the database.
Finally you can think of  bank receipt as you view.

Its just a platform to imagine … add more scenarios.

What is form Binding

Form hold data which is submitted to trigger the action on server. In the conventional approach when form is submitted the posted data is retrieved at server side component by getting parameters, like


form.getParameter(“userName”)
form.getParameter(“userAge”)
form.getParameter(“userCity”)
…..

This requires a lot of plumbing code. to make it easier latest frameworks have come with a new concept called as “Binding”.
In Form binding you create an object(POJO) which is binded to the form. so whenever the form is submitted, the object gets populated automatically without writing any plumbing code.

Similarly the “Event Binding” happens. You can bind an event with the form,  register a listener to it and  when that particular even is fired, it invokes your action. A very beautiful implementation is implemented in GWT google web toolkit for the same.

The data can  be bind to form with events like refresh, buffering etc using the xml configurations or annotations.

Sample from a Binding File

To give you an idea of what a binding file looks like, below a very simple example is shown.

<fb:context xmlns:fb="http://apache.org/cocoon/forms/1.0#binding" path="/" > <fb:value id="firstname" path="firstName"/> <fb:value id="lastname" path="lastName"/> <fb:value id="email" path="email"/> </fb:context>

With the dyna form in frame works like Struts 2.0 even the data object is created automatically via the xml configurations only. Hence it save time to write and maintain the data object class as well.