EJB 3.1 SessionBean Example with Remote Interface using WebLogic 12.1.1

EJB stands for Enterprise Java Bean. If you are not fimilar with EJB, Please read below in order to move ahead with "Creating EJB 3.1 Application using WebLogic 12.1.1".
  1. What is EJB and Why Comes into Picture
  2. EJB Container and it's Feature
EJB application requires to be run in Application Server like WebLogic, JBoss. As part of current EJB Demo, WebLogic Server 12.1.1 and  JDK 1.7 Update 03 is used.

Suppose, I want to write Stateless Session Bean(Can be local or remote), in My case Remote Component which will provide customer Information upon request from Client.

EJB 3.1 Remote Interface for Session Bean Example using Weblogic Server 12.1.1:

Create Remote Interface : CustomerServiceRemote.java
package com.anuj.business;

import javax.ejb.Remote;
import com.anuj.business.rep.Customer;

/**
 * 
 * @author Anuj
 * 
 */
@Remote
public interface CustomerServiceRemote {

	public Customer getCustomerInfo(String customerId);
}

Create Session bean implementation Class : CustomerService.java
package com.anuj.business;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;

import com.anuj.business.rep.Customer;

/**
 * @author Anuj
 * Session Bean implementation class CustomerService
 */
@Stateless(mappedName="customerServiceEJB")
public class CustomerService implements CustomerServiceRemote {

	private List customers = new ArrayList();
	
    /**
     * Default constructor. 
     */
    public CustomerService() {
    	createCustomers();
    }

	@Override
	public Customer getCustomerInfo(String customerId) {
		Customer customer = null;
		
		for(Customer cust : customers){
			if(cust.getCustomerId().equals(customerId)){
				customer = cust;
				break;
			}
		}
				
		if(customer != null){
			return customer;
		}
		else{
			return null;
		}	
	}

	protected void createCustomers(){
		Customer customer = new Customer();
		customer.setCustomerId("1");
		customer.setCustomerName("Anuj");
		customer.setAddress("India");
		customer.setPhone("1234567890");
		
		customers.add(customer);
	}
}

Deploy EJB to WebLogic Server :
Now, you have Session Bean available. Export EJB jar and Deploy it to WebLogic Server.

Create Client :
Creating Client which will access Remote EJB deployed on Server, includes following steps
    1. Create Java Project and add weblogic.jar,wlclient.jar to Build Path in eclipse

    2. Export CustomerServiceSessionBean as jar with only Remote Interface and other required classes. Don't include Implementation class since that's why EJB concept comes to picture. Ex. if you observe jar shows in picture, you will notice that Implementation class is not added here

    3.  Configure Properties for WebLogic
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    properties.put(Context.SECURITY_PRINCIPAL,"weblogic");
    properties.put(Context.SECURITY_CREDENTIALS,"weblogic1");
    properties.put(Context.PROVIDER_URL,"t3://localhost:7001");
    

    4. Initialize Context with Configured Properties which will be used for JNDI Lookup
    import javax.naming.InitialContext;
    Context context = new InitialContext(properties);
    

    5. Perform JNDI lookup using Context. customerServiceEJB used below is MappedName which we have defined in CustomerSessionBean EJb Earlier.
    context.lookup("customerServiceEJB#com.anuj.business.CustomerServiceRemote");

    6. Access Remote Interface method
    Customer customer = customerService.getCustomerInfo("1");
    System.out.println("Customer Id : "+customer.getCustomerId());
    System.out.println("Customer Name : "+customer.getCustomerName());
    System.out.println("Address : " + customer.getAddress());
    System.out.println("Phone : " + customer.getPhone());
    

    Complete EJB 3.1 SessionBean example with Remote Interface using WebLogic Server 12c

    import java.util.Properties;
    
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    
    import com.anuj.business.CustomerServiceRemote;
    import com.anuj.business.rep.Customer;
    
    /**
     * 
     * @author Anuj
     *
     */
    public class CustomerServiceEJBClient {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		Properties properties = new Properties();
    		properties.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    		properties.put(Context.SECURITY_PRINCIPAL,"weblogic");
    		properties.put(Context.SECURITY_CREDENTIALS,"weblogic1");
    		properties.put(Context.PROVIDER_URL,"t3://localhost:7001");
    		
    		try {
    			Context context = new InitialContext(properties);
    			
    			CustomerServiceRemote customerService =   (CustomerServiceRemote)context.lookup("customerServiceEJB#com.anuj.business.CustomerServiceRemote");
    			
    			Customer customer = customerService.getCustomerInfo("1");
    			System.out.println("Customer Id : "+customer.getCustomerId());
    			System.out.println("Customer Name : "+customer.getCustomerName());
    			System.out.println("Address : " + customer.getAddress());
    			System.out.println("Phone : " + customer.getPhone());
    			
    		} catch (NamingException e) {
    			e.printStackTrace();
    		}
    		
    		
    	}
    
    }
    

    Output :

    Customer Id : 1
    Customer Name : Anuj
    Address : India
    Phone : 1234567890
    

    After a lots of efforts I finally made my EJB Example up and Running. Hope this tutorial helps you for understanding EJB.

    if My Tutorials helped you in any case then Like it or provide your feedback. You know, What? providing feedback or comments or like makes blogger happy:)

    How to write JAX-WS WebServices and WebService Client in Java

    Today, I am going to explain about how to write JAX-WS Webservice providers(Endpoints) and how to create webservice client which uses published webservices.

    JAX-WS is Java Api for XML webservices. APIs for creating webservices in XML formats.

    Let's consider that I want to write JAX-WS Service which will publish customer Information and client will use this service and display requested customer Information.

    You require to develop following parts :
    1. Create WebService Endpoint Interfaces
    2. Create WebService Endpoint Implementation
    3. Endpoint Publisher
    4. Analyze Created wsdl file
    5. Create WebService Client which will use exposed services.

    CustomerService.java - CustomerService Interface
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    import javax.jws.soap.SOAPBinding.Style;
    import com.anuj.rep.Customer;
    
    /**
     * 
     * @author Anuj
     *
     */
    @WebService
    @SOAPBinding(style=Style.RPC)
    public interface CustomerService {
    
     @WebMethod public Customer getCustomerInfo(String customerId);
    }
    

    CustomerServiceImpl.java - Implementation Logic for CustomerService Interface
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    import com.anuj.endpoints.interfaces.CustomerService;
    import com.anuj.rep.Customer;
    
    /**
     * 
     * @author Anuj
     *
     */
    @WebService(endpointInterface="com.anuj.endpoints.interfaces.CustomerService")
    public class CustomerServiceImpl implements CustomerService {
    
     private List customers = new ArrayList();
     
     public CustomerServiceImpl(){
      createCustomers();
     }
     
     @Override
     @WebMethod
     public Customer getCustomerInfo(String customerId) {
      Customer customer = null;
      
      for(Customer cust : customers){
       if(cust.getCustomerId().equals(customerId)){
        customer = cust;
        break;
       }
      }
        
      if(customer != null){
       return customer;
      }
      else{
       return null;
      }  
     }
    
     protected void createCustomers(){
      Customer customer = new Customer();
      customer.setCustomerId("1");
      customer.setCustomerName("Anuj");
      customer.setAddress("India");
      customer.setPhone("1234567890");
      
      customers.add(customer);
     }
    }
    

    CustomerServicePublisher.java - Publish CustomerService
    import javax.xml.ws.Endpoint;
    import com.anuj.endpoints.implementation.CustomerServiceImpl;
    
    /**
     * 
     * @author Anuj
     *
     */
    public class CustomerServicePublisher {
    
     private static String address = "http://localhost:8080/webservices/customers";
     
     /**
      * @param args
      */
     public static void main(String[] args) {
      Endpoint.publish(address,new CustomerServiceImpl());
      System.out.println("Services deployed at "+ address);
     }
    

    Analyze Created WSDL File
    Once WebService is publised, You can access WSDL(Web Service Description Language) using Url  http://localhost:8080/webservices/customers?wsdl

    WSDL File will look like as below.(Below is XML View)
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Create WebService Client
    wsimport command is used to parse wsdl file and generate requires files for accessing published JAX-WS Service.

    wsimport -keep http://localhost:8080/webservices/customers?wsdl

    Once all required files has been generated, you can access exposed services as below :

    import com.anuj.endpoints.implementation.CustomerService;
    import com.anuj.endpoints.implementation.CustomerServiceImplService;
    import com.anuj.endpoints.interfaces.Customer;
    
    /**
     * 
     * @author Anuj
     *
     */
    public class JAXRSClient {
    
     /**
      * @param args
      */
     public static void main(String[] args) {
      
      CustomerServiceImplService customerServiceImpl = new CustomerServiceImplService();
      CustomerService customerService = customerServiceImpl.getPort(CustomerService.class);
      
      Customer customer = customerService.getCustomerInfo("1");
      System.out.println("Customer Id : " + customer.getCustomerId());
      System.out.println("Customer Name : " + customer.getCustomerName());
      System.out.println("Customer Address : " + customer.getAddress());
      System.out.println("Customer Phone : "+ customer.getPhone());  
     }
    }
    

    Output :
    Customer Id : 1
    Customer Name : Anuj
    Customer Address : India
    Customer Phone : 1234567890 

    Hope you liked this tutorial of Creating JAW-WS WebServices Endpoints and WebService Clients.

    if My Tutorials helped you in any case then Like it or provide your feedback. You know, What? providing feedback or comments or like makes blogger happy:)

    Generate BeanName using Spring AnnotationBeanNameGenerator

    Developing application with Spring, sometimes require to retrieve bean name which you have either specified in @Bean annotation or bean id which is internally generated by Spring.

    Spring by Default generate Bean id same as Bean class name but with first letter in small caps.
    Using Spring AnnotationBeanNameGenerator class, one can achieve this using generateBeanName method.

    Ex. private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
    String beanName = this.beanNameGenerator.generateBeanName(definition, registry); 

    Here,
    (1) definition is Spring BeanDefinition. BeanDefinition describes bean instance which has property values, constructor argument values any many more.

    In order to retrieve BeanDefinition for bean, method resolveScopeMetadata(BeanDefinition definition) of Spring interface like ScopeMetadatResolver or AnnotationScopeMetadataResolver can be used.


    Spring provide interface called AnnotatedBeanDefinition which provide awesome bean information like getMetadata() for those beans which has annotation defined.

    (2) registry is of Spring BeanDefinitionRegistry.(Ex. BeanDefinitionRegistry registry)  it's basically interface for registries which holds bean Definition. It's only interface which encapsulate registries of bean Definition

    After struggling hours , I finally able to make things working. Hope you find this information useful

    Prefix mvc for element mvc:annotation-driven is not bound

    If you are planning to use <mvc:annotation-driven>  into your Spring MVC application, chances that you may be facing issue for "Prefix mvc for element mvc:annotation-driven is notbound " erorr. Root cause is that your bean definition XML doesn't have names-spaces mentioned below.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


        <context:component-scan base-package="com.anuj.spring.controller" />
        <mvc:annotation-driven />

    Benefits of mvc-annotation-driven :
    • enable MVC java Config. To do same in Code instead of beans xml, you can add the annotation @EnableWebMvc to one of your @Configuration
    • enable support for formatting using @NumberFormat and @DateTimeFormat
    • enable support for validation using @Valid if JSR-303 provider present on classpath
    • HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values from @RequestMapping or @ExceptionHandler methods. Also enable support for atom,rss,json,jaxb,String,resource,form,source convertors.
    • many more..

    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

    While developing SpringMVC application in Eclipse, All require dependencies has been added to maven dependencies in pom.xml. Yet running application encountered with Exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

    Solution : 
    Even though you have added all required dependencies into pom.xml for your J2EE WebProject you are require to reference maven dependencies to "Web Deployment Assembly"

    Right Click J2EE Web Project->Deployment Assembly->Add->Select Maven Dependencies.




    GuideLines and Troubleshootings :
    In Order to run your project with Maven, It should be created with proper J2EE WebProject with Maven Guidelines as mentioned below.

    1. Use Maven CommandLine Argument for WebProject :
    mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
    and Convert project to eclipse using mvn eclipse:eclipse

    2. If you have installed M2E in Eclipse then create Maven Project and choose archetypeArtifactId as "maven-archetype-webapp". (if you don't prefer Maven command Line approch)

    3. Once you have maven project, you will not be able to see Deployment Assembly in Project Properties. You need to add "Dynamic Web Module" from Project Facets in Project properties.
    Here, You will be able to add "Maven Dependencies" references as mentioned above.

    4. Since maven will only create src/main/webapp,src/main/resources folder. you are suppose to create java folder manually in src/main.

    5. Project should contains web.xml in src/main/webapp/WEB-INF/

    6. Folder src/main/webapp/ or src/main/webapp/WEB-INF can contains file like jsp,html,xml etc

    7. In Run as->Maven Build, you can provide configurations like clean,install.

    8. If you are facing issues like error: package javax.servlet.http does not exist", please add following dependencies to your pom.xml

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
    </dependency>

    9. If you are facing issue as [ERROR] Unable to locate the Javac Compiler in: [ERROR] C:\Program Files (x86)\Java\jre7\..\lib\tools.jar, Please follow(in Eclipse):
    Window->Preferences->installed JRE->select path of JRE from JDK folder and not ourside JRE folder

    10. Once Maven Build is successful, You are ready to run your application.
    But If you are running application from Eclipse, In "Deploy Web Assembly" remove WebContent/ and add path for src/main/webapp since it's place where web.xml available.

    I spent almost 3 hours to get my project working and finally "SpringMVC J2EE WebApplication with Maven Support working in WebLogic Server". All information shared above are valuable information and Unique.


    Hope it might help you.

    java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

    I was working on developing Spring MVC Application with Maven+Tomcat with Spring 3.2. While running application, encountered with Exception : java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

    Solution :
    I found that tomcat container doesn't contain jatl library and hence require to explicitly add it to maven dependencies in Pom.xml

    Maven Dependencies
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    After adding maven dependencies as mentioned above, issue is resolved. Hope it might help you.

    Note : apache-tomcat-7.0.27  was used

    Unable to view Convert to Maven in Eclipse Juno IDE for J2EE

    While I was working on issue of converting my Java Project to Maven, I found that there is no options like configure-> "convert to Maven Project" on my current working project which is being discussed in existing forums.

    Solution :
    You need to add M2E(Maven Integration for Eclipse Plugin) to Eclipse Juno J2EE IDE from location http://download.eclipse.org/technology/m2e/releases

    Please refer to Eclipse IDE and Packages for comparison which Eclipse IDE supports which default packages.

    Hope You find this information useful :)

    Apache Solr and SolrJ Maven Dependancies

    While I was developing Solr application using Solrj, there was confusion (which is always :) ) of which maven dependencies to be included in Pom.xml. Hence thought to share here.
    Please don't miss to add M2_REPO classpath variable pointing to repository directory so you can easily import required library into your Java Project.

    Maven Dependencies for Developing application with Solr (version 4.1) are followed as :

    1. Solrj Dependencies
    <dependency>
               <artifactId>solr-solrj</artifactId>
               <groupId>org.apache.solr</groupId>
               <version>4.1.0</version>
               <type>jar</type>
        </dependency>

    2. Solr-core Dependencies
    <dependency>
               <artifactId>solr-core</artifactId>
               <groupId>org.apache.solr</groupId>
               <version>4.1.0</version>
               <type>jar</type>
        </dependency>
        <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>servlet-api</artifactId>
               <version>2.5</version>
        </dependency>

    Servlet-api required because EmbeddedSolrServer is dependent on servlet-api. Please include in Maven if you are planning to add into your project

    3. Sl4j Dependencies
    <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.2</version>
        </dependency>

    4. HttpClient Dependencies
    <!-- httpClient dependencies -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.2.1</version>
        </dependency>

    5. JUnit Dependencies
    <!-- Junit Depedencies -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>

    Maven Compiler Plugins for POM.xml are :
    <build>
          <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
          </plugins>
        </build>

    Once You added all required dependencies and plugins to pom.xml it's time to Compile project

    1.Convert your project to eclipse project with mvn eclipse:eclipse
    2.Compile your Project with mvn compile
    3.Clean your Project with mvn eclipse:clean or mvn clean
     

    Spring org.springframework.beans.BeanInstantiationException - Solved

    I was working on JAX-RS and encountered with BeanInstantiationException.

    Exception :
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.anuj.services.CountryServiceImpl]: Constructor threw exception; nested exception is com.anuj.common.errors.InternalServerException: Internal Server Error Occured
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:983)
        ... 41 more
    Caused by: com.anuj.common.errors.InternalServerException: Internal Server Error Occured
        at com.anuj.services.CountryServiceImpl.initialize(CountryServiceImpl.java:160)
        at com.anuj.services.CountryServiceImpl.(CountryServiceImpl.java:44)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
        ... 43 more


    After looking at Exception I found that Constructor of Impl(Resource) class was Throwing null exception and hence Spring was unable to initialize bean. nested exception was java.lang.NullPointerException. After solving that issue, Got expected JAX-RS Response.



    Java i18n Internationalization Example

    Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

    Sometimes I was wondering term internationalization is abbreviated as i18n, Why? and Found reason is   there are 18 letters between the first "i" and the last "n." :)

    Why to use i18n and Benifits of i18n :
    1. Support for new languages does not require recompilation as stored in Properties Files.
    2. Can be localized quicklyby setting Local as per Language and country
    3. Instead of hard coding Textual elemtns(GUI labels,status message,Error message. they are stored outside and retrieved dynamically.
    4. By small additional of data(properties file of different landuage) , same code can be run WorldWide.
    5. Culturally dependent data, like dates and currencies, appear in formats that line up with user's region and language
    Steps to create i18n Example : 

    1. Create Properties Files and define key-value pair for "text" : "value in Specific Language"
        Ex. MessagesBundle_de_DE.properties
              MessagesBundle_en_US.properties
              MessagesBundle_fr_FR.properties

             MessagesBundle_de_DE.properties looks like as 
             greetings = Hallo.
             farewell = Tschüß.
             inquiry = Wie geht's?

    2. Define Locale
        Ex. Locale currentLocale= new Locale("en", "US");
     
    3. Create Resource Bundle
    ResourceBundle messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);

    4. Retrieve Text from Resource Bundle
    Ex. messages.getString("greetings")


    Java i18n Internalization Program : 

    package com.anuj.utils;
    
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    /**
     *
     * @author Anuj Patel
     */
    public class i18nExample {
    
        public static void main(String[] args) {
            Locale currentLocale;
            ResourceBundle messages;
            String language = "de"; //en,de,fr
            String country = "DE"; //US,DE,FR
    
            currentLocale = new Locale(language, country);
    
            messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
    
            System.out.println(messages.getString("greetings"));
            System.out.println(messages.getString("inquiry"));
            System.out.println(messages.getString("farewell"));
        }
    }
    Output :
    Hallo.
    Wie geht's?
    Tschüß.