While Using JSON Array for adding Details the required filter parameter in the Array may appear in any part of the Array.To Filter the Array which has many multiple data types i.e String, Integer, boolean you need to do instanceof comparison

In the below JSON array has a List of Employee Details from which Employee from a Particular location is taken out after Filtering

 
 package com.mugil.json;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;

public class Employee {

	public static void main(String[] args) {
		String Location = "Chennai";
		JSONArray arrEmpDetails = getEmpList();

		System.out
				.println("*-----------------Before Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		arrEmpDetails = filterEmpByLocation(arrEmpDetails, Location);

		System.out
				.println("*-----------------After Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		System.out
				.println("*-----------------------------------------------------*");

	}

	private static void displayEmpDetails(JSONArray arrEmpDetails) {
		JSONArray arrEmpDet = new JSONArray();

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				arrEmpDet = arrEmpDetails.getJSONArray(i);
				System.out.println(arrEmpDet);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	private static JSONArray filterEmpByLocation(JSONArray arrEmpDetails,
			String location) {
		JSONArray arrEmpByLoc = new JSONArray();
		String strToComp = null;
		boolean isSameLoc = false;

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				JSONArray type = arrEmpDetails.getJSONArray(i);

				for (int j = 0; j < type.length(); j++) {
					Object strString = type.get(j);
					if (strString instanceof java.lang.String) {
						strToComp = (String) strString;
						isSameLoc = strToComp.equals(location);
					}
				}

				if (isSameLoc) {
					arrEmpByLoc.put(type);
					isSameLoc = false;
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return arrEmpByLoc;
	}

	public static JSONArray getEmpList() {
		JSONArray arrEmpDetails = new JSONArray();
		JSONArray arrPerDetails = new JSONArray();

		arrPerDetails.put("Empl1");
		arrPerDetails.put(23);
		arrPerDetails.put("Address1");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl2");
		arrPerDetails.put(23);
		arrPerDetails.put("Address2");
		arrPerDetails.put("Coimbatore");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl3");
		arrPerDetails.put(24);
		arrPerDetails.put("Address3");
		arrPerDetails.put("Tirchy");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl4");
		arrPerDetails.put(26);
		arrPerDetails.put("Address4");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		return arrEmpDetails;
	}

}

“Reflection” is a language’s ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java has the method getClass, which lets you determine its class even if you don’t know it at compile time (like if you declared it as Object) – this might seem trivial, but such reflection is not by default possible in less dynamic languages such as C++.

Why do we need reflection?

Reflection enables us to:

  1. Examine an object’s class at runtime
  2. Construct an object for a class at runtime
  3. Examine a class’s field and method at runtime
  4. Invoke any method of an object at runtime
  5. Change accessibility flag of Constructor, Method and Field
    etc.

Reflection is important since it lets you write programs that does not have to “know” everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lets see the simple example of forName() method.

    class Simple{}  
      
    class Test{  
     public static void main(String args[]){  
      Class c=Class.forName("Simple");  
      System.out.println(c.getName());  
     }  
    }  

For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.

So, to give you a code example of this in Java (imagine the object in question is foo) :

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

Getting list of methods in a Class by Reflection

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

Details which can be accessed by reflection

  1. Class Name
  2. Class Modifies (public, private, synchronized etc.)
  3. Package Info
  4. Implemented Interfaces
  5. Superclass
  6. Constructors
  7. Fields
  8. Methods
  9. Annotations

Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.

It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.

Drawbacks
Since everything is done at runtime optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Usage

  1. Reflection is used when it is needed to get into the other classes in deeper level. So in most of the cases, these implementors have the container-behavior. For instance, dependency injection is mostly done with the use of reflection
  2. Remote procedure calling — treat part of a message received over the network as a method name.
  3. Object-relational mappings — maintain a relationship between fields in an object and columns in a database.
  4. Interfaces with dynamically typed scripting languages — turn a string value produced by a scripting language into a reference to a field or method on an object.
  5. Serialization and deserialization — convert field names to string so you can write the object’s fields to a stream and later convert it back into an object.

One useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where th framework author doesn’t know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. For instance, I don’t think it would be possible to write a complex aspect-oriented librory without reflection.

Servlet Mapping in web.xml and Junit annotations are other where reflection is used.

For example, JUnit use reflection to look through methods tagged with the @Test annotation, and then call those methods when running the unit test. (Here is a set of examples of how to use JUnit.)

For web frameworks, product developers define their own implementation of interfaces and classes and put is in the configuration files. Using reflection, it can quickly dynamically initialize the classes required.

For example, Spring uses bean configuration such as:

<bean id="someID" class="com.programcreek.Foo">
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument “com.programcreek.Foo” to instantiate that Class. It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

The same mechanism is also used for Servlet web applications:

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.programcreek.WhyReflectionServlet</servlet-class>
<servlet>
 Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);

The above returns actual maximum for current month. For example it is February of leap year now, so it returns 29.

And to get last day as Date object:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDayOfMonth = cal.getTime();

Invocation of toString on an array

private String [] arrActions;

public String [] getArrActions() {
  return arrActions;
}

public void setArrActions(String [] parrActions) {
  this.arrActions = parrActions;
}

String action = null;

if(form.getArrActions() != null){
  action = form.getArrActions().toString;
}

Bug Code

  action = form.getArrActions().toString;

Fix Code

  action = Arrays.toString(form.getArrActions());

——————————————————————————————————————————————————————

Incorrect lazy initialization and Update of Static Field

Below is the Sample code trying to implement Singleton pattern without synchronized

public static Object getInstance() {
    if (instance != null) {
        return instance;
    }

    instance = new Object();
    return instance;
}

In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.

The race condition here is on the if check. On the first call, a thread will get into the if check, and will create the instance and assign it to ‘instance’. But there is potential for another thread to become active between the if check and the instance creation/assignment. This thread could also pass the if check because the assignment hasn’t happened yet. Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.

The solution for this can be in Two Ways
Solution 1

private static volatile Object myLock = new Object(); // must be declared volatile

public static Object getInstance() {
    if (instance == null) { // avoid sync penalty if we can
        synchronized (MyCurrentClass.myLock) { // declare a private static Object to use for mutex
            if (instance == null) {  // have to do this inside the sync
                instance = new Object();
            }
        }
    }

    return instance;
}

For more Details on Volatile memory refer the following Link
http://tutorials.jenkov.com/java-concurrency/volatile.html

Solution 2

public synchronized static Object getInstance() {
    if (instance == null) {
        instance = new Object();
    }

    return instance;
}

——————————————————————————————————————————————————————
Covariant Equals method Defined

When equals method not properly overridden in your class then this Error is Thrown.

Things to Check
1.The Passing parameter should be Object Type.

Code for Overridding equals() method

public boolean equals(Object other){
    boolean result;
    if((other == null) || (getClass() != other.getClass())){
        result = false;
    } // end if
    else{
        People otherPeople = (People)other;
        result = name.equals(otherPeople.name) &&  age == otherPeople.age;
    } // end else

    return result;
} // end equals

——————————————————————————————————————————————————————

int value cast to float and then passed to Math.round

 public static String createFileSizeString(big size)
 {
   if (size < 1048576)
   {
     return (Math.round(((size * 10) / 1024)) / 10) + " KB";
   }
 }

Math.round was intended to be used on floating point arithmetic.The (size*10)/1024 may or may not return float value.So we should explicitly convert to float before using math.round

  (size * 10) / 1024 

should be

  ((float)size * 10) / 1024

——————————————————————————————————————————————————————
Bad comparison of nonnegative value with negative constant

 if (rows.size() < 0 || rows.isEmpty()) {
 .
 .
 .
 }

rows.size() can either be 0 or Positive Integer

 if (rows.size() < 0 || rows.isEmpty()) 

Should be

 if (rows.size() <= 0 || rows.isEmpty()) 

——————————————————————————————————————————————————————
the parameter is dead upon entry

 public void TestSample(boolean status)
 {
  .
  . 
  .
  status = true;
 }

The Parameter status is set to true and it was never used.So we can simply remove it as shown below

 public void TestSample(boolean status)
 {
  .
  . 
  .
 }

——————————————————————————————————————————————————————
Null value guaranteed to be De referenced
Solution
Check for null value of the Bean before calling bean method

 .
 shipmentBean.getStatus();
 .

should be

 .
 (shipmentBean==null?null:shipmentBean.getStatus());
 .

——————————————————————————————————————————————————————
Suspicious reference Comparison
Suspicious reference Comparison of Long

  Long val1 = 127L;
  Long val2 = 127L;

  System.out.println(val1 == val2);

  Long val3 = 128L;
  Long val4 = 128L;

  System.out.println(val3 == val4);

Output

 true
 false

This is happening because you are comparing Long objects references, not long primitives values.

To safely do this comparison you want (still using Long objects), you have the following options:

 System.out.println(val3.equals(val4));                    // true
 System.out.println(val3.longValue() == val4.longValue()); // true
 System.out.println((long)val3 == (long)val4);             // true

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127.

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

——————————————————————————————————————————————————————

Convert double to BigDecimal and set BigDecimal Precision

new BigDecimal(0.1)

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.

This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

 new BigDecimal(0.1)

should be

 BigDecimal.valueOf(0.1)

Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of

Double.toString(double).

——————————————————————————————————————————————————————
Dead store to Local Variable

public class Foo
{
    public static void Bar()
    {
    
    }
}

public class Abc
{
    public void Test()
    {
      Foo objFoo = new Foo(); 
      objFoo.Bar();

    }
}

Bug

    Foo objFoo = new Foo(); 
    objFoo.Bar(); 

Fix

   Foo.Bar();

If I look at code someVariable.SomeMethod() I expect it to use the value of someVariable. If SomeMethod() is a static method, that expectation is invalid. Java won’t let you use a potentially uninitialized variable to call a static method, despite the fact that the only information it’s going to use is the declared type of the variable.

Creating Database Connection in Context.xml

<Context>
  <Resource name="jdbc/[YourDatabaseName]"  auth="Container" type="javax.sql.DataSource"
   username="[DatabaseUsername]" password="[DatabasePassword]" driverClassName="com.mysql.jdbc.Driver"
   url="jdbc:mysql:/[yourserver]:3306/[yourapplication]" maxActive="15" maxIdle="3"/>
</Context>

context.xml

<Context>
  <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/test"/>
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Test.java

 PrintWriter out = response.getWriter();
 String Sno = request.getParameter("t1");
 String Name = request.getParameter("t2");
		
 try{
   InitialContext context = new InitialContext();
   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/test");
   Connection conn  = ds.getConnection();
   PreparedStatement statement = conn.prepareStatement("insert into Details values(?,?)");
   statement.setString(1, Sno);
   statement.setString(2, Name);
   statement.execute();
   conn.close();
   statement.close();
   out.println("Done");
  }catch (Exception e) {
   e.printStackTrace();
  }

Working with ENUM
ENUM is just a list of set of value which are static and final.Executing the below code will have a output like one below

public class Test {
	public enum Company {
		EBAY, PAYPAL, GOOGLE, YAHOO, ATT
	}

	public static void main(String[] args) {
                System.out.println(Company.EBAY);
	}
}

Output

  EBAY

Now what you can do is to make this constant (static and final) to have further attributes like one below.

public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
 
private Company(int value) {
this.value = value;
}
}

and more Values with overloaded constructor

public class Test1 {

	public enum JobStatus {
		OPEN("Open", "Its Open", "1"), ERROR("Error", "Its a Error", "2"), WORKING(
				"Working", "Its Working", "3"), CLOSED("Closed", "Its Closed");
		private String	value;
		private String	label;
		private String	order;

		private JobStatus(String label, String value, String order) {
			this.label = label;
			this.value = value;
			this.order = order;
		}

		private JobStatus(String label, String value) {
			this.label = label;
			this.value = value;
		}

		public String getValue() {
			return this.value;
		}

		public String getLabel() {
			return this.label;
		}
	}

	public static void main(String[] args) {
		System.out.println(JobStatus.OPEN.value);
		System.out.println(JobStatus.OPEN.label);
		System.out.println(JobStatus.OPEN.order);
		System.out.println(JobStatus.CLOSED.order);
	}
}

Output

Its Open
Open
1
null

When you need a predefined list of values which do not represent some kind of numeric or textual data, you should use an enum. For instance, in a chess game you could represent the different types of pieces as an enum

enum ChessPiece {
PAWN,
ROOK,
KNIGHT,
BISHOP,
QUEEN,
KING;
}

Assigning Values to ENUM

public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
 
private Company(int value) {
this.value = value;
}
}
  • All enums implicitly extend java.lang.Enum.
  • MyEnum.values() returns an array of MyEnum’s values.
  • Enum constants are implicitly static and final and can not be changed once created.
  • Enum can be safely compare using “==” equality operator
  • An enum can be declared outside or inside a class, but NOT in a method.
  • An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • enum constructors can have arguments, and can be overloaded.

1.Utility Classes should have constants for variable

public class PolicyUtils 
{
 public static final String TOTAL_POLICY_LIMIT = "totalpolicylimit";
 requestHelper.setRequestAttribute(TOTAL_POLICY_LIMIT, policyLimit);
}

Since multiple Users can access the JSP page at same time assigning variable name to constant and changing it later makes it easy to change the actual variable name in case needed in future.

Posted in JSP.

There are two types of objects in Hibernate
1. Value Object
2. Entities

Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.
Entity Objects are those who can stand alone like College and Student.

So in case of value objects preferred way is to Embed them into an entity object. In the example below Address class does not derive the meaning of its own. So Address is Value Object and is Embeddable. Whereas UserDetails(Entities) could stand on its own and it could have Embedded Objects

Address.java

 import javax.persistence.Embeddable;

@Embeddable
public class Address {
	private String Street;
	private String Location;
	private String City;
	
	public String getStreet() {
		return Street;
	}
	public void setStreet(String street) {
		Street = street;
	}
	public String getLocation() {
		return Location;
	}
	public void setLocation(String location) {
		Location = location;
	}
	public String getCity() {
		return City;
	}
	public void setCity(String city) {
		City = city;
	}
}

UserDetails.java

public class UserDetails 
{
 @Embedded
 private Address address;
 .
 .
 .
}

The above code explains how the Embedded and Embeddable annotations can be used in the code.

CreateUser.java

  Address objAddress = new Address();
  objUserDetail.setAddress(objAddress);

Attribute Override

@Embedded
@AttributeOverride (name="Street",column=@Column(name="HOME_STREET"))
private Address addr;

Multiple Attribute Overrides

@Embedded
 @AttributeOverrides({
	@AttributeOverride(name="doorNo", column=@Column(name="Office_DoorNo")),
	@AttributeOverride(name="streetName", column=@Column(name="Office_streetName")),
	@AttributeOverride(name="location", column=@Column(name="Office_location")),
	@AttributeOverride(name="pincode", column=@Column(name="Office_pincode"))
})
private Address addr;
  @Id @GeneratedValue(strategy=GenerationType.AUTO)
  private int userId;

By using @GeneratedValue annotation we can create primary key in table.The annotations takes 4 parameter as strategy attribute.

@GeneratedValue(strategy=GenerationType.AUTO)
Auto tells the Hibernate to do the primary key addition from hibernate side

@GeneratedValue(strategy=GenerationType.IDENTITY)
IDENTITY tells the Hibernate to do the primary key addition from DB side when set to auto increment.

@GeneratedValue(strategy=GenerationType.SEQUENCE)
SEQUENCE tells the Hibernate to do the primary key addition as defined by sequence in DB.

@GeneratedValue(strategy=GenerationType.TABLE)
TABLE tells the Hibernate to create a seperate table in DB and maintain the last inserted values.
The table contains only one row with last inserted value.

15

Retrieve value from Database using Session

public static void main(String[] args)
{
	UserDetails objUserDetail =  new UserDetails();
	.
	session.getTransaction().commit();

	objUserDetail = null;

	/*Retriving UserDetails from DB Using Session*/
	session = sessionFact.openSession();
	session.beginTransaction();
	objUserDetail = (UserDetails)session.get(UserDetails.class, 105);
	System.out.println(objUserDetail.getUserName());
}

To retrieve the value from session we use the primary key for the table in the above case.

 objUserDetail = (UserDetails)session.get(UserDetails.class, 105);
 System.out.println(objUserDetail.getUserName());

105 – is the UserId which is primary key for the USER_DETAILS table in DB.