Showing posts with label j2EE. Show all posts
Showing posts with label j2EE. Show all posts

Monday, May 13, 2013

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

Links to this post
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.

Sunday, April 21, 2013

Generate BeanName using Spring AnnotationBeanNameGenerator

Links to this post
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

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

Saturday, March 30, 2013

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

Links to this post
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">

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

Links to this post
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.

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

Links to this post
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.

Monday, February 18, 2013

Apache Solr and SolrJ Maven Dependancies

Links to this post
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>

Sunday, January 20, 2013

Spring org.springframework.beans.BeanInstantiationException - Solved

Links to this post
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


Wednesday, October 03, 2012

Sending Email using Spring MailSender and Gmail SMTP Server

Links to this post
Spring provides interface called "MailSender" (org.springframework.mail.MailSender) to send mail.
Developer can use MailSender method send(SimpleMailMessage simpleMessage)and pass SimpleMailMessage with From,To,Subject, and Text set.

MailSender Documentation : MailSender
SimpleMailMessage Documentation : SimpleMailMessage


Java Program to send Mail using Spring MailSender :
package com.anuj.spring.mail;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 *
 * @author Anuj Patel
 */
public class NotifyImpl {
    
    private MailSender mailsender;
    
    public MailSender getMailsender() {
        return mailsender;
    }
    
    public void setMailsender(MailSender mailsender) {
        this.mailsender = mailsender;
    }
    
    public void sendMail(String from, String to, String subject, String message) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(message);
        
        mailsender.send(simpleMailMessage);
    }
} 

Tuesday, September 25, 2012

Spring - java.lang.ClassNotFoundException: org.aopalliance.aop.Advice

Links to this post
Even after adding all Spring 3.1 jar i was getting excpetion as below :

Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException:
Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 49 more
   
Solution :

As part of https://jira.springsource.org/browse/SPR-2011, Removed AOP Alliance interfaces from spring-aop.jar and
the aopalliance.jar needs to be added explicitly. Instead of using jar from any other sources, it's better to use jar from official maven repository.

Saturday, July 28, 2012

How to load multiple Spring bean configuration file

Links to this post
When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex. Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

You may load multiple Spring bean configuration files in code :
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",
              "Spring-Common.xml"});

This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML into ClassPathXmlApplicationContext
Ex. 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">    
       <import resource="common/Spring-Core.xml"/>  
      <import resource="connection/Spring-Common.xml"/> 
</beans>

Sunday, June 10, 2012

Deep Dive into Spring Setter Injection

Links to this post
Spring setter injection provide you to set value of different types of Data which you use while developing application. If you are not aware of Constructor or Setter Injection concept, please refer Spring Setter Injection and Constructor Injection before going through tutorial.

I will show you how to use it Spring setter Injection for different types of data.somehow due to formatting String is displayed as string.please use String in your example.

1. Create PropertyTest.java
package com.anuj.spring.core.injection;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 *
 * @author Anuj J Patel
 */
public class PropertyTest {
    
    private int intData;
    private double doubleData;
    private float floatData;
    private String stringData;
    private int[] intArr;
    private String[] stringArr;
    private List listdata;
    private Map map;
    private Properties properties;
    private Set setData;

    public PropertyTest() {
        System.out.println("Constructor Called");
    }
    
    @Override
    public String toString() {
        return "PropertyTest{" + "intData=" + intData + ", doubleData=" + doubleData + ", floatData=" + floatData + ", stringData=" + stringData + ", intArr=" + intArr + ", stringArr=" + stringArr + ", listdata=" + listdata + ", map=" + map + ", properties=" + properties + ", setData=" + setData + '}';
    }
    
    public double getDoubleData() {
        return doubleData;
    }

    public void setDoubleData(double doubleData) {
        this.doubleData = doubleData;
    }

    public float getFloatData() {
        return floatData;
    }

    public void setFloatData(float floatData) {
        this.floatData = floatData;
    }

    public int[] getIntArr() {
        return intArr;
    }

    public void setIntArr(int[] intArr) {
        this.intArr = intArr;
    }

    public int getIntData() {
        return intData;
    }

    public void setIntData(int intData) {
        this.intData = intData;
    }

    public List getListdata() {
        return listdata;
    }

    public void setListdata(List listdata) {
        this.listdata = listdata;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Set getSetData() {
        return setData;
    }

    public void setSetData(Set setData) {
        this.setData = setData;
    }

    public String[] getStringArr() {
        return stringArr;
    }

    public void setStringArr(String[] stringArr) {
        this.stringArr = stringArr;
    }

    public String getStringData() {
        return stringData;
    }

    public void setStringData(String stringData) {
        this.stringData = stringData;
    }
}

Saturday, May 26, 2012

Spring JdbcTemplate and Spring SimpleJdbcTemplate difference with Example

Links to this post
To use the SimpleJdbcTemplate you need to use JDK 1.5 or higher. SimpleJdbcTemplate takes advantage of the Java 5 language features like varargs, autoboxing, generics and covariant returns.

Following example shows you how to use SimpleJdbcTemplate and advantage of it over JdbcTemplate
package com.anuj.spring.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

/**
 *
 * @author Anuj J Patel
 */
public class ForumDAOSimpleJDBCImpl implements ForumDAO{

    /**
     * Simple JDBCTemplate
     * 1.When using SimpleJDBCTemplate there is no need to typecast from int to Integer
     * and you can pass variable length arguments instead of Object array
     * 2.There is no need to typecast return object, parameterizedRowMapper object's type parameter 
     * will be taken by default
     */
    private SimpleJdbcTemplate simpleJDBCTemplate;
    
    public void setDataSource(DataSource dataSource){
        this.simpleJDBCTemplate = new SimpleJdbcTemplate(dataSource);
    }
    
    @Override
    public void insert(Forum forum) {
        String query = "insert into tbforum(forumId,forumName,forumDesc) values(?,?,?)";
        simpleJDBCTemplate.update(query, forum.getForumId(),forum.getForumName(),forum.getForumDesc());
        System.out.println("Record Inserted successfully");
    }

    @Override
    public Forum selectForum(int forumId) {
        String query="select * from tbforum where forumId=?";
        
        return simpleJDBCTemplate.queryForObject(query, 
                new ParameterizedRowMapper(){
                        @Override
                        public Forum mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return new Forum(rs.getInt("forumId"),rs.getString("forumName"), rs.getString("forumDesc"));
                        };               
                },forumId);        
    }
    
}

Friday, April 27, 2012

JAX-RS Handling XML using JAXB Annotation

Links to this post
In this tutorial, I will show you how to create an “user” object, convert it into XML file,
and return it back to the client.

Create an object, annotate with JAXB annotation to support XML file conversion.

POJO Class with JAXB annotation :
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {

String username;
String password;
int pin;

@XmlElement
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

@XmlElement
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@XmlAttribute
public int getPin() {
return pin;
}

public void setPin(int pin) {
this.pin = pin;
}

}

File Download in JAX-RS

Links to this post
In JAX-RS, for user to download a file, annotate the method with @Produces("text/plain") :

Put @Produces(“text/plain”) on service method, with a Response return type. It means the output is a text file.
Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download.

Download File in JAX-RS :

See a full example to download a text file in JAX-RS.

import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/file")
public class FileService {

private static final String FILE_PATH = "c:\\file.log";

@GET
@Path("/get")
@Produces("text/plain")
public Response getFile() {
File file = new File(FILE_PATH);

ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"file_from_server.log\"");
return response.build();
}
}

@HeaderParam Implementation in JAX-RS

Links to this post
There are 2 ways to get HTTP request header in JAX-RS :
Inject directly with @HeaderParam
Pragmatically via @Context

Implementation using @HeaderParam :

In this example, it gets the browser “user-agent” from request header.

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/users")
public class UserService {

@GET
@Path("/get")
public Response addUser(@HeaderParam("user-agent") String userAgent) {
  return Response.status(200)
.entity("addUser is called, userAgent : " + userAgent)
.build();
}
}

Access via URI pattern “/users/get“, with FireFox, see following result :
addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0

@MatrixParam Implementation in JAX-RS

Links to this post
In this tutorial , i will show usage of @MatrixParam. Matrix parameters are a set of “name=value” in URI path, for example, /books/2012;author=anuj
In above URI, the matrix parameter is “author=anuj“, separate by a semi colon “;“.


@MatrixParam example
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/books")
public class BookService {

 @GET
 @Path("{year}")
 public Response getBooks(@PathParam("year") String year,
   @MatrixParam("author") String author,
   @MatrixParam("country") String country) {

  return Response
   .status(200)
   .entity("getBooks is called, year : " + year
    + ", author : " + author + ", country : " + country)
   .build();

 }
}

Saturday, January 14, 2012

Spring Setter Injection and Constructor Injection

Links to this post
In this post i am going to demonstrate you how to set bean property using spring setter injection and constructor. First i will demonstrate Happy scenario and later will be complex. This will force you to think deeply about bean.xml

Consider i have class User containing 3 property name,age and country. Using spring i want to display value of user with all it's property.

User.java
package com.anuj.spring.injection;
/**
 *
 * @author Anuj J Patel
 *
 */
public class User {

    private String name;
    private int age;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String toString()
    {
        String output = "Name : " + name + " Age: " + age + " Country:" + country;
        return output;
    }
}


Sunday, December 18, 2011

Spring IOC and Dependancy Injection

Links to this post
In Spring, Inversion of Control(IOC) is implemented using Dependancy Injection(DI) Design Pattern. Let's understand DI with java example and then I will see how DI can solve tightly coupled problem and Spring container will inject dependency.

What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.

If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.

Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.

There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection

1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.

2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
-  here, handling over dependencies takes after the dependent object is instantiated

Monday, December 12, 2011

What is Spring and why came into Picture ?

Links to this post
In order to start with Spring, it's very important to clear concepts about what is Spring and why it came into picture. Once you have idea about Spring picture, you will be sure able to easily understand 7 Spring modules described here as well. So Let's Jump into Spring :)

Java Enterprise Edition (JEE) component that was used to implement business logic was Enterprise Java Beans (EJB). However, EJBs are heavy weight components that require application servers to run. 

This was the scenario before the Spring Framework came into the picture. The Spring Framework provides a lightweight container to run the objects implementing business logic. In other words, Spring Framework-based business objects do not require an application server to run.

Spring Framework: What is it? Spring Framework is “An open-source layered Java/J2EE application framework having a light-weight container implementing Inversion-of-Control and Aspect Oriented Programming.” The key points here are “layered application framework” and “Inversion of Control and Aspect Oriented Programming.” and they are divided into two broad categories:
  1. Patterns
  2. Components of the Framework

Spring has two patterns at its core. They are:
    • Inversion-of-Control(IOC)
    • Aspect Oriented Programming(AOP)

Inversion-of-Control - refer to Spring DI and IOC concept and Example

Aspect Oriented Programming(AOP) is “An approach to programming that attempts the separation of concerns, specifically cross-cutting concerns, as an advance in modularization.” Here, the key point is separation of concerns. 

Separation of concerns means that the applications are divided into modules that do not overlap in terms of functionality.Logging is an example of such a concern.by using AOP a developer can encapsulate cross cutting concerns.

Thursday, September 29, 2011

Using Spring JdbcTemplate to store and retrive values into DB

Links to this post
In This example i will demonstrate you Spring example to insert and select values from oracle DB. The insertForum() method below shows the amount of code you need to write to insert data using JDBC.

1. Create Java POJO Class ex. Forum which contains getter and setter method for field as mentioned below.
    private int forumId;
    private String forumName;
    private String forumDesc;


1.1 create parameterized constructor as below.
  public Forum(int forumId, String forumName, String forumDesc) {
        this.forumId = forumId;
        this.forumName = forumName;
        this.forumDesc = forumDesc;
    }
 

2. Create Interface ex. ForumDAO which contains insert and select methods
package com.learning.dao;
import com.learning.core.Forum;
public interface ForumDAO {

    public void insertForum(Forum forum);
    public Forum selectForum(int forumId);
}