Friday, July 19, 2013

java Enum Just for reference

via MKYONG


UserStatus.java – User’s status in enum structure
package com.mkyong;
 
public enum UserStatus {
 PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D");
 
 private String statusCode;
 
 private UserStatus(String s) {
  statusCode = s;
 }
 
 public String getStatusCode() {
  return statusCode;
 }
 
}
test.java – Get the user status
package com.mkyong;
 
public class test {
 
 public static void main(String[] args) {
 
  System.out.println(UserStatus.ACTIVE.getStatusCode());
 
 }
 
}

Tuesday, July 16, 2013

NullPointer Exception in java ..



via:: javarevisited.blogspot.com

When does NullPointerException occurs in Java

Javadoc of java.lang.NullPointerException has outlined scenario when it could be occurred:

1) When you call instance method on a null object. you won't get null pointer exception if you call static method or class method on null object because static method doesn't require an instance to call any method.
2) While accessing or changing any variable or field on null object.
3) Throwing null when an Exception is expected to throw.
4) When calling length of array when array is  null.
5) Accessing or changing slots of null just like an array.
6) When you try to synchronize on null object or using null inside synchronized block in Java

we will see examples of NullPointerException for each of above scenario to get it right and understand it better.

Common cause of NullPointerException in Java as Example

Based upon my experience java.lang.NullPointerException repeats itself on various format, I have collected most common cause of  java.lang.NullPointerException in java code and explained them here, we will use following Trade class for example :

public class Trade {
    
private String symbol;
    
private int price;
    
public static String market;

    
public Trade(String symbol, int price) {
        
this.symbol = symbol;
        
this.price = price;
    
}

    
public int getPrice() {
        
return price;
    
}

    
public void setPrice(int price) {
        
this.price = price;
    
}

    
public String getSymbol() {
        
return symbol;
    
}

    
public void setSymbol(String symbol) {
        
this.symbol = symbol;
    
}
}


1)  Java  NullPointerException while calling instance method on null object
This is probably the most common case of this error, you call method on some object and found that reference is null, always perform null check if you see possibility of null before calling any method on object.

Trade pennyStock = null;
pennyStock.
getPrice(); //this will throw NullPointerException
Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:23)

2) NullPointerException in Java while accessing field on null reference.

Trade fxtrade = null;
int price = fxtrade.price; //here fxtrade is null, you can’t access field here
Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:64)


3) java.lang.NullPointerException when throwing null as exception.
If you thorw an Exception object and if that is null you will get null pointer exception as shown in below example

RuntimeException nullException = null;
throw nullException;
Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:74)


4)example of NullPointerException when getting length of an array which is null.

Trade[] bluechips = null;
int length = bluechips.length;  //array is null here
Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:85)


5) Example of NPE when accessing element of a null array.
Trade[] bluechips = null;
Trade motorola = bluechips
[0]; //array is null here
Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:94)


6) You will also get NullPointerException in Java if you try to synchronize on null object or try to use null object inside synchronized block in Java.

Trade highbetaTrade = null;
synchronized(highbetaTrade){
System.out.print("This statement is synchronized on null");
}

Exception in thread "main" java.lang.NullPointerException
at test.
NullPointerExceptionTest.main(NullPointerExceptionTest.java:104)

How to solve NullPointerException in Java

To solve a NullPointerException in Java first we need to find cause, which is very easy just look the stack-trace of NullPointerException and it will show exact line number where NPE has occurred. now go to that line and look for possible object operation like accessing field, calling method or throwing exception etc, that will give you an idea which object is null. Now once you found that which object is null job is half done , now find out why that object is null and solve the java.lang.NullPointerException. , This second part always vary sometime you get null object from factory or sometime some other thread might have set it null, though using Assertion in early phase of development you can minimize chances of java.lang.NullPointerException but as I said its little bit related to environment and can come on production even if tested fine in test environment. Its best to avoid NullPointerException by applying careful or defensive coding technique and null safe API methods.

When in Java Code NullPointerException doesn't come

1) When you access any static method or static variable with null reference.
If you are dealing with static variables or static method than you won't get null pointer exception even if you have your reference variable pointing to null because static variables and method call are bonded during compile time based on class name and not associated with object. for example below code will run fine and not throw NullPointerException because "market" is an static variable inside Trade Class.

Trade lowBetaTrade = null;
String market = lowBetaTrade.market; //no NullPointerException market is static variable


Important points on NullPointerException in Java

1) NullPointerException is an unchecked exception because its extends RuntimeException and it doesn’t mandate try catch block to handle it.
2) When you get NullPointerException look at line number to find out which object is null, it may be object which is calling any method.
3) Modern IDE like Netbeans and Eclipse gives you hyper link of line where NullPointerException occurs
4) You can set an Exception break point in Eclipse to suspend execution when NullPointeRException occurs read 10 tips on java debugging in Eclipse more details.
5) Don't forget to see name of Thread on which NullPointerException occurs. in multi-threading NPE can be little tricky if some random thread is setting reference to null.
6) Its best to avoid NullPointerException while coding by following some coding best practices or putting null check on database as constraint.

That’s all on What is java.lang.NullPointerException, When it comes and how to solve it. In next part of this tutorial we will look on some best java coding practices to avoid NullPointerException in Java.


Read more: 
http://javarevisited.blogspot.com/2012/06/common-cause-of-javalangnullpointerexce.html#ixzz2ZCMiZYv3

Wednesday, July 10, 2013

Reflection in Java ...


Java reflection is one of the powerful features of java. Reflection allows to inspect and manipulate meta java at runtime. We can access Java classes, methods, attributes, annotations at runtime and objects can be instantiated, methods invoked.
Reflection is a very powerful feature, it will come handy in many a situations and can do the unexpected. Java reflection requires multiple articles and I will be writing about them in future. This one is a cheat sheet, a quick reference kind of document for reflection.

Get Class Object:
Class zooClass = ZooImpl.class;
Get Class Object Using Class Canonical Name as Argument:
String className = "com.javapapers.corejava.ZooImpl";
Class zooClass = Class.forName(className);
Get Canonical Name From a Class Object:
String classCanoName = zooClass.getCanonicalName();
Get All Constructors of a Class:
Constructor[] constructorArr = zooClass.getConstructors();
Get Constructor with Parameter as String:
Constructor constructor = zooClass.getConstructor(String.class);
Get All Parameters of a Constructor:
Class[] parameterArr = constructor.getParameterTypes();
Instantiate an Object using a Constructor:
ZooImpl zooObject = (ZooImpl)constructor.newInstance(“My Zoo”);
Get Parent Class:
Class parentClass = zooClass.getSuperclass();
Get Package:
Package package = zooClass.getPackage();
Get Modifiers:
int modifiers = zooClass.getModifiers();
Modifier.isAbstract(int modifiers)
Modifier.isFinal(int modifiers)
Modifier.isPrivate(int modifiers)
Get Interfaces Implemented by a Class:
Class[] interfaceArr = zooClass.getInterfaces();
Get Methods: (including inherited)
Method[] methodArr = zooClass.getMethods();
Get Methods: (inherited not included)
Method[] methodArr = zooClass.getDeclaredMethods();
Get a Method:
Method method = zooClass.getMethod(“removeAnimal”, new Class[]{String.class});
Invoke a Method:
Object methodReturnValue = method.invoke(zooObj, “Animal Name”);
Get Fields:
Field[] fieldArr = zooClass.getFields();
Get Public Field:
Field field = zooClass.getField(“SimpleFieldName”);
Get Field Value:
Class zooClass = zooObj.getClass()
Field zooNamefield = zooClass.getField(“zooName”);
Object fieldValue = field.get(zooObj);
Set Field Value:
Object fieldValue = “My Zoo”;
zooNamefield.set(zooObj, fieldValue);
Get Annotations: (including inherited) Should have Retention Policy set as RUNTIME to access annotations at runtime.
Annotation[] annotationArr = zooClass.getAnnotations();
Get Annotations: (inherited not included)
Annotation[] annotationArr = zooClass.getDeclaredAnnotations();
Get Annotation by Type:
Annotation annotation = zooClass.getAnnotation(ZooManager.class);
Check is Annotation:
boolean flag = annotation.isAnnotation();
Check if an Annotation is Present:
boolean flag = zooClass.isAnnotationPresent(ZooManager.class);
Get Public Members:
Class[] publicMemberArr = zooClass.getClasses();
Get All Members:
Class[] memberArr = zooClass.getDeclaredClasses();
GetElements of an Enum Class:
Object[] elementArr = enumClass.getEnumConstants();
Is an Instance of this Class:
boolean flag = zooClass.isInstance(zooObj);
Check if a Class is Synthetic Class:
boolean flag = zooClass.isSynthetic();

Tuesday, July 9, 2013

java decompiler for eclipse IDE ...


Decompile Java using Eclipse (JD-Eclipse plugin)


Decompiler is to reverse engineer source code from object code. A decompiler for java should get the respective source file from its Java binary class file.
No Java tool is complete unless it provides a plugin for Eclipse IDE. Eclipse is the most popular Java IDE.
JD Java decompiler provides a plugin for Eclipse IDE, so that we can decompile a Java class file within the Eclipse IDE itself.
Install the JD-Eclipse plugin as shown in the next screen shot.
Install JD Decompile Eclipse
JD Java decompile Eclipse plugin will take some good time to install, may be you should have a big coffee during the time. On a side note, Eclipse should still refine its plugin installation process. Once installed a java class file can be just opened and decompiled on the go.

Thursday, April 25, 2013

C# how to generate Excel sheet from class dll using Reflection.

http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm


code 
make class ExcelUtility:::::::

    class ExcelUtility
    {
        private Application app = null;
        private Workbook workbook = null;
        private Worksheet worksheet = null;
        private Range workSheet_range = null;
    
        public ExcelUtility()
        {
            createDoc();
        }
        public void createDoc()
        {
            try
            {
                app = new Application();
                app.Visible = true;
                workbook = app.Workbooks.Add(1);
                worksheet = (Worksheet)workbook.Sheets[1];
            }
            catch (Exception e)
            {
                Console.Write("Error");
            }
            finally
            {
            }
        }

        public void createHeaders(int row, int col, string htext, string cell1,
        string cell2, int mergeColumns, string b, bool font, int size, string
        fcolor)
        {
            worksheet.Cells[row, col] = htext;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Merge(mergeColumns);
            switch (b)
            {
                case "YELLOW":
                    workSheet_range.Interior.Color = System.Drawing.Color.Yellow.ToArgb();
                    break;
                case "GRAY":
                    workSheet_range.Interior.Color = System.Drawing.Color.Gray.ToArgb();
                    break;
                case "GAINSBORO":
                    workSheet_range.Interior.Color =
            System.Drawing.Color.Gainsboro.ToArgb();
                    break;
                case "Turquoise":
                    workSheet_range.Interior.Color =
            System.Drawing.Color.Turquoise.ToArgb();
                    break;
                case "PeachPuff":
                    workSheet_range.Interior.Color =
            System.Drawing.Color.PeachPuff.ToArgb();
                    break;
                default:
                    //  workSheet_range.Interior.Color = System.Drawing.Color..ToArgb();
                    break;
            }

            workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.Font.Bold = font;
            workSheet_range.ColumnWidth = size;
            if (fcolor.Equals(""))
            {
                workSheet_range.Font.Color = System.Drawing.Color.White.ToArgb();
            }
            else
            {
                workSheet_range.Font.Color = System.Drawing.Color.Black.ToArgb();
            }
        }

        public void addData(int row, int col, string data,
            string cell1, string cell2, string format)
        {
            worksheet.Cells[row, col] = data;
            workSheet_range = worksheet.get_Range(cell1, cell2);
            workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
            workSheet_range.NumberFormat = format;
        }

        public void addStringData(int row, int col, string data)
        {
          //  CellStyle cs = wb.createCellStyle();
            worksheet.Cells[row, col] = data;
         }
    }





Class 2 :: Program
namespace ConsoleApplication1
{
    class Program
    {
        static void Main1()
        {
            int currentRow = 1;

            int columnForInterface = 1;
            int columnForMethod = columnForInterface + 1;
            int columnForParameter = columnForMethod + 1;
            int columnForProperties = columnForParameter + 1;

            ExcelUtility excell_app = new ExcelUtility();

            excell_app.createHeaders(currentRow, columnForInterface, "Interface_name", "A1", "A1", 1, "YELLOW", true, 10, "n");
            excell_app.createHeaders(currentRow, columnForMethod, "Public Method", "B1", "B1", 1, "YELLOW", true, 10, "n");
            excell_app.createHeaders(currentRow, columnForParameter, "Parameters", "C1", "C1", 1, "YELLOW", true, 10, "n");
            excell_app.createHeaders(currentRow, columnForProperties, "Extended Parameters", "D1", "D1", 1, "YELLOW", true, 10, "n");

            currentRow = currentRow + 1;

            Assembly serviceAssembly = Assembly.LoadFrom("xyz.dll");
            Assembly viewDTOAssembly = Assembly.LoadFrom("abc.dll");

            Type[] serviceAssemblyTypeCollection = serviceAssembly.GetTypes();
            Type[] viewDTOAssemblyTypeCollection = serviceAssembly.GetTypes();

            foreach (Type serviceAssemblyType in serviceAssemblyTypeCollection)
            {
                if (!serviceAssemblyType.IsInterface)
                    continue;

                // ------------------------------
                excell_app.addStringData(currentRow, columnForInterface, serviceAssemblyType.Name);
                // ------------------------------

                MethodInfo[] methods = serviceAssemblyType.GetMethods();
                string methodNames = string.Empty;
                string parameterNames = string.Empty;
                string parameterTypes = string.Empty;
                foreach (MethodInfo method in methods)
                {
                    Console.WriteLine("\t{0}", method.Name);
                    methodNames += method.Name + "\n";
                    // ------------------------------
                    excell_app.addStringData(currentRow, columnForMethod, method.Name);
                    // ------------------------------

                    bool methodHasParameters = false;

                    ParameterInfo[] pinfo = method.GetParameters();
                    foreach (ParameterInfo parameterInfo in pinfo)
                    {
                        Type parameterType = parameterInfo.ParameterType;
                        if (parameterType.IsGenericType)
                        {
                            PropertyInfo[] propertyInfoCollection = parameterType.GetProperties();

                            foreach (PropertyInfo info in propertyInfoCollection)
                            {
                                string fullName = info.PropertyType.FullName;
                                Type typeInViewDTO = viewDTOAssembly.GetType(fullName);

                                if (typeInViewDTO == null)
                                {
                                    Console.WriteLine("Type Not Found in View Dto Assembly");
                                   
                                }
                                else
                                {
                                    methodHasParameters = true;
                                    // ------------------------------
                                    //excell_app.addStringData(currentRow, columnForParameter, fullName);
                                    excell_app.addStringData(currentRow, columnForMethod, method.Name);
                                    excell_app.addStringData(currentRow, columnForParameter, fullName + "::" + parameterInfo.Name);
                                    currentRow = currentRow + 1;
                                    // ------------------------------

                                    //Console.WriteLine("\t\t\t{0}", parameterType);
                                    //parameterTypes += parameterType + "\n";
                                    //parameterNames += parameterInfo.Name + "\n";
                                }
                            }
                        }
                        else
                        {
                            string fullName = parameterType.FullName;
                            Type typeInViewDTO = viewDTOAssembly.GetType(fullName);

                            if (typeInViewDTO == null)
                            {
                                excell_app.addStringData(currentRow, columnForMethod, method.Name);
                                excell_app.addStringData(currentRow, columnForParameter, fullName + "::" + parameterInfo.Name);
                                currentRow = currentRow + 1;
                                Console.WriteLine("Type Not Found in View Dto Assembly");
                            }
                            else
                            {
                                //PropertyInfo[] arrayOfProperties = typeInViewDTO.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                                PropertyInfo[] arrayOfProperties = typeInViewDTO.GetPublicProperties();
                                if (arrayOfProperties == null || arrayOfProperties.Length == 0)
                                {
                                    excell_app.addStringData(currentRow, columnForMethod, method.Name);
                                    excell_app.addStringData(currentRow, columnForParameter, fullName + "::" + parameterInfo.Name);
                                    currentRow = currentRow + 1;
                                    continue;
                                }
                                else
                                {
                                    StringBuilder propertyBuilder = new StringBuilder();
                                    foreach (PropertyInfo propertyOfDTO in arrayOfProperties)
                                    {
                                        propertyBuilder.Append(propertyOfDTO.Name);
                                        propertyBuilder.Append("\n");
                                    }
                                    excell_app.addStringData(currentRow, columnForMethod, method.Name);
                                    excell_app.addStringData(currentRow, columnForParameter, fullName + "::" + parameterInfo.Name);
                                    excell_app.addStringData(currentRow, columnForProperties, propertyBuilder.ToString());
                                    currentRow = currentRow + 1;
                                }
                               
                                //Console.WriteLine("\t\t\t{0}", parameterType);
                                //parameterTypes += parameterType + "\n";
                                //parameterNames += parameterInfo.Name + "\n";
                            }
                            methodHasParameters = true;
                        }
                    }

                    if (!methodHasParameters)
                    {
                        excell_app.addStringData(currentRow, columnForParameter, "------------");
                        currentRow = currentRow + 1;
                    }
                   
                }


                // ------------------------------

                //if (methodNames.EndsWith("\n"))
                //    methodNames = methodNames.Substring(0, methodNames.Length - 2);
                //excell_app.addStringData(classCount, methodCount, methodNames);
                //if (parameterNames.EndsWith("\n"))
                //    parameterNames = parameterNames.Substring(0, parameterNames.Length - 2);
                //excell_app.addStringData(classCount, methodCount + 1, parameterTypes + parameterNames);

                // ------------------------------

                currentRow = currentRow + 2;
               

            }
            Console.ReadLine();
        }
    }



    public static class MyExtensions
    {
        public static PropertyInfo[] GetPublicProperties(this Type type)
        {
            if (type.IsInterface)
            {
                var propertyInfos = new List<PropertyInfo>();

                var considered = new List<Type>();
                var queue = new Queue<Type>();
                considered.Add(type);
                queue.Enqueue(type);
                while (queue.Count > 0)
                {
                    var subType = queue.Dequeue();
                    foreach (var subInterface in subType.GetInterfaces())
                    {
                        if (considered.Contains(subInterface)) continue;

                        considered.Add(subInterface);
                        queue.Enqueue(subInterface);
                    }

                    var typeProperties = subType.GetProperties(
                        BindingFlags.FlattenHierarchy
                        | BindingFlags.Public
                        | BindingFlags.Instance);

                    var newPropertyInfos = typeProperties.Where(x => !propertyInfos.Contains(x));

                    propertyInfos.InsertRange(0, newPropertyInfos);
                }

                return propertyInfos.ToArray();
            }

            return type.GetProperties(BindingFlags.FlattenHierarchy
                | BindingFlags.Public | BindingFlags.Instance);
        }
    }
}

Creating mirror of BST