all about Java technoligies. Know about Java, J2EE, J2ME. Java Tutorials, Java Tips and tricks.
Friday, November 18, 2011
JMS and RMS
- RMI is tightly-coupled mechanism.
- The destination object need to be available online at the time of sending messages from client to server.
- RMI has RPC-model
JMS
- JMS provides loosely coupled mechanism.
- The destination object need not be available online at the time of sending messages from client to server.
- JMS has messaging model.
Friday, September 30, 2011
Iterator vs Enumeration
Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration, because it always denies other threads to modify the collection object which is being iterated by it. Whenever a second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly.
Wednesday, June 1, 2011
Difference Between Interface and Abstract Class
2. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one abstract class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
Monday, May 23, 2011
differences between SAX and DOM parsers
· A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
· A SAX parser serves the client application always only with pieces of the document at any given time.
· A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What’s more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.
DOM Parser:
· A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
· A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
· A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.
Externalizable and Serializable in Java
While implementing Serializable, you are not forced to define any method as it's a marker interface. However, you can use the writeObject or readObject methods to handle the serilaization process of complex objects. But, while implementing Externalizable interface, you are bound to define the two methods: writeExternal and readExternal and all the object serialization process is solely handled by these two methods only.
In case of Serializable interface implementation, state of Superclasses are automatically taken care by the default implementation whereas in case of Externalizable interface the implementing class needs to handle everything on its own as there is no default implementation in this case.
Example Scenario: when to use what?
If everything is automatically taken care by implementing the Serializable interface, why would anyone like to implement the Externalizable interface and bother to define the two methods? Simply to have the complete control on the process. OKay... let's take a sample example to understand this. Suppose we have an object having hundreds of fields (non-transient) and we want only few fields to be stored on the persistent storage and not all. One solution would be to declare all other fields (except those which we want to serialize) as transient and the default Serialization process will automatically take care of that. But, what if those few fields are not fixed at design tiime instead they are conditionally decided at runtime. In such a situation, implementing Externalizable interface will probably be a better solution. Similarly, there may be scenarios where we simply don't want to maintain the state of the Superclasses (which are automatically maintained by the Serializable interface implementation).
Which has better performance - Externalizable or Serializale?
In most of the cases (or in all if implemented correctly), Externalizable would be more efficient than Serializable for the simple reason that in case of Externalizable the entire process of marshalling, un-marshalling, writing to the stream, and reading back from stream, etc. is under your control i.e., you got to write the code and you can of course choose the best way depending upon the situaton you are in. In case of Serializable, this all (or at least most of it) is done implicitly and the internal implementation being generic to support any possible case, can ofcourse not be the most efficient. The other reason for Serializable to be less efficient is that in this case several reflective calls are made internally to get the metadata of the class. Of course, you would not need any such call is needed in case Externalizable.
However, the efficiency comes at a price. You lose flexibility because as soon as your class definition changes, you would probably need to modify your Externaliable implementation as well. Additionally, since you got to write more code in case Externalizable, you increase the chances of adding more bugs in your application.
Another disadvantage of Externalizable is that you got to have the class to interpret the stream as the stream format is an opaque binary data. Normal Serialization adds field names and types (this why reflective calls are needed here) into the stream, so it's possible to re-construct the object even without the availability of the object's class. But, you need to write the object reconstruction code yourself as Java Serialization doesn't provide any such API at the moment. The point is that in case of Serialzable you can at least write your code as the stream is enriched with field names and types whereas in case Externalizable the stream contains just the data and hence you can't unless you use the class definition. As you can see Serializable not only makes many reflective calls, but also puts the name/type info into the stream and this would of course take some time making Serialzable slower than the corresponding Externalizable process where you got to stuff only the data into the stream.
Serialization
- Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network.
What is use of serialVersionUID?
- During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.
Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree
List of incompatible changes:
Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
If we explicitly metion the suid using the statement:
private final static long serialVersionUID =
then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.
What is the need of Serialization?
- The serialization is used :-
To send state of one or more object’s state over the network through a socket.
To save the state of an object in a file.
An object’s state needs to be manipulated as a stream of bytes.
Other than Serialization what are the different approach to make object Serializable?
- Besides the Serializable interface, at least three alternate approaches can serialize Java objects:
1)For object serialization, instead of implementing the Serializable interface, a developer can implement the Externalizable interface, which extends Serializable. By implementing Externalizable, a developer is responsible for implementing the writeExternal() and readExternal() methods. As a result, a developer has sole control over reading and writing the serialized objects.
2)XML serialization is an often-used approach for data interchange. This approach lags runtime performance when compared with Java serialization, both in terms of the size of the object and the processing time. With a speedier XML parser, the performance gap with respect to the processing time narrows. Nonetheless, XML serialization provides a more malleable solution when faced with changes in the serializable object.
3)Finally, consider a "roll-your-own" serialization approach. You can write an object's content directly via either the ObjectOutputStream or the DataOutputStream. While this approach is more involved in its initial implementation, it offers the greatest flexibility and extensibility. In addition, this approach provides a performance advantage over Java serialization.
Do we need to implement any method of Serializable interface to make an object serializable?
- No. Serializable is a Marker Interface. It does not have any methods.
What happens if the object to be serialized includes the references to other serializable objects?
- If the object to be serialized includes the references to other objects whose class implements serializable then all those object’s state also will be saved as the part of the serialized state of the object in question. The whole object graph of the object to be serialized will be saved during serialization automatically provided all the objects included in the object’s graph are serializable.
What happens if an object is serializable but it includes a reference to a non-serializable object?
- If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.
e.g.
public class NonSerial {
//This is a non-serializable class
}
public class MyClass implements Serializable{
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;
MyClass(NonSerial nonSerial){
this.nonSerial = nonSerial;
}
public static void main(String [] args) {
NonSerial nonSer = new NonSerial();
MyClass c = new MyClass(nonSer);
try {
FileOutputStream fs = new FileOutputStream("test1.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("test1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MyClass) ois.readObject();
ois.close();
}
tch (Exception e) {
e.printStackTrace();
}
}
}
On execution of above code following exception will be thrown –
java.io.NotSerializableException: NonSerial
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)
Are the static variables saved as the part of serialization?
- No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.
What is a transient variable?
- These variables are not included in the process of serialization and are not the part of the object’s serialized state.
What will be the value of transient variable after de-serialization?
- It’s default value.
e.g. if the transient variable in question is an int, it’s value after deserialization will be zero.
public class TestTransientVal implements Serializable{
private static final long serialVersionUID = -22L;
private String name;
transient private int age;
TestTransientVal(int age, String name) {
this.age = age;
this.name = name;
}
public static void main(String [] args) {
TestTransientVal c = new TestTransientVal(1,"ONE");
System.out.println("Before serialization: - " + c.name + " "+ c.age);
try {
FileOutputStream fs = new FileOutputStream("testTransients.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("testTransients.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After de-serialization:- " + c.name + " "+ c.age);
}
}
Result of executing above piece of code –
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-serialization is it’s default value.
Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter?
- Yes. As while restoring the object’s state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.
How can one customize the Serialization process? or What is the purpose of implementing the writeObject() and readObject() method?
- When you want to store the transient variables state as a part of the serialized object at the time of serialization the class must implement the following methods –
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state as a part of serialized object
}
private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}
e.g.
public class TestCustomizedSerialization implements Serializable{
private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;
TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}
private void writeObject(ObjectOutputStream os) {
try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
}
private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}
public int getNoOfTranVar() {
return noOfTranVar;
}
}
The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.
If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?
- The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.
E.g.
public class ParentNonSerializable {
int noOfWheels;
ParentNonSerializable(){
this.noOfWheels = 4;
}
}
public class ChildSerializable extends ParentNonSerializable implements Serializable {
private static final long serialVersionUID = 1L;
String color;
ChildSerializable() {
this.noOfWheels = 8;
this.color = "blue";
}
}
public class SubSerialSuperNotSerial {
public static void main(String [] args) {
ChildSerializable c = new ChildSerializable();
System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
try {
FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}
}
Result on executing above code –
Before : - 8 blue
After :- 4 blue
The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.
Immutable Class
- Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
How to create an immutable class?
- To create an immutable class following steps should be followed:
Create a final class.
Set the values of properties using constructor only.
Make the properties of the class final and private
Do not provide any setters for these properties.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Immutable objects are automatically thread-safe –true/false?
- True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
Which classes in java are immutable?
- All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
What are the advantages of immutability?
- The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.
Tuesday, April 26, 2011
why string is immutable in java ?
In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.
- Imagine String Pool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
- Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming.
=> Advantages of Immutability
- You can share immutable objects between threads without danger of changes confusing the other thread. You don’t need any locking. Two threads can both work on an immutable object at the same time without any possibility of conflict.
- Once you check the value, you know it has to stay safe. No one can pass you a value, then behind your back swap it to an unsafe one using a background thread. This is particularly important in high security situations where allowing an invalid value to sneak in could compromise system integrity, e.g. a filename. This is probably the main reason that Strings are immutable.
- You can share duplicates by pointing them to a single instance. You need only one copy, e.g. String interning. This saves RAM. With mutable StringBuilders that were temporarily identical, you could not throw one away, and replace it with a reference to the other, since at any moment their values could diverge again.
- You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.
- Immutable objects are much better suited to be Hashtable keys. If you change the value of an object that is used as a hash table key without removing it and re-adding it you lose the mapping.
- Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
=>To create an immutable class following steps should be followed:
-Create a final class.
-Set the values of properties using constructor only.
-Make the properties of the class final and private
-Do not provide any setters for these properties.
-If the instance fields include references to mutable objects, don't allow those objects to be changed:
-Don't provide methods that modify the mutable objects.
-Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
Monday, April 25, 2011
Aspect-oriented programming
Aspect : An aspect of a program is a feature linked to many other parts of the program, but which is not related to the program's primary function. An aspect cross-cuts the program's core concerns, therefore violating its separation of concerns that tries to encapsulate unrelated functions. For example, logging code can cross-cut many modules, yet the aspect of logging should be separate from the functional concerns of the module it cross-cuts. Isolating such aspects as logging and persistence from business logic is the aim of aspect-oriented software development (AOSD), of which the aspect-oriented programming (AOP) paradigm is the most widely employed
Cross-cutting concern : In computer science, cross-cutting concerns are aspects of a program which affect other concerns. These concerns often cannot be cleanly decomposed from the rest of the system in both the design and implementation, and can result in either scattering (code duplication), tangling (significant dependencies between systems), or both.
For instance, if writing an application for handling medical records, the bookkeeping and indexing of such records is a core concern, while logging a history of changes to the record database or user database, or an authentication system, would be cross-cutting concerns since they touch more parts of the program.
AOP: In computing, aspect-oriented programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development.
AOP includes programming methods and tools that support the modularization of concerns at the level of the source code, while "aspect-oriented software development" refers to a whole engineering discipline.
Wednesday, September 29, 2010
Class Loaders
In a JVM, each class is loaded by some instance of a java.lang.ClassLoader. The ClassLoader class is located in the java.lang package and developers are free to subclass it to add their own functionality to class loading.
Whenever a new JVM is started by typing java MyMainClass, the "bootstrap class loader" is responsible for loading key Java classes like java.lang.Object and other runtime code into memory first. The runtime classes are packaged inside of the JRE\lib\rt.jar file. We cannot find the details of the bootstrap class loader in the Java documentation, since this is a native implementation. For the same reason, the behavior of the bootstrap class loader will also differ across JVMs.
In a related note, we will get null if we try to get the class loader of a core Java runtime class, like this:
log(java.lang.String.class.getClassLoader()); Next comes the Java extension class loader. We can store extension libraries, those that provide features that go beyond the core Java runtime code, in the path given by the java.ext.dirs property. The ExtClassLoader is responsible for loading all .jar files kept in the java.ext.dirs path. A developer can add his or her own application .jar files or whatever libraries he or she might need to add to the classpath to this extension directory so that they will be loaded by the extension class loader.
The third and most important class loader from the developer perspective is the AppClassLoader. The application class loader is responsible for loading all of the classes kept in the path corresponding to the java.class.path system property.
"Understanding Extension Class Loading" in Sun's Java tutorial explains more on the above three class loader paths. Listed below are a few other class loaders in the JDK:
java.net.URLClassLoaderjava.security.SecureClassLoaderjava.rmi.server.RMIClassLoadersun.applet.AppletClassLoader
java.lang.Thread, contains the method public ClassLoader getContextClassLoader(), which returns the context class loader for a particular thread. The context class loader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If it is not set, the default is the class loader context of the parent thread. The context class loader of the primordial thread is typically set to the class loader used to load the application.
transient and volatile in Java
Java defines two interesting type modifiers: transient and volatile. These modifiers are used to handle somewhat specialized situations.
When an instance variable is declared as transient, then its value need not persist when an object is stored. For example:
class T {
transient int a; // will not persist
int b; // will persist
}
Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the contents of b would. The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.
Wednesday, September 15, 2010
Hibernate
Caching solutions, transactions and other features Hibernate provides are not so easy to
implement. It is actually non sense to develop something which already exist.
Using Hibernate everything is there. You just have to use it.
How Hibernate works
What is nice and in my opinion an advantage over entity beans, hibernate starts from simple java
classes (Pojo = Plain Old Java Objects).
To use hibernate you will create a simple java class:
public class Bug
implements Serializable
{
private int hashValue = 0;
private java.lang.Integer id;
private java.lang.String title;
public Bug()
{
}
public Bug(java.lang.Integer fid)
{
this.setId(fid);
}
public java.lang.Integer getId() {
return id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public java.lang.String getTitle() {
return title;
}
public void setTitle(java.lang.String title) {
this.title = title;
}
.............
Than you create a mapping file. The mapping file explains Hibernate which field in the class is
mapped to which field in the database.
And you start using your hibernate class.
Example to create a new entry in the database:
try {
Bug bug = new Bug();
bug.setTitle("Title");
bug.setTuserFk(tuser);
Transaction tx = session.beginTransaction();
session.save(bug);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
}
The creation of the description file can be done with tools like MyEclipse. MyEclipse provides
functionality to create classes and description files directly from database tables.
Hibernate includes tools to
• generate Java classes from description files
• description files from existing database tables
• database tables from description files.
Hibernate
Better system architecture
When you include all functionality of your application and the access to the database
within your dialogs, you will have some severe disadvantages.
It is really difficult to reuse code. You will repeat code at many places. If you change
anything it is quite hard to find out all places where you have to add changes,
when you separate your dialogs from your logic and the logic from the persistence
mechanism you can more easily apply changes to one part without influencing the other
parts.
Reduce time for standard DB actions
Most queries in database development are simple “insert, update, delete” statements.
There is no need to develop all these tedious statements. Hibernate helps you to save time.
Loading classes from the database looks like
Query query = session.createQuery("select b from Bug as b");
for (Iterator iter = query.iterate(); iter.hasNext();) {
bugs.add((Bug) iter.next());
}
return bugs;
saving a class “bug” to the database looks like
session.update(bug);
Hibernate
Main features
Hibernate is a solution for object relational mapping and a persistence management
solution or persistent layer.
What you can imagine is probably that you have your application with some functions
(business logic) and you want to save data in a database. When you use Java all the
business logic normally works with objects of different class types. Your database tables
are not at all objects.
Hibernate provides a solution to map database tables to a class. It copies the database
data to a class. In the other direction it supports to save objects to the database. In this
process the object is transformed to one or more tables.
Saving data to a storage is called persistence. And the copying of tables to objects and
vice versa is called object relational mapping.
Wednesday, June 16, 2010
Features and differences between JDK 1.4, 1.5, 1.6
before couple of days i encountered a question that what are the differences between all versions of Java. I was knowing some features but was not able to explain exact to my team members. Then try googling and gathered some information . I think it will be helpful to all. Correct me if something goes wrong.
JDK 1.0 (january 23, 1996) oak
- Initial release
JDK 1.1 (february 19, 1997)
- Retooling of the AWT event model
- Inner classes added to the language
- JavaBeans
- JDBC
- RMI
J2SE 1.2 (December 8, 1998) playground
This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 & version name "J2SE"
(Java 2 platform, Standard edition) replaced JDK to distinguish the base platform from
J2EE (java 2 platform, enterprise edition) and J2ME (java 2 platform, micro edition).
- Strictfp keyword
- Reflection
- Swing api integration into the core classes
- JVM equipped with a jit compiler
- Java plug-in
- Java IDL
- An IDL implementation for corba interoperability
- Collections Framework
J2SE 1.3 (may 8, 2000) kestrel
- Hotspot jvm included
- JavaSound
- JNDI included in core libraries
- Java platform debugger architecture (jpda)
- RMI was modified to support optional compatibility with corba
J2SE 1.4 (february 6, 2002) merlin
- assert keyword
- Regular expressions
- Exception chaining (allows an exception to encapsulate original lower-level exception)
- Internet protocol version 6 (IPV6) support
- Non-blocking nio (new input/output)
- Logging API
- Image i/o api for reading and writing images in formats like jpeg and png
- Integrated XML parser and XSLT processor (JAXP)
- Integrated security and cryptography extensions (JCE, JSSE, JAAS)
- Java web start
J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5]
- Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
- Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.
- Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer).
- Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).
- Swing: new skinnable look and feel, called synth.
- Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
- Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory.
- Automatic stub generation for rmi objects.
- Static imports concurrency utilities in package java.util.concurrent.
- Scanner class for parsing data from various input streams and buffers.
- Assertions
- StringBuilder class (in java.lang package)
- Annotations
Java SE 6 (december 11, 2006) mustang
sun replaced the name "J2SE" with java se and dropped the ".0" from the version number.
Beta versions were released in february and june 2006, leading up to a final release that occurred on december 11, 2006.
The current revision is update 14 which was released in may 2009.
- Support for older win9x versions dropped.
- Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration
- Dramatic performance improvements for the core platform, and swing.
- Improved web service support through JAX-WS JDBC 4.0 support
- Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically.
- Upgrade of JAXB to version 2.0: including integration of a stax parser.
- Support for pluggable annotations
- Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).
Java se 6 update 10
A major enhancement in terms of end-user usability.
- Java Deployment Toolkit, a set of javascript functions to ease the deployment of applets and java web start applications.
- Java Kernel, a small installer including only the most commonly used jre classes. Enhanced updater.
- Enhanced versioning and pack200 support: server-side support is no longer required.
- Java quick starter, to improve cold start-up time.
- Improved performance of java2D graphics primitives on windows, using direct3D and hardware acceleration.
- A new Swing look and feel called NIMBUS and based on synth.
- Next-generation java plug-in: applets now run in a separate process and support many features of web start applications.
Java se 6 update 12
This release includes the highly anticipated 64-bit java plug-in (for 64-bit browsers only), windows server 2008 support,
and performance improvements of java and JAVAFX applications.
Friday, September 11, 2009
Special characters (#, @, :) in URL
Special characters (#,@,:) in URLs
Special characters as #,@,: in URLs have to be hex encoded.
Example: Your password is ###
It gets encoded to ftp://user:%23%23%23@host.com
where 23 is the hex value (0x23) of '#'
Character Hex Conversion
| # | %23 |
| space | %20 |
| @ | %40 |
Unsafe characters :
Why: Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded.
Characters:
Character CodePoints(Hex) CodePoints(Dec)
Space 20 32
Quotation marks 22 34
'Less Than' symbol("<") 3C 60
'Greater Than' symbol (">") 3E 62
'Pound' character ("#") 23 35
Percent character ("%") 25 37
Left Curly Brace ("{") 7B 123
Right Curly Brace ("}") 7D 125
Vertical Bar/Pipe ("|") 7C 124
Backslash ("\") 5C 92
Caret ("^") 5E 94
Tilde ("~") 7E 126
Left Square Bracket ("[") 5B 91
Right Square Bracket ("]") 5D 93
Grave Accent ("`") 60 96
The Best Java Web Framework
This one will be a very short article about my experiences with several Java Web Frameworks out there. Here we go:
| Spring MVC | It would be a good choice for the most of your needs. |
| Wicket | Interesting to look at – no XML, no JSP (JSTL), just Java and HTML. Can mimic a flow in a WebPage object. Better separation of concerns than, for example, in GWT (e.g. no Javish CSS, etc.). Good Community The only thing that is off is your dynamic HTML elements are done in Java |
| Spring Webflow | It is a separate beast. It mostly is good, and makes sense, however, in practice, once you need to do something a bit more complex that a shopping cart or a hotel booking app (hint, hint), you can run into problems. “Back button” and “Double click” are not very well handled by the framework, may get an exception while bookmarking (there is a magic recipe, but far from being simple, and intuitive), sharing data across the flow, last resort error handling are not simple, etc. |
| Stripes | It is Good and simple (no XML – conventions), but not very actively maintained - hence not as mature. (good community though) Worth to look at for simple projects. |
| Struts | It's architecture is wrong from the very beginning: Validation (XML - why? What about minimum search criteria, what about several, what about nested OO validators!?) / 0 for NULLs / Multi Action Forms / Testing (without StrutsTestcase) / etc. ) Improved a bit since WebWork merging, but still lots of “code smells”. |
| JSF | Quite hard to keep up with all these JSF based JSP tags + integration with security is not simple + full JSF solutions are usually Frankensteins with many pieces from different vendors. |
| Tapestry | It is not bad, actually make sense, when you get it. But have you ever looked and tried to follow the Tapestry code? - Very complex implementation, if ever need to look inside the code + Tapestry does take time to learn, so forget about a new off-shore team, or fresh out of college not so geeky grads, taking it on. Some more benefits of using Spring framework:
|
Useful lInks for Java
http://java.sun.com - The official Java developer website - new articles posted weekly.
http://www.jguru.com - A great source for Q&A style interaction in the community
http://www.javaranch.com - Everything about Java and more. you can also get help for your problems in Java and prepare for certification. Best forum.
http://java.sun.com/docs/books/tutorial/ - The Official Java tutorial from Sun - very useful for almost any feature set. Must for detail study of Java.
http://www.javaworld.com - One of the originals. Weekly updates of Java articles.
Saturday, November 22, 2008
Utilities and Frameworks fro Java
There are so many useful Java frameworks and utilities out there, those are free and open-source . Here are a few of my recent favorites. Feel free to add your own to the list.
Joda Time : Java Date/Time replacement
Rome : Java tools for parsing, generating and publishing RSS and Atom feeds.
GWT : Java-Ajax web framework
Java Mozilla HTML Parser : A wrapper around Mozilla’s HTML Parser
JFreeChart : JFreeChart is a 100% free Java chart library that makes it easy for developers to display professional quality charts in their applications.
Lucene : High-performance, full-featured text search engine library written entirely in Java.
PMD: One of best code review tool with eclipse plug-in.
iText : This library contains classes that generate documents in the Portable Document Format (PDF) and/or HTML.
GanttProject : GanttProject is a project scheduling application written in Java and featuring gantt chart, resource management, calendaring, import/export (MS Project, HTML, PDF, spreadsheets). more info http://ganttproject.biz
XStream : A simple library to serialize objects to XML and back again