Sunday, April 24, 2016

Exam Support

            OSGi--------------------------------------------------------------------

1)OPEN ECLIPSE (in my case HELIOS JavaEE)

2)CREATE SERVICE PROJECT
            i) File => new => OSGi bundle project => next
                        OR
                        File => new => plug-in project =>eclipse version 3.6

            ii) Project name = com.mtit.osgi.Service
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name "ServerActivator"
            v) finish

3)CREATE CLIENT PROJECT
            i) File => new => plug-in project =>eclipse version 3.6
            ii) Project name = com.mtit.osgi.Client
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name as "ClientActivator"
            v) finish

4)CREATE INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> interface
            ii) name = "IServiceActions"
            ii) add function skeletons to interface
                        public String PrintService();
                        public String Hello();

5)IMPLEMENT INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> class (implements "IServiceActions")
            ii) name = "ServiceActions"
            iii) implement methods
                        public String PrintService(){
                                    return "execute print service";
                        }
                        public String Hello(){
                                    return "Hello!!";
                        }

6)IMPLEMENT Start() FUNCTION IN "ServerActivator"
            i) create global variable in the class
                         org.osgi.framework.ServiceRegistration serviceReg;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("service started");
                        IServiceActions sactions = new ServiceActions();
                        serviceReg = context.registerService(IServiceActions.class.getName(),sactions,null);

7)IMPLEMENT Stop() FUNCTION IN "ServerActivator"
            i) comment whatever lines inside Stop() method(or keep as it is)
            ii) type
                        serviceReg.unregister();
                        System.out.println("service stopped");


8)ADD org.osgi.service PROJECT TO org.osgi.client BUILD PATH
            i)right click org.osgi.client --> properties --> java build path --> "project" tab
            ii)add --> select org.osgi.service --> ok

6)IMPLEMENT Start() FUNCTION IN "ClientActivator"
            i) create global variable in the class
                        org.osgi.framework.ServiceReference serviceRef;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("client starts!!");
                        serviceRef = context.getServiceReference(IServiceActions.class.getName());
                        ServiceActions sactions = (ServiceActions)context.getService(serviceRef);
                        System.out.println(sactions.Hello());
                        System.out.println(sactions.PrintService());

                       
7)NEED NOT TO IMPLEMENT Stop() FUNCTION IN "ServerActivator".Keep as it is unless asked.

8)EXPORT org.osgi.service RUNTIME PACKAGES
            i) open org.osgi.service MANIFEST.MF file
            ii) open "Runtine" tab --> add --> select "org.osgi.service" --> ok
           

9)ADD DEPENDENCIES TO org.osgi.client
            i) open org.osgi.client MANIFEST.MF file
            ii) open "Dependencies" tab --> add imported package--> search and select "org.osgi.service" --> ok


10) RUN org.osgi.service (as osgi framework project)
    RUN org.osgi.client


----------------Client-------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Client
Bundle-SymbolicName: com.mtit.osgi.Client
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.client.ClientActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Import-Package: org.osgi.framework;version="1.3.0", com.mtit.osgi.service

------------Server----------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Service
Bundle-SymbolicName: com.mtit.osgi.Service
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.service.ServerActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ActivationPolicy: lazy
Export-Package: com.mtit.osgi.service
Import-Package: org.osgi.framework;version="1.3.0"


Configure osgiFramework(Run As OSGIFramework)
Deselect all
Add felix, eqoix.consol ,
Com.mtit.osgi.client/service

Runà after error add required bundle


***Coding Standard 





























            Reflections-----------------------------------------------------------

2.1         Lab.Task1

import java.lang.reflect.Modifier;

public class Task1 {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clazz = Class.forName("com.mtit.lab.task1.Task1");
                                             System.out.println(clazz.getSimpleName());
                                             System.out.println(clazz.getName());
                                             System.out.println(clazz.getPackage());
                                             System.out.println(clazz.getModifiers());
                                             System.out.println(clazz.getDeclaredMethod("main", String[].class));
                                             System.out.println(Modifier.toString(clazz.getDeclaredMethod("main", String[].class).getModifiers()));
                              } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
                                             e.printStackTrace();
                              }
               }
}

2.2         2015Q1Answers

public class Answer {
               public static void main(String[] args) {
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.User");

                                             User user = (User) clz.newInstance();
                                             System.out.println(user.toString());

                                             Field username = clz.getDeclaredField("username");
                                             username.setAccessible(true);
                                             Field passsowrd = clz.getDeclaredField("password");
                                             passsowrd.setAccessible(true);

                                             username.set(user, "MTIT_Admin");
                                             passsowrd.set(user, "admin123");

                                             System.out.println(user.toString());

                              } catch (ClassNotFoundException | SecurityException e) {
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (NoSuchFieldException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }
}

---------------------------------------------------------------------------------------------------------------------------------
public class AnswerB {

               public static void main(String[] args) {
                              Class<?> clazz;
                              try {
                                             clazz = Class.forName("com.mtit.q1.b.Employee");

                                             // Q1 Part B
                                             Constructor[] constructors = clazz.getConstructors();
                                             for (Constructor constructor : constructors) {
                                                            Parameter[] param = constructor.getParameters();
                                                            for (Parameter parameter : param) {
                                                                           System.out.println(parameter.getType());
                                                            }
                                             }
                                             // Q1 Part B
                                             // This Also should work. But its not working :( I don't know why
                                             // Employee emp =(Employee)clazz.getConstructor(String.class,String.class,Integer.class,Double.class).newInstance("Nimal",
                                             // "Colombo 10", 30001, 65000.80);
                                             // emp.displayEmployeeDetails();

                                             Constructor[] constructors1 = clazz.getConstructors();
                                             for (Constructor constructor : constructors1) {
                                                            Employee emp1 = (Employee) constructor.newInstance("Nimal", "Colombo 10", 30001, 65000.80); // can
                                                            emp1.displayEmployeeDetails();
                                             }
                             

                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }

               }

}

2.3         2015RQ1Answers

public class CalculateTest {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                                             Calculate calculate =  (Calculate)clz.newInstance();
                                            
                                             Field[] fields = clz.getDeclaredFields();
                                             for (Field field : fields) {
                                                            field.setAccessible(true);
                                                            System.out.println(field.getName()+" = "+field.get(calculate));
                                             }
                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }

}
---------------------------------------------------------------------------------------------------------------------
               try {
                              Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                              Calculate calculate =  (Calculate)clz.newInstance();
                                            
                              Method method = clz.getDeclaredMethod("calculate", String.class);
                                             method.invoke(calculate, "+");
                                            
                              }


Employee e = new Employee();
                   
                    Class[] parameters = new Class[4];
                    parameters[0] = String.class;
                    parameters[1] = String.class;
                    parameters[2] = String.class;
                    parameters[3] = Double.TYPE;
                   
Method method = e.getClass().getDeclaredMethod("display", parameters);


System.out.println( "Authors = " + Arrays.asList((String [])clazz.getField("authors").get(b)));
        
       Field price = clazz.getDeclaredField("price");
       price.setDouble(b, 234.6);


Employee b = new Employee();
                    Class<?> clazz = b.getClass();
                    Method[] allMethods = clazz.getDeclaredMethods();
                   
for(Method m:allMethods){
String s =" Modifier => " +Modifier.toString(m.getModifiers())+"|| Return Type => " +m.getReturnType()+"|| Method Name => " + m.getName();
             if(m.getParameterCount()>0){
             java.lang.reflect.Parameter[] p = m.getParameters();
                    String pr ="";
             for (int i = 0; i < p.length; i++) {
                         pr=pr+ p[i].toString()+" ,";
}
                    String e=" ||parameters =>"+pr;
                    s=s+e;
                           }
                           System.out.println( s);
                           System.out.println("");


Useful Links:



***Coding Standard 

            XML-JSON------------------------------------------------------------



{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}


XPath
JSONPath
Result
/store/book/author
$.store.book[*].author
the authors of all books in the store
//author
$..author
all authors
/store/*
$.store.*
all things in store, which are some books and a red bicycle.
/store//price
$.store..price
the price of everything in the store.
//book[3]
$..book[2]
the third book
//book[last()]
$..book[(@.length-1)]
$..book[-1:]
the last book in order.
//book[position()<3]
$..book[0,1]
$..book[:2]
the first two books
//book[isbn]
$..book[?(@.isbn)]
filter all books with isbn number
//book[price<10]
$..book[?(@.price<10)]
filter all books cheapier than 10
//*
$..*
all Elements in XML document. All members of JSON structure.

Path
JSONPath
Description
/
$
the root object/element
.
@
the current object/element
/
. or []
child operator
..
n/a
parent operator
//
..
recursive descent. JSONPath borrows this syntax from E4X.
*
*
wildcard. All objects/elements regardless their names.
@
n/a
attribute access. JSON structures don't have attributes.
[]
[]
subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|
[,]
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a
[start:end:step]
array slice operator borrowed from ES4.
[]
?()
applies a filter (script) expression.
n/a
()
script expression, using the underlying script engine.
()
n/a
grouping in Xpath


Write to a json file
public class JSONSimpleWritingToFileExample {
      public static void main(String[] args) { 
             
        JSONObject countryObj = new JSONObject(); 
        countryObj.put("Name", "India")
        countryObj.put("Population", new Integer(1000000))
 
        JSONArray listOfStates = new JSONArray(); 
        listOfStates.add("Madhya Pradesh")
        listOfStates.add("Maharastra")
        listOfStates.add("Rajasthan")
 
        countryObj.put("States", listOfStates)
 
        try
             
            // Writing to a file 
            File file=new File("D:\\SLIIT\\CountryJSONFile.json"); 
            file.createNewFile(); 
            FileWriter fileWriter = new FileWriter(file); 
            System.out.println("Writing JSON object to file"); 
            System.out.println("-----------------------"); 
            System.out.print(countryObj); 
 
            fileWriter.write(countryObj.toJSONString()); 
            fileWriter.flush(); 
            fileWriter.close(); 
 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
 
    } 
}
Read from a json file
public class JSONSimpleReadingFromFileExample {
      public static void main(String[] args) throws org.json.simple.parser.ParseException, ParseException { 
             
              JSONParser parser = new JSONParser(); 
             
              try
             
               Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json")); 
             
               JSONObject jsonObject = (JSONObject) obj
             
               String nameOfCountry = (String) jsonObject.get("Name"); 
               System.out.println("Name Of Country: "+nameOfCountry); 
             
               long population = (Long) jsonObject.get("Population"); 
               System.out.println("Population: "+population); 
             
               //String state = with(Object).get("store.book[0].category");
               //String state = (String) jsonObject.get("States[0]"); 
               //System.out.println("Name Of STATE: "+state);
              
               System.out.println("States are :"); 
               JSONArray listOfStates = (JSONArray) jsonObject.get("States"); 
               Iterator<String> iterator = listOfStates.iterator()
               while (iterator.hasNext()) { 
                System.out.println(iterator.next()); 
               } 
             
              } catch (FileNotFoundException e) { 
               e.printStackTrace(); 
              } catch (IOException e) { 
               e.printStackTrace(); 
              } 
             
             } 
}

            ESB---------------------------------------------------------------------

4.1         Inside Proxy

<inSequence>
         <property name="DISABLE_CHUNKING" value="true" scope="axis2"/>
</inSequence>

4.2         Error Troubleshooting Tips for w3school service (This only for w3school)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
<soap:Header/>
            <soap:Body>
                        <x:CelsiusToFahrenheit>
                        <!--Optional:-->
                                    <x:Celsius>0</x:Celsius>
                        </x:CelsiusToFahrenheit>
            </soap:Body>
</soap:Envelope>

4.3         connector.xml

<?xml version="1.0" encoding="UTF-8"?>
<connector>
    <component name="twitter" package="org.wso2.carbon.connector" >
            <dependency component="twitter_config"/>
            <dependency component="twitter_direct_messages"/>
            <dependency component="twitter_friends_followers"/>
            <description>WSO2 Connector for Twitter</description>
    </component>
</connector>

4.4         Methods.csv

googlecontacts_config,init,userEmail:username:password,Configuration file.
googlecontacts_contacts,retrieveAllContacts,,Retrieve all user contacts.

4.5         Init.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="init" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="apiUrl" description="The apiUrl" />
                        <parameter name="accessToken" description="The accessToken" />
                        <sequence>
                                                <property expression="$func:apiUrl" name="uri.var.url" />
                                                <property expression="$func:accessToken" name="uri.var.accessToken" />

                                                <property name="uri.var.auth" expression="fn:concat('Bearer ', $ctx:uri.var.accessToken)"/>
                                            <property name="Authorization" expression="$ctx:uri.var.auth" scope="transport"/>

            </sequence>
</template>

4.6         templateMethod.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="publishPost" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="blogId" description="The blogId" />
                        <sequence>
                                                <property expression="$func:blogId" name="uri.var.blogId" />
                                                <property name="Accept-Encoding" action="remove" scope="transport" />
                                                <property name="messageType" scope="axis2" value="application/json" />

                                    <call>
                                    <endpoint>
                                                <http method="get" uri-template="https://www.googleapis.com/blogger/v3/blogs/{uri.var.blogId}/posts" />
                                    </endpoint>
                        </call>
            </sequence>
</template>

4.7         Proxy.txt

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
                        name="GetBlogs"
                         transports="https,http"
                         statistics="disable"
                         trace="disable"
                         startOnLoad="true">
             <target>
                        <inSequence>
                                    <property name="apiUrl" expression="json-eval($.apiUrl)"/>
                                     <property name="accessToken" expression="json-eval($.accessToken"/>
                                     <property name="blogId" expression="json-eval($.blogId)"/>
            <blogger.init>
                        <apiUrl>{$ctx:apiUrl}</apiUrl>
                        <acessToken>{$ctx:acessToken}</acessToken>
            </blogger.init>
            <blogger.GetBlogs>
                        <blogId>{$ctx:blogId}</blogId>
            </blogger.GetBlogs>
            <property name="messageType" value="application/json" scope="axis2"/>
            <respond/>
            </inSequence>
            <outSequence>
                        <log level="full"/>
                        <send/>
            </outSequence>
            </target>
 <description/>
</proxy>




            Additional-------------------------Exam Support


            OSGi--------------------------------------------------------------------

1)OPEN ECLIPSE (in my case HELIOS JavaEE)

2)CREATE SERVICE PROJECT
            i) File => new => OSGi bundle project => next
                        OR
                        File => new => plug-in project =>eclipse version 3.6

            ii) Project name = com.mtit.osgi.Service
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name "ServerActivator"
            v) finish

3)CREATE CLIENT PROJECT
            i) File => new => plug-in project =>eclipse version 3.6
            ii) Project name = com.mtit.osgi.Client
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name as "ClientActivator"
            v) finish

4)CREATE INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> interface
            ii) name = "IServiceActions"
            ii) add function skeletons to interface
                        public String PrintService();
                        public String Hello();

5)IMPLEMENT INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> class (implements "IServiceActions")
            ii) name = "ServiceActions"
            iii) implement methods
                        public String PrintService(){
                                    return "execute print service";
                        }
                        public String Hello(){
                                    return "Hello!!";
                        }

6)IMPLEMENT Start() FUNCTION IN "ServerActivator"
            i) create global variable in the class
                         org.osgi.framework.ServiceRegistration serviceReg;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("service started");
                        IServiceActions sactions = new ServiceActions();
                        serviceReg = context.registerService(IServiceActions.class.getName(),sactions,null);

7)IMPLEMENT Stop() FUNCTION IN "ServerActivator"
            i) comment whatever lines inside Stop() method(or keep as it is)
            ii) type
                        serviceReg.unregister();
                        System.out.println("service stopped");


8)ADD org.osgi.service PROJECT TO org.osgi.client BUILD PATH
            i)right click org.osgi.client --> properties --> java build path --> "project" tab
            ii)add --> select org.osgi.service --> ok

6)IMPLEMENT Start() FUNCTION IN "ClientActivator"
            i) create global variable in the class
                        org.osgi.framework.ServiceReference serviceRef;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("client starts!!");
                        serviceRef = context.getServiceReference(IServiceActions.class.getName());
                        ServiceActions sactions = (ServiceActions)context.getService(serviceRef);
                        System.out.println(sactions.Hello());
                        System.out.println(sactions.PrintService());

                       
7)NEED NOT TO IMPLEMENT Stop() FUNCTION IN "ServerActivator".Keep as it is unless asked.

8)EXPORT org.osgi.service RUNTIME PACKAGES
            i) open org.osgi.service MANIFEST.MF file
            ii) open "Runtine" tab --> add --> select "org.osgi.service" --> ok
           

9)ADD DEPENDENCIES TO org.osgi.client
            i) open org.osgi.client MANIFEST.MF file
            ii) open "Dependencies" tab --> add imported package--> search and select "org.osgi.service" --> ok


10) RUN org.osgi.service (as osgi framework project)
    RUN org.osgi.client


----------------Client-------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Client
Bundle-SymbolicName: com.mtit.osgi.Client
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.client.ClientActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Import-Package: org.osgi.framework;version="1.3.0", com.mtit.osgi.service

------------Server----------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Service
Bundle-SymbolicName: com.mtit.osgi.Service
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.service.ServerActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ActivationPolicy: lazy
Export-Package: com.mtit.osgi.service
Import-Package: org.osgi.framework;version="1.3.0"


Configure osgiFramework(Run As OSGIFramework)
Deselect all
Add felix, eqoix.consol ,
Com.mtit.osgi.client/service

Runà after error add required bundle


***Coding Standard 





























            Reflections-----------------------------------------------------------

2.1         Lab.Task1

import java.lang.reflect.Modifier;

public class Task1 {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clazz = Class.forName("com.mtit.lab.task1.Task1");
                                             System.out.println(clazz.getSimpleName());
                                             System.out.println(clazz.getName());
                                             System.out.println(clazz.getPackage());
                                             System.out.println(clazz.getModifiers());
                                             System.out.println(clazz.getDeclaredMethod("main", String[].class));
                                             System.out.println(Modifier.toString(clazz.getDeclaredMethod("main", String[].class).getModifiers()));
                              } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
                                             e.printStackTrace();
                              }
               }
}

2.2         2015Q1Answers

public class Answer {
               public static void main(String[] args) {
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.User");

                                             User user = (User) clz.newInstance();
                                             System.out.println(user.toString());

                                             Field username = clz.getDeclaredField("username");
                                             username.setAccessible(true);
                                             Field passsowrd = clz.getDeclaredField("password");
                                             passsowrd.setAccessible(true);

                                             username.set(user, "MTIT_Admin");
                                             passsowrd.set(user, "admin123");

                                             System.out.println(user.toString());

                              } catch (ClassNotFoundException | SecurityException e) {
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (NoSuchFieldException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }
}

---------------------------------------------------------------------------------------------------------------------------------
public class AnswerB {

               public static void main(String[] args) {
                              Class<?> clazz;
                              try {
                                             clazz = Class.forName("com.mtit.q1.b.Employee");

                                             // Q1 Part B
                                             Constructor[] constructors = clazz.getConstructors();
                                             for (Constructor constructor : constructors) {
                                                            Parameter[] param = constructor.getParameters();
                                                            for (Parameter parameter : param) {
                                                                           System.out.println(parameter.getType());
                                                            }
                                             }
                                             // Q1 Part B
                                             // This Also should work. But its not working :( I don't know why
                                             // Employee emp =(Employee)clazz.getConstructor(String.class,String.class,Integer.class,Double.class).newInstance("Nimal",
                                             // "Colombo 10", 30001, 65000.80);
                                             // emp.displayEmployeeDetails();

                                             Constructor[] constructors1 = clazz.getConstructors();
                                             for (Constructor constructor : constructors1) {
                                                            Employee emp1 = (Employee) constructor.newInstance("Nimal", "Colombo 10", 30001, 65000.80); // can
                                                            emp1.displayEmployeeDetails();
                                             }
                             

                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }

               }

}

2.3         2015RQ1Answers

public class CalculateTest {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                                             Calculate calculate =  (Calculate)clz.newInstance();
                                            
                                             Field[] fields = clz.getDeclaredFields();
                                             for (Field field : fields) {
                                                            field.setAccessible(true);
                                                            System.out.println(field.getName()+" = "+field.get(calculate));
                                             }
                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }

}
---------------------------------------------------------------------------------------------------------------------
               try {
                              Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                              Calculate calculate =  (Calculate)clz.newInstance();
                                            
                              Method method = clz.getDeclaredMethod("calculate", String.class);
                                             method.invoke(calculate, "+");
                                            
                              }


Employee e = new Employee();
                   
                    Class[] parameters = new Class[4];
                    parameters[0] = String.class;
                    parameters[1] = String.class;
                    parameters[2] = String.class;
                    parameters[3] = Double.TYPE;
                   
Method method = e.getClass().getDeclaredMethod("display", parameters);


System.out.println( "Authors = " + Arrays.asList((String [])clazz.getField("authors").get(b)));
        
       Field price = clazz.getDeclaredField("price");
       price.setDouble(b, 234.6);


Employee b = new Employee();
                    Class<?> clazz = b.getClass();
                    Method[] allMethods = clazz.getDeclaredMethods();
                   
for(Method m:allMethods){
String s =" Modifier => " +Modifier.toString(m.getModifiers())+"|| Return Type => " +m.getReturnType()+"|| Method Name => " + m.getName();
             if(m.getParameterCount()>0){
             java.lang.reflect.Parameter[] p = m.getParameters();
                    String pr ="";
             for (int i = 0; i < p.length; i++) {
                         pr=pr+ p[i].toString()+" ,";
}
                    String e=" ||parameters =>"+pr;
                    s=s+e;
                           }
                           System.out.println( s);
                           System.out.println("");


Useful Links:



***Coding Standard 

            XML-JSON------------------------------------------------------------



{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}


XPath
JSONPath
Result
/store/book/author
$.store.book[*].author
the authors of all books in the store
//author
$..author
all authors
/store/*
$.store.*
all things in store, which are some books and a red bicycle.
/store//price
$.store..price
the price of everything in the store.
//book[3]
$..book[2]
the third book
//book[last()]
$..book[(@.length-1)]
$..book[-1:]
the last book in order.
//book[position()<3]
$..book[0,1]
$..book[:2]
the first two books
//book[isbn]
$..book[?(@.isbn)]
filter all books with isbn number
//book[price<10]
$..book[?(@.price<10)]
filter all books cheapier than 10
//*
$..*
all Elements in XML document. All members of JSON structure.

Path
JSONPath
Description
/
$
the root object/element
.
@
the current object/element
/
. or []
child operator
..
n/a
parent operator
//
..
recursive descent. JSONPath borrows this syntax from E4X.
*
*
wildcard. All objects/elements regardless their names.
@
n/a
attribute access. JSON structures don't have attributes.
[]
[]
subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|
[,]
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a
[start:end:step]
array slice operator borrowed from ES4.
[]
?()
applies a filter (script) expression.
n/a
()
script expression, using the underlying script engine.
()
n/a
grouping in Xpath


Write to a json file
public class JSONSimpleWritingToFileExample {
      public static void main(String[] args) { 
             
        JSONObject countryObj = new JSONObject(); 
        countryObj.put("Name", "India")
        countryObj.put("Population", new Integer(1000000))
 
        JSONArray listOfStates = new JSONArray(); 
        listOfStates.add("Madhya Pradesh")
        listOfStates.add("Maharastra")
        listOfStates.add("Rajasthan")
 
        countryObj.put("States", listOfStates)
 
        try
             
            // Writing to a file 
            File file=new File("D:\\SLIIT\\CountryJSONFile.json"); 
            file.createNewFile(); 
            FileWriter fileWriter = new FileWriter(file); 
            System.out.println("Writing JSON object to file"); 
            System.out.println("-----------------------"); 
            System.out.print(countryObj); 
 
            fileWriter.write(countryObj.toJSONString()); 
            fileWriter.flush(); 
            fileWriter.close(); 
 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
 
    } 
}
Read from a json file
public class JSONSimpleReadingFromFileExample {
      public static void main(String[] args) throws org.json.simple.parser.ParseException, ParseException { 
             
              JSONParser parser = new JSONParser(); 
             
              try
             
               Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json")); 
             
               JSONObject jsonObject = (JSONObject) obj
             
               String nameOfCountry = (String) jsonObject.get("Name"); 
               System.out.println("Name Of Country: "+nameOfCountry); 
             
               long population = (Long) jsonObject.get("Population"); 
               System.out.println("Population: "+population); 
             
               //String state = with(Object).get("store.book[0].category");
               //String state = (String) jsonObject.get("States[0]"); 
               //System.out.println("Name Of STATE: "+state);
              
               System.out.println("States are :"); 
               JSONArray listOfStates = (JSONArray) jsonObject.get("States"); 
               Iterator<String> iterator = listOfStates.iterator()
               while (iterator.hasNext()) { 
                System.out.println(iterator.next()); 
               } 
             
              } catch (FileNotFoundException e) { 
               e.printStackTrace(); 
              } catch (IOException e) { 
               e.printStackTrace(); 
              } 
             
             } 
}

            ESB---------------------------------------------------------------------

4.1         Inside Proxy

<inSequence>
         <property name="DISABLE_CHUNKING" value="true" scope="axis2"/>
</inSequence>

4.2         Error Troubleshooting Tips for w3school service (This only for w3school)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
<soap:Header/>
            <soap:Body>
                        <x:CelsiusToFahrenheit>
                        <!--Optional:-->
                                    <x:Celsius>0</x:Celsius>
                        </x:CelsiusToFahrenheit>
            </soap:Body>
</soap:Envelope>

4.3         connector.xml

<?xml version="1.0" encoding="UTF-8"?>
<connector>
    <component name="twitter" package="org.wso2.carbon.connector" >
            <dependency component="twitter_config"/>
            <dependency component="twitter_direct_messages"/>
            <dependency component="twitter_friends_followers"/>
            <description>WSO2 Connector for Twitter</description>
    </component>
</connector>

4.4         Methods.csv

googlecontacts_config,init,userEmail:username:password,Configuration file.
googlecontacts_contacts,retrieveAllContacts,,Retrieve all user contacts.

4.5         Init.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="init" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="apiUrl" description="The apiUrl" />
                        <parameter name="accessToken" description="The accessToken" />
                        <sequence>
                                                <property expression="$func:apiUrl" name="uri.var.url" />
                                                <property expression="$func:accessToken" name="uri.var.accessToken" />

                                                <property name="uri.var.auth" expression="fn:concat('Bearer ', $ctx:uri.var.accessToken)"/>
                                            <property name="Authorization" expression="$ctx:uri.var.auth" scope="transport"/>

            </sequence>
</template>

4.6         templateMethod.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="publishPost" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="blogId" description="The blogId" />
                        <sequence>
                                                <property expression="$func:blogId" name="uri.var.blogId" />
                                                <property name="Accept-Encoding" action="remove" scope="transport" />
                                                <property name="messageType" scope="axis2" value="application/json" />

                                    <call>
                                    <endpoint>
                                                <http method="get" uri-template="https://www.googleapis.com/blogger/v3/blogs/{uri.var.blogId}/posts" />
                                    </endpoint>
                        </call>
            </sequence>
</template>

4.7         Proxy.txt

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
                        name="GetBlogs"
                         transports="https,http"
                         statistics="disable"
                         trace="disable"
                         startOnLoad="true">
             <target>
                        <inSequence>
                                    <property name="apiUrl" expression="json-eval($.apiUrl)"/>
                                     <property name="accessToken" expression="json-eval($.accessToken"/>
                                     <property name="blogId" expression="json-eval($.blogId)"/>
            <blogger.init>
                        <apiUrl>{$ctx:apiUrl}</apiUrl>
                        <acessToken>{$ctx:acessToken}</acessToken>
            </blogger.init>
            <blogger.GetBlogs>
                        <blogId>{$ctx:blogId}</blogId>
            </blogger.GetBlogs>
            <property name="messageType" value="application/json" scope="axis2"/>
            <respond/>
            </inSequence>
            <outSequence>
                        <log level="full"/>
                        <send/>
            </outSequence>
            </target>
 <description/>
</proxy>




            Additional-------------------------------------------------------------

5.1         Get console Inputs

               Scanner input = new Scanner(System.in);
               System.out.print("Enter number of rows: ");
               int rows = input.nextInt();
               System.out.print("Enter number of columns: ");
               int cols = input.nextInt();

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); word = in.readLine();

5.2         Read File

/**
                * Another method to read all file
                * @param path
                * @param encoding like StandardCharsets.UTF_8
                * @return file content
                * @throws IOException
                *
                * http://stackoverflow.com/questions/326390/how-to-create-a-java-Exam Support

            OSGi--------------------------------------------------------------------

1)OPEN ECLIPSE (in my case HELIOS JavaEE)

2)CREATE SERVICE PROJECT
            i) File => new => OSGi bundle project => next
                        OR
                        File => new => plug-in project =>eclipse version 3.6

            ii) Project name = com.mtit.osgi.Service
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name "ServerActivator"
            v) finish

3)CREATE CLIENT PROJECT
            i) File => new => plug-in project =>eclipse version 3.6
            ii) Project name = com.mtit.osgi.Client
            iii) ECLIPSE VERSION 3.6 -> NEXT
            iv) set ACTIVATOR name as "ClientActivator"
            v) finish

4)CREATE INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> interface
            ii) name = "IServiceActions"
            ii) add function skeletons to interface
                        public String PrintService();
                        public String Hello();

5)IMPLEMENT INTERFACE IN SERVICE PROJECT
            i) right click package --> new --> class (implements "IServiceActions")
            ii) name = "ServiceActions"
            iii) implement methods
                        public String PrintService(){
                                    return "execute print service";
                        }
                        public String Hello(){
                                    return "Hello!!";
                        }

6)IMPLEMENT Start() FUNCTION IN "ServerActivator"
            i) create global variable in the class
                         org.osgi.framework.ServiceRegistration serviceReg;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("service started");
                        IServiceActions sactions = new ServiceActions();
                        serviceReg = context.registerService(IServiceActions.class.getName(),sactions,null);

7)IMPLEMENT Stop() FUNCTION IN "ServerActivator"
            i) comment whatever lines inside Stop() method(or keep as it is)
            ii) type
                        serviceReg.unregister();
                        System.out.println("service stopped");


8)ADD org.osgi.service PROJECT TO org.osgi.client BUILD PATH
            i)right click org.osgi.client --> properties --> java build path --> "project" tab
            ii)add --> select org.osgi.service --> ok

6)IMPLEMENT Start() FUNCTION IN "ClientActivator"
            i) create global variable in the class
                        org.osgi.framework.ServiceReference serviceRef;

            ii) comment whatever lines inside Start() method(or keep as it is)
            iii) type
                        System.out.println("client starts!!");
                        serviceRef = context.getServiceReference(IServiceActions.class.getName());
                        ServiceActions sactions = (ServiceActions)context.getService(serviceRef);
                        System.out.println(sactions.Hello());
                        System.out.println(sactions.PrintService());

                       
7)NEED NOT TO IMPLEMENT Stop() FUNCTION IN "ServerActivator".Keep as it is unless asked.

8)EXPORT org.osgi.service RUNTIME PACKAGES
            i) open org.osgi.service MANIFEST.MF file
            ii) open "Runtine" tab --> add --> select "org.osgi.service" --> ok
           

9)ADD DEPENDENCIES TO org.osgi.client
            i) open org.osgi.client MANIFEST.MF file
            ii) open "Dependencies" tab --> add imported package--> search and select "org.osgi.service" --> ok


10) RUN org.osgi.service (as osgi framework project)
    RUN org.osgi.client


----------------Client-------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Client
Bundle-SymbolicName: com.mtit.osgi.Client
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.client.ClientActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Import-Package: org.osgi.framework;version="1.3.0", com.mtit.osgi.service

------------Server----------------------
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Service
Bundle-SymbolicName: com.mtit.osgi.Service
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.mtit.osgi.service.ServerActivator
Bundle-Vendor: MTIT
Require-Bundle: org.eclipse.ui,
 org.eclipse.core.runtime
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ActivationPolicy: lazy
Export-Package: com.mtit.osgi.service
Import-Package: org.osgi.framework;version="1.3.0"


Configure osgiFramework(Run As OSGIFramework)
Deselect all
Add felix, eqoix.consol ,
Com.mtit.osgi.client/service

Runà after error add required bundle


***Coding Standard 





























            Reflections-----------------------------------------------------------

2.1         Lab.Task1

import java.lang.reflect.Modifier;

public class Task1 {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clazz = Class.forName("com.mtit.lab.task1.Task1");
                                             System.out.println(clazz.getSimpleName());
                                             System.out.println(clazz.getName());
                                             System.out.println(clazz.getPackage());
                                             System.out.println(clazz.getModifiers());
                                             System.out.println(clazz.getDeclaredMethod("main", String[].class));
                                             System.out.println(Modifier.toString(clazz.getDeclaredMethod("main", String[].class).getModifiers()));
                              } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
                                             e.printStackTrace();
                              }
               }
}

2.2         2015Q1Answers

public class Answer {
               public static void main(String[] args) {
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.User");

                                             User user = (User) clz.newInstance();
                                             System.out.println(user.toString());

                                             Field username = clz.getDeclaredField("username");
                                             username.setAccessible(true);
                                             Field passsowrd = clz.getDeclaredField("password");
                                             passsowrd.setAccessible(true);

                                             username.set(user, "MTIT_Admin");
                                             passsowrd.set(user, "admin123");

                                             System.out.println(user.toString());

                              } catch (ClassNotFoundException | SecurityException e) {
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (NoSuchFieldException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }
}

---------------------------------------------------------------------------------------------------------------------------------
public class AnswerB {

               public static void main(String[] args) {
                              Class<?> clazz;
                              try {
                                             clazz = Class.forName("com.mtit.q1.b.Employee");

                                             // Q1 Part B
                                             Constructor[] constructors = clazz.getConstructors();
                                             for (Constructor constructor : constructors) {
                                                            Parameter[] param = constructor.getParameters();
                                                            for (Parameter parameter : param) {
                                                                           System.out.println(parameter.getType());
                                                            }
                                             }
                                             // Q1 Part B
                                             // This Also should work. But its not working :( I don't know why
                                             // Employee emp =(Employee)clazz.getConstructor(String.class,String.class,Integer.class,Double.class).newInstance("Nimal",
                                             // "Colombo 10", 30001, 65000.80);
                                             // emp.displayEmployeeDetails();

                                             Constructor[] constructors1 = clazz.getConstructors();
                                             for (Constructor constructor : constructors1) {
                                                            Employee emp1 = (Employee) constructor.newInstance("Nimal", "Colombo 10", 30001, 65000.80); // can
                                                            emp1.displayEmployeeDetails();
                                             }
                             

                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }

               }

}

2.3         2015RQ1Answers

public class CalculateTest {

               public static void main(String[] args) {
                              // TODO Auto-generated method stub
                              try {
                                             Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                                             Calculate calculate =  (Calculate)clz.newInstance();
                                            
                                             Field[] fields = clz.getDeclaredFields();
                                             for (Field field : fields) {
                                                            field.setAccessible(true);
                                                            System.out.println(field.getName()+" = "+field.get(calculate));
                                             }
                              } catch (ClassNotFoundException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (InstantiationException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              } catch (IllegalAccessException e) {
                                             // TODO Auto-generated catch block
                                             e.printStackTrace();
                              }
               }

}
---------------------------------------------------------------------------------------------------------------------
               try {
                              Class<?> clz = Class.forName("com.mtit.q1.b.Calculate");
                              Calculate calculate =  (Calculate)clz.newInstance();
                                            
                              Method method = clz.getDeclaredMethod("calculate", String.class);
                                             method.invoke(calculate, "+");
                                            
                              }


Employee e = new Employee();
                   
                    Class[] parameters = new Class[4];
                    parameters[0] = String.class;
                    parameters[1] = String.class;
                    parameters[2] = String.class;
                    parameters[3] = Double.TYPE;
                   
Method method = e.getClass().getDeclaredMethod("display", parameters);


System.out.println( "Authors = " + Arrays.asList((String [])clazz.getField("authors").get(b)));
        
       Field price = clazz.getDeclaredField("price");
       price.setDouble(b, 234.6);


Employee b = new Employee();
                    Class<?> clazz = b.getClass();
                    Method[] allMethods = clazz.getDeclaredMethods();
                   
for(Method m:allMethods){
String s =" Modifier => " +Modifier.toString(m.getModifiers())+"|| Return Type => " +m.getReturnType()+"|| Method Name => " + m.getName();
             if(m.getParameterCount()>0){
             java.lang.reflect.Parameter[] p = m.getParameters();
                    String pr ="";
             for (int i = 0; i < p.length; i++) {
                         pr=pr+ p[i].toString()+" ,";
}
                    String e=" ||parameters =>"+pr;
                    s=s+e;
                           }
                           System.out.println( s);
                           System.out.println("");


Useful Links:



***Coding Standard 

            XML-JSON------------------------------------------------------------



{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}


XPath
JSONPath
Result
/store/book/author
$.store.book[*].author
the authors of all books in the store
//author
$..author
all authors
/store/*
$.store.*
all things in store, which are some books and a red bicycle.
/store//price
$.store..price
the price of everything in the store.
//book[3]
$..book[2]
the third book
//book[last()]
$..book[(@.length-1)]
$..book[-1:]
the last book in order.
//book[position()<3]
$..book[0,1]
$..book[:2]
the first two books
//book[isbn]
$..book[?(@.isbn)]
filter all books with isbn number
//book[price<10]
$..book[?(@.price<10)]
filter all books cheapier than 10
//*
$..*
all Elements in XML document. All members of JSON structure.

Path
JSONPath
Description
/
$
the root object/element
.
@
the current object/element
/
. or []
child operator
..
n/a
parent operator
//
..
recursive descent. JSONPath borrows this syntax from E4X.
*
*
wildcard. All objects/elements regardless their names.
@
n/a
attribute access. JSON structures don't have attributes.
[]
[]
subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
|
[,]
Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.
n/a
[start:end:step]
array slice operator borrowed from ES4.
[]
?()
applies a filter (script) expression.
n/a
()
script expression, using the underlying script engine.
()
n/a
grouping in Xpath


Write to a json file
public class JSONSimpleWritingToFileExample {
      public static void main(String[] args) { 
             
        JSONObject countryObj = new JSONObject(); 
        countryObj.put("Name", "India")
        countryObj.put("Population", new Integer(1000000))
 
        JSONArray listOfStates = new JSONArray(); 
        listOfStates.add("Madhya Pradesh")
        listOfStates.add("Maharastra")
        listOfStates.add("Rajasthan")
 
        countryObj.put("States", listOfStates)
 
        try
             
            // Writing to a file 
            File file=new File("D:\\SLIIT\\CountryJSONFile.json"); 
            file.createNewFile(); 
            FileWriter fileWriter = new FileWriter(file); 
            System.out.println("Writing JSON object to file"); 
            System.out.println("-----------------------"); 
            System.out.print(countryObj); 
 
            fileWriter.write(countryObj.toJSONString()); 
            fileWriter.flush(); 
            fileWriter.close(); 
 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
 
    } 
}
Read from a json file
public class JSONSimpleReadingFromFileExample {
      public static void main(String[] args) throws org.json.simple.parser.ParseException, ParseException { 
             
              JSONParser parser = new JSONParser(); 
             
              try
             
               Object obj = parser.parse(new FileReader("E:\\CountryJSONFile.json")); 
             
               JSONObject jsonObject = (JSONObject) obj
             
               String nameOfCountry = (String) jsonObject.get("Name"); 
               System.out.println("Name Of Country: "+nameOfCountry); 
             
               long population = (Long) jsonObject.get("Population"); 
               System.out.println("Population: "+population); 
             
               //String state = with(Object).get("store.book[0].category");
               //String state = (String) jsonObject.get("States[0]"); 
               //System.out.println("Name Of STATE: "+state);
              
               System.out.println("States are :"); 
               JSONArray listOfStates = (JSONArray) jsonObject.get("States"); 
               Iterator<String> iterator = listOfStates.iterator()
               while (iterator.hasNext()) { 
                System.out.println(iterator.next()); 
               } 
             
              } catch (FileNotFoundException e) { 
               e.printStackTrace(); 
              } catch (IOException e) { 
               e.printStackTrace(); 
              } 
             
             } 
}

            ESB---------------------------------------------------------------------

4.1         Inside Proxy

<inSequence>
         <property name="DISABLE_CHUNKING" value="true" scope="axis2"/>
</inSequence>

4.2         Error Troubleshooting Tips for w3school service (This only for w3school)

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
<soap:Header/>
            <soap:Body>
                        <x:CelsiusToFahrenheit>
                        <!--Optional:-->
                                    <x:Celsius>0</x:Celsius>
                        </x:CelsiusToFahrenheit>
            </soap:Body>
</soap:Envelope>

4.3         connector.xml

<?xml version="1.0" encoding="UTF-8"?>
<connector>
    <component name="twitter" package="org.wso2.carbon.connector" >
            <dependency component="twitter_config"/>
            <dependency component="twitter_direct_messages"/>
            <dependency component="twitter_friends_followers"/>
            <description>WSO2 Connector for Twitter</description>
    </component>
</connector>

4.4         Methods.csv

googlecontacts_config,init,userEmail:username:password,Configuration file.
googlecontacts_contacts,retrieveAllContacts,,Retrieve all user contacts.

4.5         Init.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="init" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="apiUrl" description="The apiUrl" />
                        <parameter name="accessToken" description="The accessToken" />
                        <sequence>
                                                <property expression="$func:apiUrl" name="uri.var.url" />
                                                <property expression="$func:accessToken" name="uri.var.accessToken" />

                                                <property name="uri.var.auth" expression="fn:concat('Bearer ', $ctx:uri.var.accessToken)"/>
                                            <property name="Authorization" expression="$ctx:uri.var.auth" scope="transport"/>

            </sequence>
</template>

4.6         templateMethod.xml

<?xml version="1.0" encoding="UTF-8"?>
<template name="publishPost" xmlns="http://ws.apache.org/ns/synapse">
                        <parameter name="blogId" description="The blogId" />
                        <sequence>
                                                <property expression="$func:blogId" name="uri.var.blogId" />
                                                <property name="Accept-Encoding" action="remove" scope="transport" />
                                                <property name="messageType" scope="axis2" value="application/json" />

                                    <call>
                                    <endpoint>
                                                <http method="get" uri-template="https://www.googleapis.com/blogger/v3/blogs/{uri.var.blogId}/posts" />
                                    </endpoint>
                        </call>
            </sequence>
</template>

4.7         Proxy.txt

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
                        name="GetBlogs"
                         transports="https,http"
                         statistics="disable"
                         trace="disable"
                         startOnLoad="true">
             <target>
                        <inSequence>
                                    <property name="apiUrl" expression="json-eval($.apiUrl)"/>
                                     <property name="accessToken" expression="json-eval($.accessToken"/>
                                     <property name="blogId" expression="json-eval($.blogId)"/>
            <blogger.init>
                        <apiUrl>{$ctx:apiUrl}</apiUrl>
                        <acessToken>{$ctx:acessToken}</acessToken>
            </blogger.init>
            <blogger.GetBlogs>
                        <blogId>{$ctx:blogId}</blogId>
            </blogger.GetBlogs>
            <property name="messageType" value="application/json" scope="axis2"/>
            <respond/>
            </inSequence>
            <outSequence>
                        <log level="full"/>
                        <send/>
            </outSequence>
            </target>
 <description/>
</proxy>




            Additional-------------------------------------------------------------

5.1         Get console Inputs

               Scanner input = new Scanner(System.in);
               System.out.print("Enter number of rows: ");
               int rows = input.nextInt();
               System.out.print("Enter number of columns: ");
               int cols = input.nextInt();

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); word = in.readLine();

5.2         Read File

/**
                * Another method to read all file
                * @param path
                * @param encoding like StandardCharsets.UTF_8
                * @return file content
                * @throws IOException
                *
                * http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
                * readFile("howto.xml", StandardCharsets.UTF_8);
                */
               public static String readFile(String path, Charset encoding) throws IOException {
                              byte[] encoded = Files.readAllBytes(Paths.get(path));
                              return new String(encoded, encoding);
               }



Xpath: http://xmltoolbox.appspot.com/xpath_generator.html
jPath: //http://jsonpath.com/
json toXML: http://www.freeformatter.com/json-to-xml-converter.html#ad-output
***Coding Standard 
 -from-the-contents-of-a-file
                * readFile("howto.xml", StandardCharsets.UTF_8);
                */
               public static String readFile(String path, Charset encoding) throws IOException {
                              byte[] encoded = Files.readAllBytes(Paths.get(path));
                              return new String(encoded, encoding);
               }



Xpath: http://xmltoolbox.appspot.com/xpath_generator.html
jPath: //http://jsonpath.com/
json toXML: http://www.freeformatter.com/json-to-xml-converter.html#ad-output
***Coding Standard 

 ------------------------------------

5.1         Get console Inputs

               Scanner input = new Scanner(System.in);
               System.out.print("Enter number of rows: ");
               int rows = input.nextInt();
               System.out.print("Enter number of columns: ");
               int cols = input.nextInt();

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); word = in.readLine();

5.2         Read File

/**
                * Another method to read all file
                * @param path
                * @param encoding like StandardCharsets.UTF_8
                * @return file content
                * @throws IOException
                *
                * http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file
                * readFile("howto.xml", StandardCharsets.UTF_8);
                */
               public static String readFile(String path, Charset encoding) throws IOException {
                              byte[] encoded = Files.readAllBytes(Paths.get(path));
                              return new String(encoded, encoding);
               }



Xpath: http://xmltoolbox.appspot.com/xpath_generator.html
jPath: //http://jsonpath.com/
json toXML: http://www.freeformatter.com/json-to-xml-converter.html#ad-output
***Coding Standard