Monday, July 11, 2011

RPC in Javascript using JSON-RPC-Java


 RPC in Javascript using JSON-RPC-Java


Remote procedure call (RPC) in javascript is a great concept of creating rich web applications. First we will see some background about RPC using JavaScript Object Notation (JSON). See following quote from Wikipedia entry of JSON-RPC.
JSON-RPC is a remote procedure call protocol encoded in JSON. It is a very simple protocol (and very similar to XML-RPC), defining only a handful of data types and commands. In contrast to XML-RPC or SOAP, it allows for bidirectional communication between the service and the client, treating each more like peers and allowing peers to call one another or send notifications to one another. It also allows multiple calls to be sent to a peer which may be answered out of order.
A JSON invocation can be carried on an HTTP request where the content-type is application/json. Besides using HTTP for transport, one may use TCP/IP sockets. Using sockets, one can create much more responsive web applications with JSON-RPC, compared to polling data from a service with JSON-RPC over HTTP.
JSON-RPC-Java is a key piece of Java web application middleware that allows JavaScript DHTML web applications to call remote methods in a Java Application Server without the need for page reloading (now referred to as AJAX). It enables a new breed of fast and highly dynamic enterprise Web 2.0 applications.
For using JSON-RPC-Java in your code, you need to download following json-rpc-java-1.0.1.zip file and unzip it.
http://oss.metaparadigm.com/jsonrpc/download.html
The zip contains required jsonrpc-1.0.jar and jsonrpc.js files that we will use in our project.
Once the JAR file is in classpath of your project, modify your WEB.XML (deployment descriptor) file and make an entry for JSONRPCServlet as follow.
?
1
2
3
4
5
6
7
8
<servlet>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-name>
<url-pattern>/JSON-RPC</url-pattern>
</servlet-mapping>
Note that JSONRPCServlet is a servlet class inside the jsonrpc-1.0.jar file. Also, we have mapped a URL/JSON-RPC with the servlet. Hence the servlet will be invoked by the container whenever this URL is called by the client.
Also, do not forget in include the javascript file in your application.
?
1
<script src="js/jsonrpc.js" type="text/javascript"></script>
We will create a small webpage which will have two textboxes to enter numbers and a button which will call the RPC (call .sum() method on an object which resides in server) and send these two numbers to server. Server will do sum of these numbers and return the result back and the result will be displayed on webpage.
Following is the content of the html page.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html>
<head>
<title>JSON-RPC-Java Demo</title>
<script type="text/javascript" src="js/jsonrpc.js"></script>
<script type="text/javascript">
function fnSum(form) {
try {
//Create a jsonrpc object for doing RPC.
jsonrpc = new JSONRpcClient("JSON-RPC");
 
// Call a Java method on the server
result = jsonrpc.sumObject.sum(form.a.value, form.b.value);
//Display the result
alert(result);
 
} catch(e) {
alert(e.description);
}
}
</script>
</head>
<body>
<h1>JSON-RPC-JAVA</h1>
<form>
<input type="text" name="a"/>
<input type="text" name="b"/>
<input type="button" onclick="fnSum(this.form)" value="Sum"/>
</form>
</body>
</html>
Note that in order to use JSON-RPC-Java, you need to set an object ofcom.metaparadigm.jsonrpc.JSONRPCBridge class in session. All the object that we will use in RPC from Client side needs to be registered into JSONRPCBridge’s object. JSONRPCBridge object can be written in session using jsp:useBean tag.
?
1
2
<jsp:useBean id="JSONRPCBridge" scope="session"
class="com.metaparadigm.jsonrpc.JSONRPCBridge" />
We will use a business class called Sum which will do sum operation on the input and return the output. Following is the content of Sum class.
?
1
2
3
4
5
6
package net.viralpatel.jsonrpc;
public class Sum {
public Integer sum(Integer a, Integer b) {
return a + b;
}
}
Thus we need to register an object of class Sum in JSONRPCBridge object in order to use it from javascript.
?
1
2
Sum sumObject = new Sum();
JSONRPCBridge.registerObject("sumObject", sumObject);
Doing RPC from javascript is easy now. All we need is an jsonrpc object that we get by doing jsonrpc = new JSONRpcClient(“JSON-RPC”);. Note that the argument passed inside the JSONRpcClient() is the URL that we mapped to JSONRPCServlet servlet.
Once we get an object of jsonrpc, we can call remote methods by:
?
1
result = jsonrpc.sumObject.sum(form.a.value, form.b.value);
Where sumObject is the name that we provided while registering Sum class to JSONRPCBridge.
Following is the screenshot of the html page for user input.
JSON-RPC-Java Screen
Following is the sum output that the server returned to webpage using json-rpc.
JSON-RPC-Java Output screen

Wednesday, July 6, 2011

How to Make a Java Class Immutable


Making a class immutable
Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable).
However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this.
The reason perhaps might be clear once we have a look at the code.
Now in order to make a class immutable we must restrict changing the state of the class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Above do not provide any method where we modify the instance variables.
Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values.
Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding.
The following code gives a way to make the class immutable.
/*
Code Developed By Prafulla Raut
This code demonstrates the way to make a class immutable
*/
// The immutable class which is made final
final class MyImmutableClass
{
// instance var are made private & final to restrict the access
private final int count;
private final double value;
// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
   count = paramCount;
   value = paramValue;
}
// provide only methods which return the instance var
// & not change the values
public int getCount()
{
   return count;
}
public double getValue()
{
  return value;
}
}
// class TestImmutable
public class TestImmutable
{
  public static void main(String[] args)
  {
   MyImmutableClass obj1 = new MyImmutableClass(3,5);
   System.out.println(obj1.getCount());
   System.out.println(obj1.getValue());
   // there is no way to change the values of count & value-
  // no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}
The possible use of immutable classes would be a class containing a price list represented for a set of products.
Otherwise also this represents a good design.

Monday, May 30, 2011

Interview Questions when 5 or 6 years of Java/J2EE experience


Interview Questions when 5 or 6 years of Java/J2EE experience

I attended so many interviews. I have around 6 years of IT industry experience, with 5 years in Java/J2EE. Attending interviews is good thing for me because it helps me revise the things, and I have switched many companies so nobody offers me a job, thats good, because I am also not willing to join or change, but for my acumen, and to keep myself ready, I attend interviews.
I believe apart from following blogs, forums, technocrats, interviews are also good way to be up to date.
Below are the questions asked several companies in India like Sapient, Royal Bank OF Scotland, Namura, HP, etc.
I would post the solutions to some tricky questions in following blogs.
Generally there were some basic questions:
1. java Objective SCJP level
2. J2EE objective
3. JMS Objective
4. IBM MQ Objective
5. Complicated Multithreading
6. Serialization, File I/O

Then in Face to Face, which generally is of more than 1 hr. Following are questions asked from different companies:

Sapient:
JDk 1.5 Collections classes.
Multintreading Concepts - Barrier, Latch, etc.
JMS functioning
SQl Query using JOINS
Java Design pattern - detail
Overloading, Overriding, Comparator, Comparable, hashCode(), equals(), Serializable, Externalizable, RMI, garbage Collection.

Nomura
1. How would you implement cache in java.
2. How would you implement auto complete using java, jsp.
3. How would you implement a chache with auto complete feature.
4. How to make class immutable.
5. How to serialize immutable class.
6. How to gaurantee message delivery in JMS, fault tolerance
7. Message recovery techniques and redelivery.
8. DROP table.
9. Oracle Stored Procedure or function
10. Struts architecture
11. JSP Exception Handling
12. java Objective SCJP Level
13. java Design Pattern
14. J2EE objective
15. Implementing references
16. UNIX Commands - grep, softlink, hardlink
17. Serializable, Externalizable, Cloneable


Gemstone
1. How would you implement your own Thread Pool.
2. What is NIO
3. Best way to read data from socket using traditional I/O
4. Beat way to read file.
5. How to read characters from InputStream.
6. How Serialization works
7. Synchronization
8. how to implement counter in servlet.
9. how hashtable is thread safe.
10. CharSet, Enocder, Decoder
11. AtomicInteger, volatile, transient.
12. JTA, XA, how XA works, two phase commit.
13. Role of transaction manager in XA transaction.
14. XADataSource, and closing XADataSource.
15. UserTransaction
16. JCA Architecture


Mobily Infotech
1. deep copy and shallow copy
2. hash code
3. graceful shutdown of threads
4. NaN, 0/0
5. wrapper classes.
6. BootStrap Class Loader
7. Oracle OCI.
8. Oracle JDBC drivers
9. Oracle Thin and Thick Clients.
10. Oracle Rak
11. MQ API, MQ classes for Java.
12. MessageId, Priority for MQ message.
13. Garbage Collection
14. Java Green Threads
15. Coorelated Sub Queries.
16. Steps to make connection to MQ using Java.
17. Options to set for browsing message in MQ Queue.
18. Client Mode/Bindings Mode.
19. Log4j
ION Trading
1. Core Java SCJP level
2. Current Project Architecture
3. Message Flow in current project.
4. Fault Tolerance in JMS
5. Hashing Algo in Java, HashMap
6. Aggregation, Composition, Encapsulation, Abstraction.
7. How to implement Thread Pool
8. Complete Garbage Colection Algo.
9. DataSource, DB connection pool - how it works.
10. Exception- Logic, how to handle and design Exception, Error.
11. NIO-concept, Socket handling using NIO.
12. Adapter Design pattern
13. Stored Proc, Trigger
14. JDK1.5 Thread pool
15. Serialization, Externalization
16. Immutable, FInal, Usage of Final and Immutable
17. Exception handling in the spawned threads
18. RESTful Web Services, JEEVAN
19. Types of Parsers


HP
1. Why Use EJB 3.0
2. Why use JPA
3. Why use JPA with ORM, Standard ORM products
4. Writing Complex Query while using JPA and ORM
5. JTA, how it works
6. JTA, how to use
7. Where to use JDBC and where ORM
8. JSF Architecture, who is model, view and controller
9. Optimistic Lock in JPA - Detailed
10. Multithreaded program to read large file/ code and design

1. Latch, Barrier, synchronized, Lock, ThreadPoolExecuter, Garbage Collection Algo.
2. Which forums do you follow,  Cloud Computing, How to improve programming and Coding skills.
3.  Design hrose racing application.
4. Struts, how to extend struts. Why to use Struts.
5.  Where to use messaging

Royal Bank Of Scotland:
1. Hashing Algorithm.
2. Search Algorithm
3. MVC design Pattern.
4. Multi threading Objectives.
5. Design Application which handles a particular operation for millions of trades, operation like trade validation. Application communicates external application for data.
6. Several Designing Questions.
7. Scala, Open Source high performing JMS implementations, Dynamic languages
8. Cache Implementation.
9. How Oracle Coherence works.

TIBCO:
1. JCA - Tntro
2. JPA - Intro
3. EAGER/ LAZY loading
4. JPA relations
5. IBM MQ Objective
6. JMS session, Thread Safety In JMS
7. JMS providers
8. JMS implementation
9. AQ Provider and implementation using JNDI
10. Garbage Collection algorithms.
11. SOAP
12. JTA.


Bank Of America - Meriyl Lynch
1. How is semaphore implemented.
2. How to ensure only one instance in Singleton class.
3. How synchronization works, inside JVM.
4. Master JVM is holding objects. Slave JVM's are reading and writing the object.
     What problems can come and what is solution.
5. How Garbage Collection works in JVM.
6. When are class garbage collected, when are classes unloaded.
7. How to ensure that instance is never garbage collected.
8. Different protocols for Web Services.
9. Managing Session in Web Services
10. RMI, how EJB works
11. passing objects between two JVM's.

12. role of WSDL, stubs, etc. in Web Services.
13. Garbage Collection Tuning parameters.
14. LAZY Loading in ORM.
15. Why there is Stack and heap in JVM. Why this structure.
16. how much memory a program consumes, when no objects created inside program.
And more....

CSC
1. 50 numbers ( 1 to 50 ) are distributed in random order in an array of size 50. One number is missing. How to find. 
2. Inner Classes, Anonymous Classes. 
3. Find manager name who has max. number of employees working under him, when table has employeedID, Name, and ManagerID as columns. and Manager can also be employee. 
4. Serialization. 
5. How to design a web application, medium size. 
6. Write logic to print alternate elements in a ArrayList, even some are removed. 
7. How to implement a Hospital scenario, where doctor is examining patients, and emergency cases, and informing doctor of emergency cases, scheduling, etc. 
8. How to select unique elements from a table. 
9. Calculate number of legs, and give formula:
   7 persons, each person having 7 bags, each bag having 7 dogs, and each dog having 7 puppies. 

http://shekup.blogspot.com/2010_10_01_archive.html

Thursday, April 28, 2011

4 different ways to create objects in java:

There are four different ways to create objects in java:

A. Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way.

 MyObject object = new MyObject();

B. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

C. Using clone() The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();


D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();