JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Difference between Checked and Unchecked Exceptions in Java

October 1, 2013 by Manisha Patil Leave a Comment

In this article we will understand the differences between Checked and Unchecked Exceptions in Java language.Exception handling is essential to make a robust application, because the user does not want to see a stacktrace on your screen, but a well-written message indicating that only an error occurred. All the applications are subject to failures, and because of that, application will also need treatment of these failures.

The objective of this article is to show a little more about exception handling in Java , and specifically to illustrate the difference between Checked and Unchecked exceptions.Moreover, exceptions are one of the favorite topic discussed in the java interviews.We have covered few basic articles on exception handling in the previous years, this post will be a refreshment for the new Java folks.

Checked and Unchecked Exceptions

Many a times a developer is in dilemma to understand what a checked and unchecked exception is? When to make an exception checked or unchecked? All these questions will be answered in the subsequent sections.

To describe briefly Checked exceptions are those, which you are required to treat. It is with a try-catch block or a throws (releasing the same to another location). On the other hand, when you have the type Unchecked exceptions, then it need not be treated, you can treat only if you want or feel that it is necessary for the proper operation of your application.

Checked exceptions are used for recoverable errors, while Unchecked exceptions are used for unrecoverable errors. This means that when you know that your error can be treated, you can use Checked Exceptions, otherwise use Unchecked Exceptions.

To illustrate this, imagine that you have to create a Exception called “LowestPayementValueThanShipmentRateException”, this means that when the payment amount is less than the shipping rate, you will throw an Exception and deal with the way you want. For example: Asking the user to increase payment amount. These are Checked Exceptions, you know that the error may occur and know how to fix it if it occurs.

On the other hand, imagine a NullPointerException unexpected in its application. This error can not be handled, when error occurs, you should show only a message by telling the user that the error has occurred. But nothing can be done to fix it, if not restart the whole process. These Unchecked Exceptions inherit RuntimeException, hence these exceptions occur at runtime and not at design time. When you create a block of a code that requires you to use try-catch or throws, it will be for a typical Checked Exception. Unlike Runtime Exceptions which only occur at runtime and are unexpected.

Problems in Exception Handling

Problems occurs in some cases that this pattern is not well applied, such as JDBC API. See Listing 1 in the misuse of this pattern:

Exception Handling Example Listing 1 : using JDBC exceptions

[java]

try {
PreparedStatement stmt = con.prepareStatement (query);
/ / …
} Catch (SQLException e) {

throw new DataAccessException ("Problem in creating the Statement", e);

}
[/java]

You should be familiar with using the try-catch or throws using the JDBC API, treating a SQLException. But if you think about it, the SQLException is an exception too generic and most often is unrecoverable. Imagine for example, if your database crashed, then how will you recover it? There is no way, you can only show a message to the user.

In Listing 1, we transform the “alleged” SQLException Checked as Unchecked Exception by DataAccessException that only returns a message with the error and nothing can be done. Get used to this lack of standardization, because you can find many codes applied in place of Checked and Unchecked vice versa, but knowing the concept of both, you can easily make necessary changes.

Practical Example

To understand this concept better, let us apply the concepts in a practical example, where we have the following situation: Our method attempts to write a file in a folder A, but if some error occurs an IOException (Checked Exception) is thrown and we will try to write in an Alternative folder. Why is that? Imagine that a folder in the user’s computer may be without WRITE permission, and hence not to lose the file we will write to an alternative folder that has write permissions. After we get all the files that were in the alternate folder and put them in folder A manually, but not loosing the processing.

In Listing 2 you will see the code of the case described above.

Exception Handling Example Listing 2 : Example of a real Checked Exception

[java]

private static void createFiles(String alternatePath) {
File file = null;
try {
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
if (alternatePath.equals(""))
file = new File("/home/manisha/javabeatdocs/file_"
+ fmt.format(new Date()));
else
file = new File(alternatePath + "file_"
+ fmt.format(new Date()));
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Line 001");
writer.close();
} catch (IOException e) {
if (file != null) {
if (file.exists()) {
file.delete();
createFiles("/home/manisha/alternatePath/");
}
}
}
}
[/java]

We can even improve a bit by putting one generic Exception in the code above. So anything that was not an IOException we could treat it as an Unchecked Exception, it would be an unrecoverable error and nothing we could do.

Summary

It is possible that many professionals do not know the real use of the concept described in this article, because a lot of times this goes unnoticed. But with the learning of this, it becomes much easier to understand the actual application (based on good programming practices) of exceptions.

Filed Under: Java Tagged With: Java

Dynamic Class Loading using Java Reflection

September 28, 2013 by Manisha Patil Leave a Comment

In this article we will discuss the concept of Java Reflection. Java Reflection is used to determine methods and attributes that will be used in a certain class at runtime.The Reflection in a nutshell, is used to determine methods and attributes that will be used in class (you do not know) at runtime. There are many uses for this type of task, we can mention for example the installation of additional plugins to our developed software.

Imagine if every time a new plugin was developed for the Eclipse , it had to be refactored to adapt to the use of this new plugin. It would be very laborious and impractical, given the amount of plugins that are developed for this IDE. The solution for this is undoubtedly the use of Reflection API. Say for example, strategic points of the system accept the installation of plugins in order to make the system extensible.

Reflection Example Listing 1 : Applying Reflection
[java]</div>
<div>
<pre>Class unknownClass = UnknownClass.class;
for (Field attribute: unknownClass.getDeclaredFields()) {
System.out.println (attribute.getName ());
}
[/java]

Notice in the above code we do not know methods and attributes of “UnknownClass”, for this we will use the tools offered by Reflection in order to find this information at runtime. Note that the method “getDeclaredFields” can capture all the attributes of the class in question, without knowing how it was built.

Risks of Java Reflection

This feature should be used with care, always paying attention to the possible risks that can be caused by improper use:

  • Reduction of Performance: because the code that is being executed is required very often, hence will result in a reduction of performance.
  • Problems for security restriction: especially if done in an environment with specific rules.
  • Exposure of the internal structure of objects: for using this feature we have access to all methods and attributes of the given object, this can be a problem when it comes to security.

Benefits of Java Reflection

There are also the benefits that can be availed if we use the Java Reflection correctly and appropriately.

  • Ease of maintenance
  • Minimizing Errors
  • Productivity Gain
  • Standardization
  • Extensibility

Some items are pretty obvious, such as the Productivity Gain, because it is clear that we will not need to rewrite code every time we want to add new features to our system, it is obvious that it has to be ready to receive such ” Coupling “. We consider the extensibility as one of the most important points and beneficiaries of Java Reflection.

Using Java Reflection in the correct way in our system can become more complex (in terms of features). By just adding plugins without messing with any code, it is incredible and extremely powerful.

Some known examples that use the idea of reflection to make your software extensible are tools like Hibernate, Netbeans, Eclipse and among others that enable new plugins to be installed without changing the application code page . Hibernate example uses the Java Reflection to discover fields in our class in order to create the database tables (using the auto-update = ‘true’).

Let us see an example below which creates a class file with several fields and then apply Reflection.

Reflection Example Listing 2 : Defining our Class File

[java]</div>
<div>
<pre>package net.javabeat;

public class File {
private String name;
private String numberOfCCP;
private int quantityOfCCP;
private String toHashTable;
private boolean performCheckSum;
private boolean converterHash;
private boolean combineNameNumberCCP;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNumberOfCCP() {
return numberOfCCP;
}

public void setNumberOfCCP(String numberOfCCP) {
this.numberOfCCP = numberOfCCP;
}

public int getQuantityOfCCP() {
return quantityOfCCP;
}

public void setQuantityOfCCP(int quantityOfCCP) {
this.quantityOfCCP = quantityOfCCP;
}

public String getToHashTable() {
return toHashTable;
}

public void setToHashTable(String toHashTable) {
this.toHashTable = toHashTable;
}

public boolean isPerformCheckSum() {
return performCheckSum;
}

public void setPerformCheckSum(boolean performCheckSum) {
this.performCheckSum = performCheckSum;
}

public boolean isConverterHash() {
return converterHash;
}

public void setConverterHash(boolean converterHash) {
this.converterHash = converterHash;
}

public boolean isCombineNameNumberCCP() {
return combineNameNumberCCP;
}

public void setCombineNameNumberCCP(boolean combineNameNumberCCP) {
this.combineNameNumberCCP = combineNameNumberCCP;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (combineNameNumberCCP ? 1231 : 1237);
result = prime * result + (converterHash ? 1231 : 1237);
result = prime * result
+ ((toHashTable == null) ? 0 : toHashTable.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((numberOfCCP == null) ? 0 : numberOfCCP.hashCode());
result = prime * result + quantityOfCCP;
result = prime * result + (performCheckSum ? 1231 : 1237);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
File other = (File) obj;
if (combineNameNumberCCP != other.combineNameNumberCCP)
return false;
if (converterHash != other.converterHash)
return false;
if (toHashTable == null) {
if (other.toHashTable != null)
return false;
} else if (!toHashTable.equals(other.toHashTable))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (numberOfCCP == null) {
if (other.numberOfCCP != null)
return false;
} else if (!numberOfCCP.equals(other.numberOfCCP))
return false;
if (quantityOfCCP != other.quantityOfCCP)
return false;
if (performCheckSum != other.performCheckSum)
return false;
return true;
}
}
[/java]

Note that we have everything in our class: attributes, getters, setters, hashCode and equals. Now let’s work on it and use the reflection. In the code below, you can follow what is being done step by step with the code comments that are well documented.

Reflection Example Listing 3 : Showing attributes and methods with Reflection

[java]</div>
<div>
<pre>package net.javabeat;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {

public static void main(String args[]) {

/**
* We load the class file through Class.forName which enables us to Load
* a class given by a string that must match the Local default class.
* This default class is loaded in ClassLoader which is being used by the class
* that is running the command.
**/
Object fileFromReflection = null;
try {
fileFromReflection = Class.forName("net.javabeat.File").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Retrieves the class name
System.out.println("Class Name:"
+ fileFromReflection.getClass().getName());

/*
* The Class Method of Reflection gives us the possibility to handle All
* methods within the loaded object
*/
System.out.println("");
System.out.println("Methods:");
for (Method m : fileFromReflection.getClass().getMethods()) {
System.out.println(m.getName());
}

/*
* We now capture the attributes of the class. We now have another
* important class that use Field class of Reflection. This allows us to
* Handle field / fields of our class loaded.
*/
System.out.println("");
System.out.println("Attributes:");
for (Field f : fileFromReflection.getClass().getDeclaredFields()) {
System.out.println(f.getName());
}

/*
* Note that our approach is very simple, i.e, we are only capturing the
* names of methods and attributes, but you can go much further,
* capturing the modifiers, types, return and so on.
*/

}
}

[/java]

OUTPUT:

Executing the above code gives the following output.
[java]</div>
<div>
<pre>Class Name:net.javabeat.File

Methods:
equals
hashCode
getName
setName
getNumberOfCCP
setNumberOfCCP
getQuantityOfCCP
setQuantityOfCCP
getToHashTable
setToHashTable
isPerformCheckSum
setPerformCheckSum
isConverterHash
setConverterHash
isCombineNameNumberCCP
setCombineNameNumberCCP
wait
wait
wait
toString
getClass
notify
notifyAll

Attributes:
name
numberOfCCP
quantityOfCCP
toHashTable
performCheckSum
converterHash
combineNameNumberCCP
[/java]

Summary

Reference Books:

  • Java: The Complete Reference
  • Head First Java by Kathy Sierra, Bert Bates

Reflection is useful especially when we are thinking of extensible, hence making the system able to receive new features without requiring code modification.


Filed Under: Java Tagged With: Java

Difference between ArrayList, Vector and LinkedList in Java

September 25, 2013 by Manisha Patil Leave a Comment

This is a basic tutorial explaining about the APIs define under the collection package in Java. We encounter numerous questions from our readers to clarify the differences on these interfaces, we have come up with an tutorial to explain the key differences on these APIs. ArrayList, Vector and LinkedList, these confuse many beginners and even experienced professionals who end up not knowing where to apply each of these types of lists. In fact they are all very similar, after all they implement the same interface (List). They all possess the same methods but not the same implementations of those methods. It is mainly in the performance that we can see the main difference.In the following sections we will explain how to use each of the lists and finally point out the main differences between them, which is the main objective of this article.

ArrayList

Let us start with the most known and used, ArrayList. This type of list is implemented as an array that is dynamically scaled, ie whenever it is necessary to increase its size by 50% the size of the list. Say you have a list size of 10 and its size will increase to 15 automatically when an add operation happens. Also the ArrayList allows elements to be accessed directly by the methods get () and set (), and added through add () and remove ().

Example Listing 1 : Using ArrayList

[java]
package net.javabeat;

import java.util.ArrayList;
import java.util.Iterator;

public class Main {

public static void main(String args[]) {

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(3);
al.add(2);
al.add(1);
al.add(4);
al.add(5);
al.add(6);
al.add(6);

Iterator<Integer> iter1 = al.iterator();
while (iter1.hasNext()) {
System.out.println(iter1.next());
}
System.out.println("**************");
System.out.println(al.get(2));

}

}
[/java]

If you run the above code the output would be:

[java]

3
2
1
4
5
6
6
**************
1
[/java]

In the above code we notice that the ArrayList does not remove duplicate elements, and we can still access any element directly through its index, but everything has a cost and which we will see later.

ArrayList starts with a fixed size, which increases as needed, but the cost of this increase is high, because a copy is made of the current array to a new array with a new size, then imagine an array with 10 million elements that will be copied to a new array to create only 5000 elements? Indeed it is a high cost. So it is highly advisable that you start your Array with a number of elements that suits your current goal, without the need for dynamic creation of new spaces, or if you know you’ll have to store 300-400 objects in an Array , set 500.

There is a further very important point about ArrayList: These are not synchronized, hence are not thread-safe, ie, if your application needs to work as thread-safe at some point where a list is required, then discard ArrayList unless you take care of thread safety explicitly, which is obviously not correct way of doing.

Vector

From the point of view of API, or the way it is used, ArrayList and Vectors are very similar, you can say they are same. If you do not know in depth the concept of Vector and ArrayList both are used as if they were the same. See in Listing 2 is an example of that.

Example Listing 2 : Using Vector

[java]
package net.javabeat;

import java.util.Iterator;
import java.util.Vector;

public class Main {

public static void main (String args []) {

Vector<Integer> al = new Vector<Integer> ();
al.add (3);
al.add (2);
al.add (1);
al.add (4);
al.add (5);
al.add (6);
al.add (6);

Iterator<Integer> iter1 = al.iterator();
while (iter1.hasNext ()) {
System.out.println (iter1.next ());
}
System.out.println("**************");
System.out.println (al.get (2));

}
}

[/java]

If you run the above code the output would be:

[java]

3
2
1
4
5
6
6
**************
1
[/java]

You can see that in Listing 2: we have used the same structure as in Listing 1, changing only the list of ArrayList to Vector, but the rest of the code remains the same, and the output will also be identical.

So what is the difference between Vector and ArrayList?

  • First let’s talk about the fact that Vector is synchronized and ArrayList is not. This means that if you have an application that needs to be thread-safe at some point, use Vector and you will be guaranteed of thread safety.
  • Another important point is the dynamic allocation of the Vector, which is different from the ArrayList. Remember we talked about the 50% of the ArrayList increases its size when the list is full? The Vector increases twice, ie if you have a full list of 10 elements, this list will increase to 20, with 10 empty positions. But is this not bad? Depends on what you need if you want to increase the amount of elements very often, so it is ideal to use the Vector as it increases the size two times and you will get much more space than the ArrayList that need to be increased more frequently, hence reducing the performance of your application.

LinkedList

Before starting the explanations we will show a use of LinkedList and you will notice that is identical to an ArrayList.

Example Listing 3 : Using LinkedList

[java]
import java.util.Iterator;
import java.util.LinkedList;

public class Main {

public static void main (String args []) {

LinkedList ll = new LinkedList ();
ll.add (3);
ll.add (2);
ll.add (1);
ll.add (4);
ll.add (5);
ll.add (6);
ll.add (6);

Iter2 ll.iterator iterator = ();
while (iter2.hasNext ()) {
System.out.println (iter2.next ());
}

}

}
[/java]

If you run the above code the output would be:

[java]
3
2
1
4
5
6
6
[/java]

This type of list implements a double linked list, or a list doubly “linked”. The main difference between LinkedList and ArrayList is in performance between the methods add, remove, get and set.

This kind of list has better performance in the add and remove methods, than the methods that add and remove from the ArrayList, instead its get and set methods have a worse performance than the ArrayList. Let us see a comparison between each of the methods present in ArrayList and LinkedList:

  • get(int index): method in LinkedList has O (n) and the method in ArrayList has O (1)
  • add (E element): method in LinkedList has O (1) and method in ArrayList has O (n) in the worst case, since the array will be resized and copied to a new array.
  • add (int index, E element): method in LinkedList has O (n) and method in ArrayList has O (n) in the worst case.
  • remove (int index): method in LinkedList has O (n) and method in ArrayList has O (n-index), remove the last element then O (1).

Notice that the main difference is in the performance, and a thorough analysis should be made in cases where performance is critical.

Reference Books:

  • Java: The Complete Reference
  • Head First Java by Kathy Sierra, Bert Bates  

We have talked so much about performance difference between LinkedList and ArrayList, let’s see this in practice, which is faster at what times, so check the listing below.

Example Listing 4 : Performance comparison between LinkedList and ArrayList

[java]
package net.javabeat;

import java.util.ArrayList;
import java.util.LinkedList;

public class Main {

public static void main(String args[]) {

ArrayList<Integer> arrayList = new ArrayList<Integer>();
LinkedList<Integer> linkedList = new LinkedList<Integer>();

// Add ArrayList
long startTime = System.nanoTime();

for (int i = 0; i < 100000; i++) {
arrayList.add(i);
}
long endTime = System.nanoTime();
long duration = endTime – startTime;
System.out.println("ArrayList add:" + duration);

// Add LinkedList
startTime = System.nanoTime();

for (int i = 0; i < 100000; i++) {
linkedList.add(i);
}
endTime = System.nanoTime();
duration = endTime – startTime;
System.out.println("LinkedList add:" + duration);

// Get ArrayList
startTime = System.nanoTime();

for (int i = 0; i < 10000; i++) {
arrayList.get(i);
}
endTime = System.nanoTime();
duration = endTime – startTime;
System.out.println("ArrayList get:" + duration);

// Get LinkedList
startTime = System.nanoTime();

for (int i = 0; i < 10000; i++) {
linkedList.get(i);
}
endTime = System.nanoTime();
duration = endTime – startTime;
System.out.println("LinkedList get:" + duration);

// ArrayList removes
startTime = System.nanoTime();

for (int i = 9999; i >= 0; i–) {
arrayList.remove(i);
}
endTime = System.nanoTime();
duration = endTime – startTime;
System.out.println("ArrayList remove:" + duration);

// Remove LinkedList
startTime = System.nanoTime();

for (int i = 9999; i >= 0; i–) {
linkedList.remove(i);
}
endTime = System.nanoTime();
duration = endTime – startTime;
System.out.println("LinkedList remove:" + duration);

}
}
[/java]

OUTPUT

[java]
ArrayList add:18482391
LinkedList add:15140237
ArrayList get:2558084
LinkedList get:87518301
ArrayList remove:229680490
LinkedList remove:83977290
[/java]

Summary

  • Difference between JVM, JRE and JDK
  • Conversion between list and array types
  • Annotations in Java 5.0
  • G1 Garbage Collector in Java 7.0

This article highlighted about the similarities and differences between the list types: ArrayList, Vector and LinkedList. We also discussed with example the performance of the code with the use of each of these types. Hope you liked this article.

Filed Under: Java Tagged With: Java

Design Patterns in Java

September 25, 2013 by Manisha Patil Leave a Comment

In developing a system, it is expected that some requirements are guaranteed, for example, performance, robustness, understanding, ease of reuse, modification, and use. The Design Patterns were created by the architect Christopher Alexander , in the 1970s. During this period the architect wrote two books: “Pattern Language” and “Timeless Way of Building“. These books were an example of how Christopher thought in order to document these patterns.

If you are interested in receiving updates, please subscribe our newsletter.

In 1995, the professionals: Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides , wrote and released the book called “Design Patterns: Elements of Reusable Object-Oriented Software”, which shows the details of the 23 Design Patterns. For this achievement, the professionals were baptized with the name “Gang of Four” (Gang of Four or GoF).

Design Patterns in Java

The goal of design patterns are:

  • Reusable components that make it easy to standardize.
  • Enabling agile solutions for recurring problems in developing the system.

There are two design patterns known to software engineering. Those are:

  • Standard GoF (Gang of Four) patterns
  • GRASP (General Responsibility Assignment Software Patterns).

History of Design Patterns

GRASP Design Patterns

  • Design Pattern Interview Questions

These patterns consists of guidelines for assigning responsibility to classes and objects in object-oriented design. The different patterns and principles and standards used in GRASP  design patterns are:

  • Specialist in information
  • Creator
  • Controller
  • Weak coupling
  • High Cohesion
  • Polymorphism
  • Pure Fabrication
  • Indirection
  • Protected Variations

GoF Design Patterns

These patterns consist of three groups as shown below:

  • Creational Patterns
    • Factory Method
    • Abstract Factory
    • Singleton, Builder
    • Prototype
  • Structural Patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioral Patterns
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template
    • Method
    • Visitor.

GoF Design Patterns of Creation

Creational Design Patterns

The patterns of this type require a treatment of how objects (classes) are created to meet the diverse needs. In Java, objects are instantiated through their builders, but the use of them is limited when:

  • The code that references the creation of an object needs to know the builders of it, it increases the coupling of classes.
  • The object can not be created partially.
  • The builder can not control the number of instances in the present application.

Illustrative pattern

Figure 1 : Illustration of the figurative Pattern GoF Creation

  • Factory Method : This standard defines an interface for creating an object, letting the subclasses remain responsible for deciding which class to instantiate.
  • Abstract Factory : Allows you to draw an interface for creating families of related objects or interdependent, not specifying their concrete classes. These standards can be created using concrete factories, which are responsible for the creation of new objects to meet customer needs. Therefore, this practice helps to exclude the dependency between the client and the class of objects used by the client.
  • Singleton : Used when desired, that a class has only one instance of the application. Below are some aspects that should be taken care of when creating this pattern:
  • The class is final, it does not allow the creation of subclasses of the class itself.
  • Access is granted through the method that returns a single instance of the class, or is creating one, if it has not been created.
  • Builder : Provides a generic interface for the incremental construction of aggregations. This pattern hides the details of how the components are created, composed and represented.
  • Prototype : Defines the types of objects to be created from an instance that serves as a prototype. New objects are created based on this prototype.

GoF Structural Design Patterns

Structural Design Pattern in Java

This standard describes the following aspects: preparation, organization and association between objects and classes / interfaces. Allows to combine objects into more complex structures, or describe how the classes are inherited or composed from other.

gofstructure

Figure 2 : Illustration GoF Structural Pattern

  • Adapter : The action of this pattern converts the interface of a class into another, expected by the client object. Through this conversion, allows classes with incompatible interfaces, able to be adapted so that other objects can work together.
  • Bridge : This pattern separates an abstraction from its implementation, allowing both to work independently, and establishes a bridge between them.
  • Composite : Consisting of objects aggregation trees. Aggregate objects are treated as a single object.
  • Decorator : This standard seeks to offer a flexible alternative to extension object dynamic new features, without the use of inheritance. An example is the use of the scroll bar that can be incorporated dynamically to a window, text box or web page.
  • Facade : Provides a unified interface to a set of objects that consists of a subsystem, defining a high-level interface that facilitates the use.
  • Flyweight : Use sharing to support efficiently to a large number of objects with high level of granularity. This pattern creates models for each object, which concentrates all the common features of an object.
  • Proxy : Allows access is controlled by another object, which acts as a substitute. Generally used in aspect-oriented programming, aiming to help sort, wrap, modularizing methods and organize code according to importance.

GoF Behavioural Patterns

Behavioural Design Pattern in Java

These patterns show the process of how objects or classes communicate. In general, look for a loose coupling between objects, although the communication that exists between them.

gofbehaviour

Figure 3 : Illustration of GoF Behavioral Pattern

  • Chain of Responsibility : This design pattern consists of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
  • Command : encapsulates a message or request as an object, so that it can set parameters with different messaging clients.
  • Interpreter : Are representations and abstractions for grammars for parsing, being used for more language definition.
  • Iterator : Used to provide a way to access elements of a collection of objects sequentially without exposing the internal structures.
  • Mediator : This pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior.
  • Memento : Works as a “snapshot”, it captures and externalizes the internal state of an object without violating encapsulation, allowing the object can be restored to this state in the future. One example is operations that need to be reversed, so that the previous state of the object is then restored.
  • Observer : Used to synchronize, coordinate and maintain consistency between related objects which have one to many dependency between objects, ie, when the state of an object changes, all dependents are notified and updated automatically.
  • State : This patter encapsulates varying behavior for the same routine based on an object’s state object. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements.
  • Strategy : Defines a new set of algorithms without changing the classes of the elements on which it operates.
  • Template Method : This pattern defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.
  • Visitor : It is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.

Summary

  • Design pattern interview questions

In this article, we saw types of design patterns GoF patterns and GRASP. We also saw further categorization in each of these patterns. This article aims at giving a basic knowledge of design patterns. With this basic knowledge you can proceed to understand each of these patterns better and implement in your day to day software applications.

Filed Under: Java Tagged With: Design Patterns

ClassLoader in Java

September 24, 2013 by Manisha Patil Leave a Comment

In this article we will understand the basics of Classloader in Java. Let us first understand what is the meaning of classloader.

What is the ClassLoader ?

As its name implies, ClassLoader is a class that loads other classes. More scientific: The Classloader loads the bytecodes in its class to memory, so it can be used throughout your application. The ClassLoader is in the java.lang.ClassLoader package. Understanding the classloader is important for working on the server development or any product developments which is more often design the custom classloaders to load the classes.

You would have come across the ClassNotFoundExecption  many times while you are writing Java programming. Classloader is the culprit which causes this exception.

Why do we need the ClassLoader ?

The class loading mechanism allows us to have multiple classes with the same name (exactly the same) but different class loaders. This is what happens for example in web containers today, where we have several different applications but it can happen that one or two classes have the same name, this will not cause any conflict.

Let’s dive deeper into this concept. As we said earlier, everything in Java is loaded by class loaders specific (which will be explained later). So you may ask: If everything is loaded by a ClassLoader and ClassLoader itself is a class that must also be loaded, then who carries the first ClassLoader to load other classes? to solve this problem the “Bootstrap ClassLoader” which is written in native language, is loaded by JVM. It is responsible for initializing the packages essential to run the language pack as the “rt.jar”. Bootstarap classloader is a native implementation. So, it could be different for each JVM implementation.

So if the java classes are loaded dynamically (through the ClassLoader) can I replace the code of a class and load it at runtime? Yes you can. You can still load remote class through any URL at runtime.

Exemplifying the Java ClassLoader

Before jumping into the workings of each ClassLoader in native Java, we have to understand why its use has become so necessary.

The ClassLoader by default loads all classes that are present in your CLASSPATH, so in this case you do not even know the existence of this loading mechanism. Classes are identified by its fully qualified name + class loader that loaded it, so we are sure of a one Class Employee Application 001 is different from the class Employee Application 002.

The use of class loaders is useful, for instance, when working with various versions of applications with different libraries. Ex: Suppose, the application 001 can work with version 3.6 of Hibernate while the application 002 works with the version 3.3. If they were working in the same class loader then there would have been conflicts in classes as org.hibernate.Session will be loaded twice in memory.

Listing 1 : Class Loading

[java]

R = Class loadClass (String className, boolean resolveIt);

[/java]

In the above code, the parameter className is the absolute name of the class, ie, the full name of the package path (net.javabeat.MyClass). The boolean parameter resolveIt says the classes associated with our loaded class, should also be loaded as if it were a cascade of loadings.

ClassLoader Engine

We have 3 types of ClassLoaders, they are:

  • Bootstrap ClassLoader
  • ClassLoader Extension
  • Application ClassLoader

Each of these have their respective function which will be explained in the following sections.

Bootstrap ClassLoader : This is responsible for loading classes from rt.jar and has no parent, this is the father of all others. Therefore, ensure that nobody will modify the rt.jar classes. For example: the package java.lang.

Extension ClassLoader : This is responsible for loading JARs that are within the property java.ext.dirs directory, by default this directory is: $ JAVA_HOME / lib / ext. Bootstrap ClassLoader is the parent classloader for this.

Application ClassLoader : This, is no less important and is responsible for loading all classes in your application, ie, sets your CLASSPATH. Extension ClassLoader is the parent classloader. For a complete example of loading a class dynamically through loadClass, see the listing below.

Listing 2 : Loading Class

[java]
public class Main extends ClassLoader {
public static void main (String [] args) {
ClassLoader classloader = Principal.class.getClassLoader ();
try {
Class aClass = classLoader.loadClass ("AnotherClass");
System.out.println ("aClass.getName () =" + aClass.getName ());
} Catch (ClassNotFoundException e) {
e.printStackTrace ();
}
}
}
[/java]

The output of the above code will be something like: “aClass.getName () = AnotherClass”.

Well, let’s now create our own ClassLoader, whose main method the “loadClass” which is responsible for loading the class we want.

Listing 3 : Creating our own ClassLoader

[java]</span>
<pre>package net.javabeat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MyClassLoader extends ClassLoader {

public MyClassLoader(ClassLoader parent) {
super(parent);
}

public Class loadClass(String name) throws ClassNotFoundException {
if ("reflection.MyObject".equals(name))

return super.loadClass(name);

try {
String url = ""
+ "Classes / reflection / MyObject.class";
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();

while (data != -1) {
buffer.write(data);
data = input.read();
}

input.close();

byte[] classData = buffer.toByteArray();

return defineClass("reflection.MyObject", classData, 0,
classData.length);

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
}

[/java]

We see the following in the above code:

  • The class is loaded using reflection inside the package and have the name MyObject.
  • Use a URL to load this class, otherwise pass the responsibility to the parent ClassLoader.

Let’s now create a main method that uses our ClassLoader.

Listing 4 : Using our ClassLoader

[java]

package net.javabeat;

public class Main extends ClassLoader {
public static void main(String[] args) throws ClassNotFoundException,
IllegalAccessException, InstantiationException {

ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();
MyClassLoader classLoader = new MyClassLoader(parentClassLoader);
Class myObjectClass = classLoader.loadClass("reflection.MyObject");

AnInterface2 object1 = (AnInterface2) myObjectClass.newInstance();

MyObjectSuperClass object2 = (MyObjectSuperClass) myObjectClass
.newInstance();

// Create new class loader so that the classes can be reloaded.
classLoader = new MyClassLoader(parentClassLoader);
myObjectClass = classLoader.loadClass("reflection.MyObject");

object1 = (AnInterface2) myObjectClass.newInstance();
object2 = (MyObjectSuperClass) myObjectClass.newInstance();

}
}

[/java]

Let us understand the workings of the code above:

  • First grab the ClassLoader ie the ClassLoader parent of our (MyClassLoader).
  • Then we create an instance of our ClassLoader parent passing it as a parameter, so it can function loadClass delegate to the parent if needed.
  • Load the class reflection.MyObject in our new ClassLoader (remember this time it will load a specific URL that is different from our CLASSPATH)
  • We now have a class loaded into a classloader of our own, we can now re-run the same class, using a ‘loadClass “.

Summary

  • How to check Java compiler version?

Creating your own ClassLoader is a very rare scenario, in fact you may never need to work with it directly. But understanding its usefulness as a whole is essential and knowledge of this is a difference for sure. You can solve problems like NoClassDefFoundError in a short time, just knowing the basic principle of how the ClassLoader works for example in scenarios where a class can exist physically, but in another ClassLoader that is not your application.

This article aims at helping you understand the classloader concepts even though you may not necessarily write your own classloader anytime.

Reference Books:

  • Java: The Complete Reference
  • Head First Java by Kathy Sierra, Bert Bates  

Filed Under: Java Tagged With: Java

Creating Pie Chart Using CSS3 and HTML

September 18, 2013 by Manisha Patil Leave a Comment

In this article I will discuss how to create a pie chart using just CSS3. With the success of new technologies, we see that things that previously required external factors, being made ​​directly with CSS and HTML. CSS3 is the latest standard for CSS. CSS3 coding is always backwards compatible, if you write an application with CSS3, it will also run in the CSS2. In this article we will see how to create pie charts using CSS3 .

  • CSS Z-Index example
  • New Features in CSS 3.0
  • Buy : HTML 5 and CSS3

Graphs can be represented in two ways:

  • Bar Chart (Bar Chart Using DOJO)
  • Pie chart (Pie Chart Using DOJO)

css3

Pie charts have become an essential means for representing the data to any audience. Graphical representation of data serves to introduce very few facts in front of any audience. There are many examples where pie charts are used and these charts show lot of meaning. Some of examples of pie charts are:

  • Representing the number of seats of each political group.
  • Representing the sales performance of each department in an organization.
  • Representing the marks obtained by a student in an exam.
  • Representing the number of users of a particular product in different geographical locations.

Pie charts can be created in the follwoing ways:

  • Cascading Style Sheets and HTML
  • Jquery and Ajax

Here I shall discuss only about creating Pie Chart using CSS and HTML.

Creating Pie Charts using CSS3

To draw a pie chart , the first thing we need to do is draw a circle. To create a circle border that adds just one radius value which is half a pixel width of a div. Below is the css code for creating the circle.

Code for creating CSS Circle

[java]
<html>
<head>
<style>
.pieContainer {
height: 100px;
}
.pieBackground {
background-color: gray;
position: absolute;
width: 100px;
height: 100px;
-Moz-border-radius: 50px;
-Webkit-border-radius: 50px;
-O-border-radius: 50px;
border-radius: 50px;
-Moz-box-shadow:-1px 1px 3px #000;
-Webkit-box-shadow:-1px 1px 3px #000;
-O-box-shadow:-1px 1px 3px #000;
box-shadow:-1px 1px 3px #s000;
}
</style>
</head>
<body>
<div class="pieContainer">
<div class="pieBackground"></div>
</div>
</body>
</html>
[/java]

img1
The above code creates a basic circle. This can be used as background of the chart. Once the basic circle is created, we will then create a half circle using the clipping feature in order to hide the remaining half circle. This will create a slice. This slice would be exactly 50% of the circle. If you want a different size, you can change the size of the circle, by including it inside a div that controls rotation and uses an inner div to adjust the size.
Let’s start the outer div to the first slice at 0 degrees, which is the default starting point. The following code creates a circle first and then creates a small section of this circle with a different color:

Creating a circle and then a short section on it

[java]
<!DOCTYPE html>
<html>
<head>
<title>Pizza Graph </title>
</head>

<body>
<style>
.pieContainer {
height: 100px;
}
.pieBackground {
background-color: gray;
position: absolute;
width: 100px;
height: 100px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
-o-border-radius: 50px;
border-radius: 50px;
-moz-box-shadow:-1px 1px 3px #000;
-webkit-box-shadow:-1px 1px 3px #000;
-o-box-shadow:-1px 1px 3px #000;
box-shadow:-1px 1px 3px #000;
}
.pie {
position: absolute;
width: 100px;
height: 100px;
-Moz-border-radius: 50px;
-Webkit-border-radius: 50px;
-O-border-radius: 50px;
border-radius: 50px;
clip: rect (0px, 50px, 100px, 0px);
}
.hold {
position: absolute;
width: 100px;
height: 100px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
-o-border-radius: 50px;
border-radius: 50px;
clip: rect (0px, 100px, 100px, 50px);
}
#pieSlice1 .pie {
background-color: #1b458b;
-webkit-transform:rotate(50deg);
-moz-transform:rotate(50deg);
-o-transform:rotate(50deg);
transform:rotate(50deg);
}

</style>
<body>
<div class="pieContainer">
<div class="pieBackground"></div>
<div id="pieSlice1" class="hold">
<div class="pie"> </div>
</div>
</div>
</body>
</html>
[/java]

img2
Since we are forced to create multiple slices , we just need to continue to add more equal slices with multiple colors. The following code shows how to create multiple slices in a circle:

Code to create multiple slices of the pie chart

[java]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> Pie </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>

<body>
<style>
.pieContainer {
height: 100px;
}
.pieBackground {
background-color: grey;
position: absolute;
width: 100px;
height: 100px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
-o-border-radius: 50px;
border-radius: 50px;
-moz-box-shadow: -1px 1px 3px #000;
-webkit-box-shadow: -1px 1px 3px #000;
-o-box-shadow: -1px 1px 3px #000;
box-shadow: -1px 1px 3px #000;
}
.pie {
position: absolute;
width: 100px;
height: 100px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
-o-border-radius: 50px;
border-radius: 50px;
clip: rect(0px, 50px, 100px, 0px);
}
.hold {
position: absolute;
width: 100px;
height: 100px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
-o-border-radius: 50px;
border-radius: 50px;
clip: rect(0px, 100px, 100px, 50px);
}

#pieSlice1 .pie {
background-color: #1b458b;
-webkit-transform:rotate(150deg);
-moz-transform:rotate(150deg);
-o-transform:rotate(150deg);
transform:rotate(150deg);
}
#pieSlice2 {
-webkit-transform:rotate(150deg);
-moz-transform:rotate(150deg);
-o-transform:rotate(150deg);
transform:rotate(150deg);
}
#pieSlice2 .pie {
background-color: #ccbb87;
-webkit-transform:rotate(40deg);
-moz-transform:rotate(40deg);
-o-transform:rotate(40deg);
transform:rotate(40deg);
}
#pieSlice3 {
-webkit-transform:rotate(190deg);
-moz-transform:rotate(190deg);
-o-transform:rotate(190deg);
transform:rotate(190deg);
}
#pieSlice3 .pie {
background-color: #cc0000;
-webkit-transform:rotate(70deg);
-moz-transform:rotate(70deg);
-o-transform:rotate(70deg);
transform:rotate(70deg);
}
#pieSlice4 {
-webkit-transform:rotate(260deg);
-moz-transform:rotate(260deg);
-o-transform:rotate(260deg);
transform:rotate(260deg);
}
#pieSlice4 .pie {
background-color: #cc00ff;
-webkit-transform:rotate(100deg);
-moz-transform:rotate(100deg);
-o-transform:rotate(100deg);
transform:rotate(100deg);
}
</style>

<div class="pieContainer">
<div class="pieBackground"></div>
<div id="pieSlice1" class="hold"><div class="pie"></div></div>
<div id="pieSlice2" class="hold"><div class="pie"></div></div>
<div id="pieSlice3" class="hold"><div class="pie"></div></div>
<div id="pieSlice4" class="hold"><div class="pie"></div></div>
</div>
</body>
</html>
[/java]

CSS3 Pie Chart

Summary

  • CSS Z-Index example
  • New Features in CSS 3.0
  • Buy : HTML 5 and CSS3

The use of graphics is very important when we want to generate a report for a client, or simply want to display certain information to the users of our website. To summarise what we have discussed,

  • Pie chart is an important tool used to represent statistical data,
  • Pie charts are useful as it is easy to represent and understand pictorial data,
  • Pie charts can be created dynamically using CSS, HTML, AJAX and Jquery.

If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Filed Under: HTML Tagged With: CSS3

Transaction Control Using Annotations in Spring Framework

September 2, 2013 by Manisha Patil Leave a Comment

In this article I’ll discuss the use of the Spring Framework Transactions, to make the application more secure and without inconsistencies. But before you initiate a transaction in Spring, let’s first understand what are transactions. The transaction concept can be described with the acronym ACID. 1. Atomicity:- A transaction must be treated as a single operation, this means that all commands in this transaction can be completed successfully or unsuccessfully. Nothing will be saved if at least one command 100 goes wrong, everyone should run successfully without errors. 2. Consistency: This is the consistency of integrity of the database, they are: unique and primary keys etc. 3. Isolation: Many transaction can be executed at the same time, the insulation ensures that each transaction is isolated from the other, thereby preventing data corruption. 4. Durability: A transaction should continue after being persisted and can not be deleted by system failures.

Transactions with Spring Framework

Once you understand the concept, we should also keep in mind that there are two ways to work with transactions in an application: Programmatically or  Declaratively. Working Programmatically brings immense flexibility to manage their transactions, but the maintainability of the code becomes difficult and costly. On the other hand, working Decoratively is more stylish and follows good programming practices, since you’ll be separating completely the control of transaction of business rules. When it comes to Spring Framework you can work decoratively via XML or annotations, but in this article we will focus on the notes.

spring framework

Before you start using the transactions you need to tell Spring that you want to perform a transaction control via annotations, this is done through configuration shown in Listing 1 in the file applicationContext.xml.

Listing 1 : Enabling transactions via annotations in applicationContext.xml

[java]
<tx:annotation-driven transaction-manager="transactionManager"/>
[/java]

After this you will be able to use annotation @Transactional in order to define a particular method that should be within a transaction.

Isolation

The first parameter is Isolation, this can be defined as follows:

Listing 2 : Isolation Level

[java]
@ Transactional (isolation = Isolation.READ_COMMITTED)
[/java]

The possible types of isolation are:

  • ISOLATION_DEFAULT: Isolation level standard.
  • ISOLATION_READ_COMMITTED: Prevents just “dirty reads”.
  • ISOLATION_READ_UNCOMMITED: Indicates “dirty reads”, “non-repeatable reads” and “Phatom reads” may occur, or will not be prevented.
  • ISOLATION_REPEATABLE_READ: Prevents just “dirty reads” and “non-repeatable reads.”
  • ISOLATION_SERIALIZABLE: Prevents “dirty reads”, “non-repeatable reads” and “Phatom reads.”

My focus is not to teach the background operation of transaction, but only how its applied to Spring. I will briefly explain types of readings prevented in Isolation.

  • Dirty Read : This occurs when a transaction writes an X value and a transaction value B read this without having done the transaction commit or rollback the transaction. The case of a transaction rollback, the value of the transaction B read becomes invalid.
  • Non-repeatable read : Occurs when a single transaction in a line is read twice and the values ​​of these two readings are different.
  • Read Phatom : This occurs when two similar queries are executed and the result of the latter is different from the first.

Defining Propagation

Another very important parameter to be defined in a transaction in Spring is how transaction will be held. Here are the possible ways of propagation:

  • PROPAGATION_MANDATORY: Forces the use of a transaction, if there is no current transaction, an exception is thrown.
  • PROPAGATION_NESTED: Execute within a nested transaction if a current transaction exists.
  • PROPAGATION_NEVER: Prevents the use of a transaction. If there is a current transaction, an exception is thrown.
  • PROPAGATION_NOT_SUPPORTED: It uses the current transaction. This always runs with no transaction.
  • PROPAGATION_REQUIRED: Uses the current transaction if exists does not exist creates a new transaction.
  • PROPAGATION_REQUIRES_NEW: Creates a new transaction, if there is already a current stops this.
  • PROPAGATION_SUPPORTS: Uses the current transaction if one exists, otherwise executes without transaction.

There is a parameter “readOnly” in the @Transactional annotation. This specifies that no operation can be performed like DML (Insert, Update or Delete), ie only queries can be performed.

In Listing 3 we have defined a class that uses Spring’s transaction control, this uses a readOnly = false and PROPAGATION_REQUIRED, so always ensure that the Save method will run within a transaction.

Listing 3 : Using @Transactional practice

[java]
@ Repository
public class implements ProductDAOImpl ProductDAO {
private SessionFactory sessionFactory;

@ Autowired
public ProductDAOImpl (SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

private Session currentSession () {
sessionFactory.getCurrentSession return ();
}

@ Override
@ Transactional (propagation = Propagation.REQUIRED, readOnly = false)
public void save (ProductTech product) {
currentSession (.) save (product);
System.out.println ("product saved with sucess");
}
}
[/java]

The other annotations such as @Autowired and @Repository settings are also Spring annotations, which will not be focused in this article. As you can see in the “save” method we have defined the transaction as PROPAGATION_REQUIRED, therefore if we had 10 saves in the save, everyone should be required to succeed in their implementation, otherwise a rollback would be done.

Summary

Reference:

  • Managing transactions in EJB 3.0
  • Spring Auto scanning components
  • Introduction to Java Persistence API(JPA)

This article aims at practical use and fast Transaction, once you finish this reading you are able to use this feature of Spring. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Filed Under: Spring Framework Tagged With: Spring Annotations

Border Radius, Box Shadow and Border Image in CSS3

September 1, 2013 by Manisha Patil Leave a Comment

In this article we will see the properties border radius, box shadow and border image in CSS3 visual effects, which can be applied to the edges of the elements of web pages. At the end of this article, the reader should be able to understand and be able to use the properties border-radius, box-shadow and border-image, introduced in version 3 of CSS. Note that these properties are available from the CSS 3.

Many people still do not know how it is possible to create box with rounded corners, use shading effects without using any kind of image, with only CSS3. You can also get a beautiful edge made in your favourite image editor such as Photo shop, and use it on your site as the edge of something.

Working with Borders in CSS3Until the release of its latest version of the style sheets, applying effects on the edges of the elements was a pretty tiring and unproductive task. For example, to obtain an element with rounded edges, it was necessary to create multiple images to dispose them at each corner of the element.
An example of this is shown in Figure 1.

Scheme rounded edges with images
Figure 1: Scheme rounded edges with images

In the example above, we see, eight images were needed to form the edges of the central element. As outlined below, the border-radius property allows to do the same thing in a more practical and more particularly correct way. Using CSS, it will be necessary requests to the server to get images to form the layout element.

  • CSS Z-Index example
  • New Features in CSS 3.0

Border Radius in CSS3

As the name suggests, this property defines a rounded edge according to the supplied value, which indicates the radius of a circle theoretically positioned at the verticals of the element and from which you get the desired effect. The setting can be a bit tricky, but we’ll see the idea illustrated in the following figures, facilitating the understanding.

Radius of a circle - CSS3
Figure 2: Radius of a circle

First it is necessary to understand the concept of radius of the circle, which can be defined as a line segment that connects the centre of circle to its edge. As the circumference is a symmetrical figure in two dimensions, one can say that any line segment that connects its centre to its edge will have the same length, which is equal to the radius. Figure 2 illustrates the concept of lightning.

How do we apply this to the definition of the rounded edge with CSS? Suppose we define the property border-radius of a div equal to 25px. The design of the edge is done by placing a circle of radius 25px at the extreme ends, the upper and lower right and left split, as shown in Figure 3.

CSS3BorderRadius03
Figure 3: Circles basis for the rounded edge

The end result would then be that shown in Figure 4.

Element with rounded edges
Figure 4: Element with rounded edges

It is clear that in day-to-day activity we do not stick to do all this graphical analysis, however, it is important to know exactly what we are doing when we use a certain feature. The border-radius property can be defined in two ways: by setting a single value for all vertices (points) individually or by specifying the value of each vertex. The following lists exemplify the use of each of these forms.

Listing 1: Definition of general border-radius

[java]
<html>
<head>
<title> Working with Borders in CSS3 </title>
<style>
#div1{
width: 100px;
height: 100px;
border: 1px solid;
border-radius: 20px;
}
</style>
</head>
<body>

<div id="div1">General</div>

</body>
</html>
[/java]

Listing 2: Definition of individual border-radius

[java]
<html>
<head>
<title> Working with Borders in CSS3 </title>
<style type="text/css">
#div1 {
width: 100px;
height: 100px;
border: 1px solid;
border-radius: 0px 20px 0px 20px;
}
</style>
</head>
<body>
<div id="div1">Individual</div>
</body>
</html>
[/java]

The results are shown in Figure 5.

Examples of using the border-radius
Examples of using the border-radius
 Figure 5: Examples of using the border-radius
Figure 5: Examples of using the border-radius

The definition of individual values, the order of the vertices is as follows:

  • Upper left
  • Top right
  • Bottom left
  • Bottom right

Pretty simple, isn’t it? And we have the good news that this property is supported by all major browsers today.

Box Shadow in CSS3

Another effect that some time back needed some images to be obtained is the shading. This property consists of some parameters and their usage syntax is as follows:

[java]box-shadow: h v-shadow-shadow blur spread color inset;[/java]

where

  • h-shadow: horizontal position of the shadow.
  • v-shadow: vertical position of the shadow.
  • Blur: Sets the intensity of the blur (blur) the shadow (optional).
  • spread: the size of the shadow (optional).
  • color: the color of the shadow.
  • inset: whether a shadow is external (default) or internal (inset).

Listing 3 shows an example of using the box-shadow and then the result of the same.
Listing 3: Example of using box-shadow

[java]
<html>
<head>
<title> Working with Borders in CSS3 </title>
<style type="text/css">
#div1 {
width: 100px;
height: 100px;
border: 1px solid;
box-shadow: 10px 10px 10px 5px black;
}
</style>
</head>
<body>
<div id="div1"/>
</body>
</html>
[/java]

Figure 6: Div with box-shadow set
Figure 6: Div with box-shadow set

This property is also supported by major browsers

Border Image in CSS3

The last but not least we will see is the property border-image, which allows you to set an image to be used to fill the border of an element.

Unfortunately this property is not supported by Internet Explorer, and requires the use of prefixes for different browsers, as we shall see in Listing 4.
Listing 4: Example of using border-image

[java]
<html>
<head>
<title> Working with Borders in CSS3 </title>
<style type="text/css">
#div1 {
width: 100px;
height: 100px;
border-width: 10px;
border-image: url(borderimage.jpg) 30 30 repeat;
-moz-border-image: url(borderimage.jpg) 30 repeat 30; /*Firefox */
-webkit-border-image: url(borderimage.jpg) 30 repeat 30; /*Safari and Chrome*/
-o-border-image: url(borderimage.jpg) 30 repeat 30; /*Opera*/
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
[/java]

The parameters used in defining the image path, the dimensions of the edge and style, which can be strech or repeat. The first style “stretching” the image is used to fill the entire element at once, while the latter repeats the image to fill the entire edge, as can be seen in Figure 7.

 Figure 7: Border-image stretch and repeat
Figure 7: Border-image stretch and repeat

Summary

References:

  • Video : CSS3 Border Images
  • Mozilla Developer Network Tutorial
  • CSS Tip: Better Rounded Borders

CSS3 has made impossible things possible and simple. The results that were previously only obtained from the use of images and a considerable amount of code, with CSS3 it has eased the work of web designers. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Filed Under: CSS Tagged With: CSS3

Dependency Management with JNDI

August 29, 2013 by Manisha Patil Leave a Comment

In this article we will see an introduction to dependency management through JNDI (Java Naming and Directory Interface). We will see how to name resources with annotations and how to search dependencies are created. Furthermore, we see examples of using JNDI API and alternatives to search certain components.

The business logic of an application is not always independent, our implementation often depends on other resources that are in the application server such as JDBC, JMS, Session Bean and Entity Manager.

JNDI

What is JNDI?

To manage these dependencies, Java EE components provides references to resources that are defined in metadata annotations or external. These references are nothing more than a link named to the resources that can be dynamically determined at runtime within the application code or automatically by the container when the component instance is created.

Every reference has a name and a destination. The name is used by the application code to determine dynamically the reference. The server uses the destination information to find the feature that the application is looking for.

  • Annotations and Dependency Injection in EJB 3.0

Search for Dependency

The most traditional way of dependency management in Java EE is through search dependency in which the application code uses the Java Naming and Directory Interface (JNDI or) to locate a named reference.

The JNDI or Java Naming and Directory Interface is an API for accessing directory services. It allows client applications to discover and obtain data or objects via a name. Like all Java APIs, it is platform independent. Its two basic functions are :

  • Associate (map) a feature with name
  • Find a resource from its name.

All annotations resources support the name attribute that define the name of the reference. When the annotation feature is placed in the class definition, this attribute is mandatory. If the annotation is placed on an attribute or a setter method, the server will generate a default name. Usually annotations are put at the class level, and so the name is explicitly specified.

The name of the role is to provide a way for the client to locate the reference dynamically. All Java EE application server supports JNDI, and each component has its own local JNDI naming context that is called the environment naming context. The name of the reference is linked to the environment naming context, and when it is searched using the JNDI API, the server determines the reference and returns the reference destination.

Finding a dependency EJB

As an example we can consider the session bean below. In the example we have a dependency on a session bean by @ EJB annotation, the session bean is called “audit”, as defined in the “name” attribute. The attribute beanInterface only defines the business interface of the session bean that the client is concerned. @ PostConstruct in the session bean audit is located and stored in the attribute audit.

Context and InitialContext interfaces are defined both by the JNDI API. The lookup() method of the Context interface is the first point to return objects from a JNDI context. To find the reference audit, the application looks up the name java: comp/env/audit and makes a cast (conversion) result for the business interface AuditService.

The prefix java: comp/env/ added to the name of the reference to the server indicates that the environment naming context should be searched to find the reference. If the name is incorrect, an exception will be thrown when the search fails.

[java]
@ Stateless
@ EJB (name = "audit", beanInterface = AuditService.class)
public class implements DeptServiceBean DeptService {
private AuditService audit;
@ PostConstruct
public void init () {
try {
Context ctx = new InitialContext ();
audit = (AuditService) ctx.lookup ("java: comp/env/ audit");
} Catch (NamingException e) {
throw new EJBException (e);
}
}
// …
}
[/java]

Despite the above form to be valid and supported by large-scale Java EE components, we note that it is a little tricky to use it due to exception handling required by JNDI. EJBs also support an alternative syntax using a lookup() method of the interface EJBContext.

The interface EJBContext (and subinterfaces SessionContext and MessageDrivenContext) is available to any EJB and provide the bean with access to services at runtime such as timer services. The same example above is shown below using the lookup () method alternative. The instance SessionContext this example is provided via setter method.

Finding a dependency using EJB lookup

[java]
@ Stateless
@ EJB (name = "audit", beanInterface = AuditService.class)
public class implements DeptServiceBean DeptService {
SessionContext context;
AuditService audit;

public void setSessionContext (SessionContext context) {
this.context = context;
}

@ PostConstruct
public void init () {
audit = (AuditService) context.lookup ("audit");
}

// …

}
[/java]

The lookup() method of the EJBContext has two main advantages over the JNDI API:

  • First is the argument to the method is exactly the name that was specified on the resource reference.
  • The second advantage is that only runtime exceptions are thrown by the lookup() method, the other checked exceptions of API JNDI can be avoided. The management of exceptions are made automatically, but hidden from the client.

Summary

In this article we saw that an application depends on other components and we can use the search dependency to locate these components. One way is to use the JNDI API (Java Naming and Directory Interface) it allows client applications to discover and obtain data and objects via a name, or we can use an interface support to locate EJBs which in turn has some advantages in their use JNDI instead of the API.

Reference Articles on Dependency Injection

  • Lars Vogel on DI
  • Wikipedia Reference
  • Contexts and Dependency Injection
  • Joe on DI with Spring

Filed Under: Java Tagged With: JNDI

Working with Threads in Java

August 19, 2013 by Manisha Patil Leave a Comment

In this article we will see on how to use practical and simple Java threads to perform parallel processing in your application. The robust Java platform offers us another bonus feature when we deal with parallel processing. In this article we present a practical use of Threads in Java, with the goal of working in parallel, also known as concurrent programming.

Threads in Java

Before starting the practical explanation of Thread, understand that these are subdivisions of the processes. Each process has several threads (lines of instructions), so we can share parts of our process (Java program) to work in parallel.

The threads are in our day-to-day, in all the experiments in our computer. When we are listening to music and looking at facebook at the same time, we are conducting a parallel processing, even if it is transparent to the user.

In a Java program we want to run two or more threads at the same time, ie, two or more internal procedures of the program at the same time. To simplify the explanation of threads in Java, let’s take a practical example.

Imagine you have one procedure that consumes a lot of processor time, let’s assume the following example of a calculation that makes queries to a Web Service:

Procedure without common thread

[java]

public void CalculateTotalReceived () {
//Receives about 70 thousand records.
List<ReceiptHistoryreceived> received = getListOfReceipts();
Integer sum = 0;

for (h1 ReceiptHistoryreceived: received) {
sum = sum + received.getReceivedValue ();
}
Integer taxPercentage = getCurrentAdjustmentValueFromWebService();

sum = sum + ((taxPercentage/100) * sum);

totalValueReturnToWebService(sum);
}
[/java]

The above procedure seems simple (in fact it is simple),  a list with about 70 thousand records are received. For each record value and sum is picked up. After this, capture a value for adjustment percentage (captured from a WebService which can take time to respond), and recalculates the value added. Finally returns the result via WebService.

Note here that, the procedure here would take few minutes, and will not return anything to the user and just an internal communication between Web Services keep happening. We can not stop the application to perform the above procedure. Well imagine if you’re doing a simple registration and have to wait for about 5 minutes to complete the above processing.

The solution then is to make this procedure to run concurrently, ie while the user is performing the record, the above procedure is also performed, and probably when he has finished the registration, the above procedure has also ended.

In the code below we use the same code, but using the concept of threads. We will create a thread for a specific block of code through the class java.lang.Thread.

There is an interface called Runnable that has a run method. Inside the run method, you should include the procedures you want to run in parallel, so we put all the above code within a method run. Runnable is just a contract, we need some class that implements and does the work of “parallelization”, and that class is the Thread class.

Using Thread

[java]

public void CalculateTotalReceived () {
new Thread () {

@ Override
public void run () {
// Receives about 70thousand records.
List<ReceiptHistoryreceived> received = getListOfReceipts();
Integer sum = 0;

for (h1 ReceiptHistoryreceived: received) {
sum = sum + received.getReceivedValue ();
}

Integer taxPercentage = getCurrentAdjustmentValueFromWebService();

sum = sum + ((taxPercentage/100) * sum);

totalValueReturnToWebService(sum);

}
}.start ();

}

[/java]

When we do “.Start ();”  we are already starting the parallel processing, and releasing the program to be executed by any other thread. So assimilating the following idea:

  • If you want your program does not “lock the user” for that particular procedure or is taking a long time to execute, then use Thread.
  • If you want your class to be processed in parallel, but it already extends another, you can choose to implement the Runnable, which is the standard interface for Thread. For best practice, implement Runnable instead of extending Thread.
  • Pay attention to another very important point: The programmer has no control over the processor scheduler. This means that the processes are executed in parallel, you have no way of knowing what is execution order of these.

In the example below we put 2 counters to run in parallel, you will realize that the results may differ each time you run, or even from computer to computer.

Test Counters with Thread

[java]
package net.javabeat;

public class MyTest {
static int i = 0;
public static void main (String [] args) {
new Thread (t1). start ();
new Thread (t2). start ();
}

private static void countMe (String name) {
i++;
System.out.println ( "Current Counter is:" + i + ", updated by:" + name);
}

private static Runnable t1 = new Runnable () {
public void run () {
try {
for (int i = 0;i <5; i ++) {
countMe ( "t1" );
}
} catch (Exception e) {}

}
};

private static Runnable t2 = new Runnable () {
public void run () {
try {
for (int i = 0;i <5; i++) {
countMe ( "t2" );
}
} catch (Exception e) {}
}
};
}
[/java]

I’ll leave it up to you to test the above code and see what the outcome, because each computer may have a different order of execution,hence the ouptut may vary.

Summary

Use the resources of concurrent programming with care and only in the moments that really need it. Do not use Runnable in all codes thinking that your program will be faster, however, a process may need other resources. So carefully review the need to use this powerful feature .  If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Filed Under: Java

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • 5
  • …
  • 7
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved