Sending a Tweet Using Apache Camel


Twitter is an online news and social networking service where users post and interact with messages.

POC on sending a tweet from java application using Apache camel API

Technologies used in this POC are :
1. JDK 1.7
2. Apache Camel 2.12.x
3. Maven.

Lets create a maven project.

open pom.xml add the below dependencies


 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
      <modelVersion>4.0.0</modelVersion>  
      <groupId>com.learning</groupId>  
      <artifactId>tweetingthroughapachecamel</artifactId>  
      <version>0.0.1-SNAPSHOT</version>  
      <dependencies>  
           <dependency>  
                <groupId>org.apache.camel</groupId>  
                <artifactId>camel-core</artifactId>  
                <version>2.12.0</version>  
           </dependency>  
           <dependency>  
                <groupId>org.apache.camel</groupId>  
                <artifactId>camel-twitter</artifactId>  
                <version>2.12.0</version>  
           </dependency>  
      </dependencies>  
 </project>  

Generate the ConsumerSecret,ConsumerKey,AccessToken and AccesstokenSecret from https://apps.twitter.com/

Now lets create a RouteBuilder JavatoTwitterRouteBuilder.java class

 package com.learning.apachecamel.twitter;  
 import org.apache.camel.builder.RouteBuilder;  
 public class JavatoTwitterRouteBuilder extends RouteBuilder {  
      @Override  
      public void configure() throws Exception {  
           // Generate the ConsumerSecret,ConsumerKey,AccessToken and  
           // AccesstokenSecret from https://apps.twitter.com/  
           from("direct:sendingtweet").to(  
                     "twitter://timeline/user?consumerKey=XYZ&consumerSecret=ZYZ&accessToken=ZYZ&accessTokenSecret=MAY");  
      }  
 }  
Lets create one more class to test the routes.


 package com.learning.apachecamel.twitter;  
 import org.apache.camel.CamelContext;  
 import org.apache.camel.ProducerTemplate;  
 import org.apache.camel.impl.DefaultCamelContext;  
 public class JavaTwittingClass {  
      public static void main(String[] args) {  
           CamelContext camelContext = new DefaultCamelContext();  
           try {  
                camelContext.addRoutes(new JavatoTwitterRouteBuilder());  
                ProducerTemplate producerTemplate=camelContext.createProducerTemplate();  
                camelContext.start();  
                producerTemplate.sendBody("direct:sendingtweet","This tweet is done from Java Application");  
                System.out.println("Message sent");  
           } catch (Exception e) {  
                System.err.println("Message not sent");  
                e.printStackTrace();  
           }  
      }  
 }  


Output:
   
 SLF4J: Defaulting to no-operation (NOP) logger implementation  
 SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.  
 Message sent  


Unmarshalling XML to Java (JAXB)

Unmarshalling XML to Java (JAXB)
JAXB : Stands for Java Architecture for XML binding. This framework helps us to convert Xml data to java content and Vice versa.

JaxB mainly uses two terminologies,
1. Unmarshalling : Reading Xml to Java content.
2. Marshalling : Writing Java Content to Xml

POC on UnMarshalling a sample XML file usercredentials.xml to Java Objects as below 

 <?xml version="1.0" encoding="UTF-8"?>  
 <config>  
      <Users>  
           <user>  
                <username>ABC</username>  
                <password>ABC@123</password>  
           </user>  
           <user>  
                <username>BBC</username>  
                <password>BBC@123</password>  
           </user>  
           <user>  
                <username>CBC</username>  
                <password>CBC@123</password>  
           </user>  
      </Users>  
 </config>  


Technologies used in this POC:

1. JDK 1.7
2. Maven 3.X
3. XSD 
4. XML 
5. JAXB 
6. Eclipse IDE


Create a new maven Project  in eclipse.

Open the pom.xml add the dependencies and plugin as below.

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
      <modelVersion>4.0.0</modelVersion>  
      <groupId>com.learning</groupId>  
      <artifactId>jaxbunmarshalling</artifactId>  
      <version>0.0.1-SNAPSHOT</version>  
      <dependencies>  
           <dependency>  
                <groupId>commons-configuration</groupId>  
                <artifactId>commons-configuration</artifactId>  
                <version>1.6</version>  
           </dependency>  
           <dependency>  
                <groupId>javax.xml.bind</groupId>  
                <artifactId>jaxb-api</artifactId>  
                <version>2.2.6</version>  
           </dependency>  
      </dependencies>  
      <build>  
           <plugins>  
                <!-- JAXB xjc plugin that invokes the xjc compiler to compile XML schema   
                     into Java classes. -->  
                <plugin>  
                     <groupId>org.codehaus.mojo</groupId>  
                     <artifactId>jaxb2-maven-plugin</artifactId>  
                     <version>1.5</version>  
                     <executions>  
                          <execution>  
                               <goals>  
                                    <goal>xjc</goal>  
                               </goals>  
                          </execution>  
                     </executions>  
                     <configuration>  
                          <schemaDirectory>${basedir}/src/main/resources/schema</schemaDirectory>  
                          <packageName>com.learning.usercredentials</packageName>  
                          <outputDirectory>${basedir}/src/main/java</outputDirectory>  
                          <removeOldOutput>false</removeOldOutput>  
                          <clearOutputDir>false</clearOutputDir>  
                          <forceRegenerate>true</forceRegenerate>  
                     </configuration>  
                </plugin>  
           </plugins>  
      </build>  
 </project>  
Now lets create an XSD usercredentials.xsd for XML
 xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">  
  <xs:element name="config">  
   <xs:complexType>  
    <xs:sequence>  
     <xs:element name="Users">  
      <xs:complexType>  
       <xs:sequence>  
        <xs:element name="user" maxOccurs="unbounded" minOccurs="0">  
         <xs:complexType>  
          <xs:sequence>  
           <xs:element type="xs:string" name="username"/>  
           <xs:element type="xs:string" name="password"/>  
          </xs:sequence>  
         </xs:complexType>  
        </xs:element>  
       </xs:sequence>  
      </xs:complexType>  
     </xs:element>  
    </xs:sequence>  
   </xs:complexType>  
  </xs:element>  
 </xs:schema>  

Create a folder called schema (not necessarily required) under src\main\resources of the project. and place the xsd file in the schema folder.


 
It generates XML bind classes from the XSD. We are using XSD in this Project because, so that strict structure of XML followed. even if there is a mismatch in the tag, XML will not be loaded.

Lets create a singleton class UnMarshallXmlToJava.java

 package com.learning.user.unmarshal;  
 import java.io.File;  
 import java.util.HashMap;  
 import java.util.List;  
 import java.util.Map;  
 import javax.xml.bind.JAXBContext;  
 import javax.xml.bind.JAXBException;  
 import javax.xml.bind.Unmarshaller;  
 import com.learning.usercredentials.Config;  
 import com.learning.usercredentials.Config.Users.User;  
 public class UnMarshallXmlToJava {  
      /*  
       * Reason for SingletonClass is, Keep on generating java contents of XML  
       * data is a memory overhead, so use it only required. So we load the XML  
       * data and exposing to the outside world through a method.  
       *   
       */  
      private static UnMarshallXmlToJava unMarshall = null;  
      private static Config config = null;  
      private UnMarshallXmlToJava() {  
           // Providing location of the xml file to file Object  
           try {  
                File xmlfile = new File(  
                          "src/main/resources/usercredentials.xml");  
                JAXBContext context = JAXBContext.newInstance("com.learning.usercredentials");  
                // creating an Unsmarshaller instance.  
                Unmarshaller unmarshaller = context.createUnmarshaller();  
                // loading the file object to the unmarshaller, and return type is  
                // typecasted to Config Class, by this Xml data is converted to java  
                // objects  
                config = (Config) unmarshaller.unmarshal(xmlfile);  
           } catch (JAXBException e) {  
                e.printStackTrace();  
           }  
      }  
      public static UnMarshallXmlToJava getInstance() {  
           if (unMarshall == null) {  
                unMarshall = new UnMarshallXmlToJava();  
                return unMarshall;  
           }  
           return null;  
      }  
      // returning the coverted XML to java content as a map.  
      public Map<String, String> getUserCredentials() {  
           Map<String, String> map = new HashMap<String, String>();  
           List<User> userList = config.getUsers().getUser();  
           for (User user : userList) {  
                map.put(user.getUsername(), user.getPassword());  
           }  
           return map;  
      }  
 }  

Lets create one more class TestingUnMarshaling.java to test the code.

 package com.learning.user.unmarshal;  
 import java.util.Map;  
 import java.util.Map.Entry;  
 public class TestingUnMarshaling {  
      public static void main(String[] args) {  
           Map<String, String> usersMap = UnMarshallXmlToJava.getInstance().getUserCredentials();  
           for (Entry<String, String> userEntry : usersMap.entrySet()) {  
                System.out.println("*********************************");  
                System.out.println("UserName : " + userEntry.getKey());  
                System.out.println("Password : " + userEntry.getValue());  
                System.out.println("*********************************");  
           }  
      }  
 }  

Output:

 *********************************  
 UserName : ABC  
 Password : ABC@123  
 *********************************  
 *********************************  
 UserName : BBC  
 Password : BBC@123  
 *********************************  
 *********************************  
 UserName : CBC  
 Password : CBC@123  
 *********************************  


Java Reflections Part -1

Java Reflections Part -1
Reflection API : Its a per-defined programming interface provided by JDK, which helps us to find out all the capabilities of a class at runtime.

POC of  Reflection API:

Part 1 consists POC on

1. Reflection on Class
2. Reflections on Methods
3. Reflections on Fields.

Finding out the class information.

Lets create a simple class  with name CompanyClassInformation

 package com.learning.reflections;  
 public class CompanyProfileInformation {  
      private String name;  
      private int age;  
      private String company;  
      public CompanyProfileInformation() {  
           System.out.println("Calling Constructor");  
           this.name = "bharani";  
           this.age = 26;  
           this.company = "EIL";  
           System.out.println(name);  
           System.out.println(age);  
           System.out.println(company);  
      }  
      public CompanyProfileInformation(String name, int age, String company) {  
           System.out.println("Calling Parameterized Constructor");  
           this.name = name;  
           this.age = age;  
           this.company = company;  
           System.out.println(this.name);  
           System.out.println(this.age);  
           System.out.println(this.company);  
      }  
      public void getName() {  
           System.out.println(this.name);  
      }  
      public void getAge() {  
           System.out.println(this.age);  
      }  
      public void getCompany() {  
           System.out.println(this.company);  
      }  
      public void getName(String name) {  
           System.out.println(name);  
      }  
      public void getAge(int age) {  
           System.out.println(age);  
      }  
      public void getCompany(String company) {  
           System.out.println(company);  
      }  
 } 
Lets create one more Class called FindingOutClassInformation, Which tells us the information like Class Name, Class Loaders, Constructors and Invoking default and paramterized constructor through reflections.
 package com.learning.reflections;  
 import java.lang.reflect.Constructor;  
 import java.lang.reflect.InvocationTargetException;  
 public class FindingOutClassInformation {  
      @SuppressWarnings({ "rawtypes", "unchecked" })  
      public static void main(String[] args) {  
           try {  
                Class companyProfileInformation = Class.forName("com.learning.reflections.CompanyProfileInformation");  
                // getName will provide you the Class Name with its Package  
                System.out.println(companyProfileInformation.getName());  
                // getName will provide you the Class Name without the package  
                System.out.println("*****************************");  
                System.out.println(companyProfileInformation.getSimpleName());  
                // getClassLoader will provide you the information about the  
                // ClassLoader which loads the class in the JVM.  
                System.out.println("*****************************");  
                System.out.println(companyProfileInformation.getClassLoader());  
                // provides you the information about Constructors  
                System.out.println("*****************************");  
                Constructor[] companyProfileInformationDeclaredConstructors = companyProfileInformation  
                          .getDeclaredConstructors();  
                for (Constructor constructor : companyProfileInformationDeclaredConstructors) {  
                     System.out.println(constructor.getName());  
                }  
                System.out.println("*****************************");  
                Constructor[] companyProfileInformationConstructors = companyProfileInformation.getConstructors();  
                for (Constructor constructor : companyProfileInformationConstructors) {  
                     System.out.println(constructor.getName());  
                }  
                // Invoking a parameterized Constructor  
                Constructor companyProfileInformationParameterizedConstructor = companyProfileInformation  
                          .getConstructor(String.class, int.class, String.class);  
                CompanyProfileInformation paramterizedobject = (CompanyProfileInformation) companyProfileInformationParameterizedConstructor  
                          .newInstance("Bharani", 27, "EGIL");  
                System.out.println("*****************************");  
                // Invoking default Constructor  
                Constructor companyProfileInformationdefaultConstructor = companyProfileInformation.getConstructor();  
                CompanyProfileInformation defaultobject = (CompanyProfileInformation) companyProfileInformationdefaultConstructor  
                          .newInstance();  
           } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
           } catch (NoSuchMethodException e) {  
                e.printStackTrace();  
           } catch (SecurityException e) {  
                e.printStackTrace();  
           } catch (InstantiationException e) {  
                e.printStackTrace();  
           } catch (IllegalAccessException e) {  
                e.printStackTrace();  
           } catch (IllegalArgumentException e) {  
                e.printStackTrace();  
           } catch (InvocationTargetException e) {  
                e.printStackTrace();  
           }  
      }  
 }  
output:
 com.learning.reflections.CompanyProfileInformation  
 *****************************  
 CompanyProfileInformation  
 *****************************  
 sun.misc.Launcher$AppClassLoader@3301f287  
 *****************************  
 com.learning.reflections.CompanyProfileInformation  
 com.learning.reflections.CompanyProfileInformation  
 *****************************  
 com.learning.reflections.CompanyProfileInformation  
 com.learning.reflections.CompanyProfileInformation  
 Calling Parameterized Constructor  
 Bharani  
 27  
 EGIL
 *****************************  
 Calling Constructor  
 bharani  
 26  
 EIL

Finding the information about the methods,declared Methods and invoking methods of a Class 

Lets create one more Class with Name  FindingOutTheMethodsOftheClass which provides us the information of methods of CompanyClassInformation through Reflections.

 package com.learning.reflections;  
 import java.lang.reflect.InvocationTargetException;  
 import java.lang.reflect.Method;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class FindingOutTheMethodsOftheClass {  
      @SuppressWarnings({ "rawtypes", "unchecked" })  
      public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,  
                IllegalArgumentException, InvocationTargetException, InstantiationException {  
           try {  
                // This will create a Class Object  
                Class complayProfileInformation = Class.forName("com.learning.reflections.CompanyProfileInformation");  
                // getMethods will return you the methods used in your current class  
                // as well as its super class.  
                // ***************************************************************  
                // complayProfileInformation Super class is Object, so the methods  
                // of Object class is also visible.  
                Method[] methods = complayProfileInformation.getMethods();  
                for (Method m : methods) {  
                     System.out.println(m.getName());  
                }  
                System.out.println("************************************************************************");  
                // getDeclaredMethods will return you the methods which are declared  
                // in the current class  
                Method[] declaredMethods = complayProfileInformation.getDeclaredMethods();  
                for (Method declaredm : declaredMethods) {  
                     System.out.println(declaredm.getName());  
                }  
                System.out.println("************************************************************************");  
                CompanyProfileInformation cpi = (CompanyProfileInformation) complayProfileInformation.newInstance();  
                // Invoking Methods through Reflections.  
                List<String> listMethodName = new ArrayList<>();  
                listMethodName.add("getName");  
                listMethodName.add("getAge");  
                listMethodName.add("getCompany");  
                for (String methodname : listMethodName) {  
                     switch (methodname) {  
                     case "getName":  
                          System.out.println("************************************************************************");  
                          Method getNamewithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getNamewithParameters.invoke(cpi);  
                          Method getNameWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname,  
                                    String.class);  
                          getNameWithoutParameters.invoke(cpi, "Bharani Ravi Kanth R");  
                          System.out.println("************************************************************************");  
                          break;  
                     case "getAge":  
                          System.out.println("************************************************************************");  
                          Method getagewithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getagewithParameters.invoke(cpi);  
                          Method getageWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname, int.class);  
                          getageWithoutParameters.invoke(cpi, 32);  
                          System.out.println("************************************************************************");  
                          break;  
                     case "getCompany":  
                          System.out.println("************************************************************************");  
                          Method getCompanywithParameters = complayProfileInformation.getDeclaredMethod(methodname);  
                          getCompanywithParameters.invoke(cpi);  
                          Method getCompanyWithoutParameters = complayProfileInformation.getDeclaredMethod(methodname,  
                                    String.class);  
                          getCompanyWithoutParameters.invoke(cpi, "BHARANIRAVIKANTHSOFT");  
                          System.out.println("************************************************************************");  
                          break;  
                     default:  
                          System.err.println("No Such Method available");  
                          break;  
                     }  
                }  
           } catch (ClassNotFoundException e) {  
                System.err.println(e.getMessage());  
           }  
      }  
 }  
output:
 getName  
 getName  
 getAge  
 getAge  
 getCompany  
 getCompany  
 wait  
 wait  
 wait  
 equals  
 toString  
 hashCode  
 getClass  
 notify  
 notifyAll  
 ************************************************************************  
 getName  
 getName  
 getAge  
 getAge  
 getCompany  
 getCompany  
 ************************************************************************  
 Calling Constructor  
 bharani  
 26  
 EIL
 ************************************************************************  
 bharani  
 Bharani Ravi Kanth R  
 ************************************************************************  
 ************************************************************************  
 26  
 32  
 ************************************************************************  
 ************************************************************************  
 EIL  
 BHARANIRAVIKANTHSOFT
 ************************************************************************  

Accessing the Private variables of a class. 

Lets create a simple class PrivateMembersClass.Java which has only private and public variables

 package com.learning.reflections;  
 public class PrivateMembersClass {  
      private String empName = "bharani Ravi Kanth";  
      private int empAge = 27;  
      private String empCompany = "EIL";  
      public String mobileNo = "+918778888278";  
      public String designation = "Solution Integrator";  
 }  
Create one more class FindingOutThePrivateAndPublicVariableOfaClass which we use to access the variables of PrivateMembersClass class through reflections.
 package com.learning.reflections;  
 import java.lang.reflect.Field;  
 public class FindingOutThePrivateAndPublicVariableOfaClass {  
      @SuppressWarnings("rawtypes")  
      public static void main(String[] args)  
                throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException {  
           Class privateOutThePrivatePublicVariables = Class.forName("com.learning.reflections.PrivateMembersClass");  
           // GetFields will provide only the public Variables  
           Field[] variablesinClass = privateOutThePrivatePublicVariables.getFields();  
           for (Field field : variablesinClass) {  
                System.out.println(field.getName());  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields will provide you private and public Variables  
           Field[] PrivateandPublicvariablesinClass = privateOutThePrivatePublicVariables.getDeclaredFields();  
           for (Field field : PrivateandPublicvariablesinClass) {  
                System.out.println(field.getName());  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields accessing the public variables from the class  
           PrivateMembersClass membersClass = (PrivateMembersClass) privateOutThePrivatePublicVariables.newInstance();  
           for (Field field : variablesinClass) {  
                System.out.println(field.getName());  
                System.out.println(field.get(membersClass));  
           }  
           System.out.println("**********************************");  
           // GetDeclaredFields accessing the public and private variables from the  
           // class  
           // you cannot access private variables directly, We need to set the value as true for the  
           // Field method setAccessible  
           for (Field field : PrivateandPublicvariablesinClass) {  
                System.out.println(field.getName());  
                field.setAccessible(true);  
                System.out.println(field.get(membersClass));  
           }  
      }  
 }  
Output:
 mobileNo  
 designation  
 **********************************  
 empName  
 empAge  
 empCompany  
 mobileNo  
 designation  
 **********************************  
 mobileNo  
 +918778888278  
 designation  
 Solution Integrator  
 **********************************  
 empName  
 bharani Ravi Kanth  
 empAge  
 27  
 empCompany  
 EIL
 mobileNo  
 +918778888278  
 designation  
 Solution Integrator