Thursday, December 7, 2017

JSF (2.X+) + Spring 4 (3.X+) Integration

Here we discover the simplest solution for JSF and Spring integration. All required details configurations with full source are available in here. We use very simple configuration. Environment details are listed below:

Environment:

1. Maven Project: maven-archetype-webapp

2. JSF 2.2 and Spring 4 [All details are in pom.xml]

3. Dynamic Web Module: 3.0

4. JSF configuration just in web.xml [see in the repository]

5. All Spring related configurations are done in class WebAppInitializer.java. And bean  is configured on SpringConfig.java which also configures the component-scan package. 

package com.component.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer  implements WebApplicationInitializer{

@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(SpringConfig.class);  
        ctx.setServletContext(servletContext);    
        servletContext.addListener(new ContextLoaderListener(ctx));
        servletContext.addListener(new RequestContextListener());
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
        dynamic.addMapping("/");  
        dynamic.setLoadOnStartup(1);
}

}


package com.component.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.component.dao.UserManagementDao;
import com.component.dao.UserManagementDaoImpl;
import com.service.StudentService;
import com.service.StudentServiceImpl;

@Configuration
@ComponentScan("com.component")
public class SpringConfig {
@Bean
public StudentService studentService() {
return new StudentServiceImpl();
}
}

Bean classes are very simple POJO.

package com.service;

public interface StudentService {
String getStudent(Integer id);
}

package com.service;

import java.util.HashMap;
import java.util.Map;

public class StudentServiceImpl implements StudentService {

Map<Integer, String> map = new HashMap<Integer, String>();
{
map.put(1, "Ashik");
map.put(2, "Ibraim Khan");
map.put(3, "Muhammad Ashik Ali Khan");
}
@Override
public String getStudent(Integer id) {
return map.get(id);
}
}


6. For Spring Addition Just add the following entry in faces-config.xml. 

<application>
   <el-resolver>
        org.springframework.web.jsf.el.SpringBeanFacesELResolver
   </el-resolver>

</application>

7. JSF managed beans are under component-scan package [com.component].

8. All JSF pages [*.xhtml] loads text (both regular and parameterized) from messages.properties created under package com.jsf.properties in resources [src/main/resource] folder.


header=Welcome to JSF framework integration with Spring framework

greeting_text=Welcome to JSF Framework
project_type=JSF integration with Spring
greeting_custom=Welcome to {0} for our framework
index_command=Type Name and Click
std_id=Enter Student Id:
std_name=Student Name: {0}
usr_id=Enter User Id:
usr_name=User Name: {0}

9. Java: SE 7

10. Application Server: JBOSS EAP 6.3

11. Eclipse Luna (4.4.0) or above.


Project File Structure:



















Now, we create a very simple JSF page (student.xhtml) under webapp folder.

Here,

student.xhtml --> Input : ID [Integer] --> Managed Bean: StudentBean.java

result.xhtml--> Output: Name [String] --> Managed Bean: StudentBean.java

So, StudentBean.java [JSF managed bean] is very important. It is under hierarchy of component-scan package [com.component]. It links the bean StudentService by @Autowired annotation and declare it as a component i.e. @Component of spring framework.

1. It [StudentBean.java] takes the value of ID from JSF [student.xhtml],

2. passes the value to spring bean [StudentService] to retrieve the student name.

3. sets the value to bean property i.e. name. And continues the page to another with that value.

Now take a look of StudentBean.java.

package com.component.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.service.StudentService;

@ManagedBean(name="studentBean")
@RequestScoped
@Component
public class StudentBean {
@Autowired
public StudentService studentService;
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String showResult(){
name = studentService.getStudent(id);
return "result";
}
}

Moreover, Two JSF pages (student.xhtml & result.xhtml) are shown below.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html  xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:c="http://java.sun.com/jsf/composite"
    xmlns:fac="http://java.sun.com/jsf/facelets">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>JSF 2 + Spring 4 Integration</title>
<f:loadBundle var="mymsg" basename="com.jsf.properties.messages"/>
</head>
<body>
<h:form>
<h:outputText value="#{mymsg.std_id}"/>
<h:inputText value="#{studentBean.id}"/>
<h:commandButton value="Show Name" action="#{studentBean.showResult}"/>
</h:form>
</body>
</html>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html  xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:c="http://java.sun.com/jsf/composite"
    xmlns:fac="http://java.sun.com/jsf/facelets">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>JSF 2 + Spring 4 Integration</title>
<f:loadBundle var="mymsg" basename="com.jsf.properties.messages"/>
</head>
<body>
<h3>
<h:outputFormat value="#{mymsg.std_name}">
<f:param value="#{studentBean.name}"/>
</h:outputFormat> 
</h3>
</body>
</html>

 Sample Input:







Sample Output:






N.B.: This is not research but only discover of framework. Feel free to contact if any problem occurs to test this example.

Monday, September 25, 2017

Spring MVC – @RequestMapping

Let's start with a simple example - mapping HTTP request to method using some basic criteria.

1. @RequestMapping – by Path 


@RequestMapping(value = "/ex/greetings", method = RequestMethod.GET)
    @ResponseBody
    public String getGreetingsBySimplePath() {
        return "Get Greetings";
    }

 To test out this mapping with a simple curl command, run:


curl -i http://localhost:7001/springapp/ex/greetings

2. @RequestMapping – the HTTP Method

 

Previous example was based on HTTP GET method. Now mapped to HTTP POST method.


@RequestMapping(value = "/ex/greetings", method = RequestMethod.POST)
    @ResponseBody
    public String postGreetings() {
        return "Post Greetings";
    }

To test the POST via a curl command:


curl  -i  -X  POST  http://localhost:7001/springapp/ex/greetings

3. @RequestMapping and HTTP Headers


The mapping can be narrowed even further by specifying a header for the request:

@RequestMapping(value = "/ex/greetings", headers = "key=val", method = RequestMethod.GET)
    @ResponseBody
    public String getGreetingsWithHeader() {
        return "Get Greetings with some header";
    }

To test this via a curl command:


curl -i -H "key:val" "http://localhost:7001/springapp/ex/greetings"

For multiple headers via the header attribute of @RequestMapping:

@RequestMapping(value = "/ex/greetings", headers = { "key1=val1",
            "key2=val2" }, method = RequestMethod.GET)
    @ResponseBody
    public String getGreetingsWithMultipleHeader() {
        return "Get Greetings with multiple header";
    }

To test this via a curl command:


curl -i -H "key1:val1" -H "key2:val2" "http://localhost:7001/springapp/ex/greetings"

4. @RequestMapping Consumes and Produces


@RequestMapping annotation now has the produces and the consumes attributes, specifically for request based on Accept header.

@RequestMapping(value = "/ex/greetings", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getGreetingsAsJsonFromREST() {
        return "Get Greetings with header from REST";
    }

To test this via a curl command:


curl -i -H "Accept:application/json"  "http://localhost:7001/springapp/ex/greetings"

5. @RequestMapping with Path Variables


Parts of the mapping URI can be bound to variables via the @PathVariable annotation. A simple example with a single path variable:


@RequestMapping(value = "/ex/greetings/{greetingsId}/locations/{locationId}", method = RequestMethod.GET)
    @ResponseBody
    public String getGreetingsBySimplePathVariable(
            @PathVariable String greetingsId, @PathVariable String locationId) {
        return "Get Greetings with id=" + greetingsId + " and location="+locationId;
    }

To test this via a curl command:


curl "http://localhost:7001/springapp/ex/greetings/1/locations/Motijheel"

6. @RequestMapping with Request Parameters


We are now mapping a request to a URI such as:  http://localhost:7001/springapp/ex/location?id=w

@RequestMapping(value = "/ex/location", method = RequestMethod.GET)
    @ResponseBody
    public String getLocationBySimplePathWithRequestParam(
            @RequestParam("id") String id) {
        return "Get specific location with id = " + id;
    }

For more advanced scenarios, @RequestMapping can optionally define the parameters – as yet another way of narrowing the request mapping:

@RequestMapping(value = "/ex/location", params = "id", method = RequestMethod.GET)
    @ResponseBody
    public String getLocationBySimplePathWithExplicitRequestParam(
            @RequestParam("id") String id) {
        return "Get specific location params with id = " + id;
    }

Even more flexible mappings are allowed – multiple params values can be set to another URL, and not all of them have to be used:

@RequestMapping(value = "/ex/location", params = { "id", "name" }, method = RequestMethod.POST)
    @ResponseBody
    public String getLocationBySimplePathWithExplicitMultipleRequestParam(
            @RequestParam("id") String id) {
        return "Get specific location with multiple params with id = " + id;
    }

To test this via a curl command:


curl  "http://localhost:7001/springapp/ex/location?id=w&name=DHAKA

7. @RequestMapping – a fallback for all requests

 

For all requests:

@RequestMapping(value = "*", method = { RequestMethod.GET,
            RequestMethod.POST })
    @ResponseBody
    public String fallbackMessage() {
        return "Fallback Request";
    }

8. @RequestMapping – multiple paths mapped to the same controller method

 

Multiple requests using different HTTP verbs can be mapped to the same controller method:

@RequestMapping(value = { "/m0", "/m1", "/m2" })
    @ResponseBody
    public String method0() {
        System.out.println(messages.get("method0"));
        return "method0";
    }



Thursday, September 21, 2017

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

Adding the option insides Eclipse immediately resolves the issue. To add the option
  1. open preferences via application menu Window => Preferences (or on OSX Eclipse => Settings).
  2. Navigate to Team => Git => Configuration
  3. click Add entry..., then put http.sslVerify in the key box and false in the value box.
Seems to be a valid solution for Eclipse 4.4 (Luna), 4.5.x (Mars) and 4.6.x (Neon) on different Operating systems.

Sunday, July 16, 2017

Spring MVC: Inject Properties file into java.util.Map

You can inject .properties as a map in your class using @Resource annotation.

If you are working with XML based configuration, then add below bean in your spring configuration file:
  
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

For, Annotation based:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

Then you can pick them up in your application as a Map:
 
@Resource(name = "myProperties")
private Map<String, String> myProperties;


 Full Code:

1. Configuration for the Map.


package com.controller.utility;


import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class MessageUtil {

    @Bean(name = "messages")
    public static PropertiesFactoryBean mapper() {
            PropertiesFactoryBean bean = new PropertiesFactoryBean();
            bean.setLocation(new ClassPathResource(
                    "message.properties"));
            return bean;
    }
}


2. Use Map in Controller to access the value by using URL.


package com.controller.test;

import java.util.Map;

import javax.annotation.Resource;



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @Resource(name="messages")
    private Map messages;
  
   
    @RequestMapping(value="/{messageId}")
    @ResponseBody
    public String getMessage(@PathVariable("messageId") String messageId)
    {
        return messages.get(messageId);
    }
}


3. Sample message.properties file under src/main/resources.

method0=This is method0
method1=This is method1
method2=This is method2
method3=This is method3
method4=This is method4
method5=This is method5
method6=This is method6
method7=This is method7
method8=This is method8
method9=This is method9

Thursday, June 22, 2017

Adding org.glassfish.jersey.archetypes in eclipse

You can solve this issue by adding a new Maven Archetype.
  1. Open Window > Preferences
  2. Open Maven > Archetypes
  3. Click Add Remote Catalog and add the following:
    • Catalog File: http://repo1.maven.org/maven2/archetype-catalog.xml
    • Description: maven catalog
  4. Restart eclipse
Try creating a maven project again. It will work :).
{search filter:jersey-quickstart-webapp}

You will have the latest version.

Sunday, June 11, 2017

HashMap – Single Key and Multiple Values Example

Sometimes you want to store multiple values for the same hash key. The following code examples show you 2 different ways to do this.


Scenario:

HashMap can be used to store key-value pairs.

But sometimes you may want to store multiple values for the same key.

For example:
For Key A, you want to store - Apple, Aeroplane

For Key B, you want to store - Bat, Banana

For Key C, you want to store – Cat, Car

The following code snippets will show you at least 2 different ways of storing key-value pairs with a distinction of Single Key and Multiple Values.

HashMap - Single Key and Multiple Values Using List

Sample Code Snippet:

private Map<String, List<String>> mapList;

mapList = new HashMap<String, List<String>>();

public void puStringList(String key, List stringList) {
      mapList.put(key, stringList);

}
    

public List getStringList(String key) {
        return mapList.get(key);

}

HashMap – Single Key and Multiple Values Using Google Guava Collections

Maven dependency for Google Guava Collections:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>


Sample Code Snippet:

private Multimap<String, String> multiMap;

multiMap = ArrayListMultimap.create();

public void putMultiMap(String key, String value) {
    multiMap.put(key, value);
   
}

public List<String> getMultiMap(String key) {
    return (List<String>) multiMap.get(key);
}


Full Code using a class Map2Multiple combining both 2 ways.


package com.map.utility;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Map2Multiple {
  
    private Map<String, List<String>> mapList;
    private Multimap<String, String> multiMap;
  
  
    public Map2Multiple() {
        mapList = new HashMap<String, List<String>>();
        multiMap = ArrayListMultimap.create();
    }
  
    public void puStringList(String key, List<String> stringList) {
        mapList.put(key, stringList);
    }
  
    public List<String> getStringList(String key) {
        return mapList.get(key);
    }
  
    public void putMultiMap(String key, String value) {
        multiMap.put(key, value);
      
    }
  
    public List<String> getMultiMap(String key) {
        return (List<String>) multiMap.get(key);
    }
  
    public void printAllMapList() {
        for(Map.Entry<String,List<String>> entry : mapList.entrySet())
        {
            System.out.println("key:    " + entry.getKey());
            System.out.println("Value:    " + entry.getValue());
        }
    }
  
    public void printAllMultiMap() {
        for(String key : multiMap.keySet())
        {
            System.out.println("key:    " + key);
            System.out.println("Value:    " + multiMap.get(key));
        }
      
    }

}

Test Map2Multiple from main method of Map2MultipleMain.


 package com.map.utility;

import java.util.Arrays;

public class Map2MultipleMain {

    public static void main(String[] args) {
        Map2Multiple maps = new Map2Multiple();
       
        maps.puStringList("A", Arrays.asList("Apple", "Aeroplane", "Army"));
        maps.puStringList("A", Arrays.asList("Angry", "Aeroplane", "Army"));
       
        System.out.println(maps.getStringList("A"));
       
        maps.putMultiMap("B", "Banana");
        maps.putMultiMap("B", "Bat");
        maps.putMultiMap("B", "Ball");
        maps.putMultiMap("B", "Ballon");
        maps.putMultiMap("C", "Cat");
        maps.putMultiMap("C", "Car");
        maps.putMultiMap("C", "Canada");
       
        System.out.println(maps.getMultiMap("Z"));
       
        maps.printAllMapList();
        maps.printAllMultiMap();

    }

}

Sunday, May 21, 2017

Spring MVC - Read Properties file

1. I've a Maven project.

2. I've created a properties file i.e. message.properties under resources folder.

3. My project structure snapshot is as follows:



4. Contents of message.properties:

index.page=home
salutation.page=welcome
salutation.text=Welcome to Spring MVC framework
name=MY NAME

5. base-package entry of servlet-context.xml is as follows: [All config files are here]

<context:component-scan base-package="com.controller" />

6. I'll use @PropertySource and @Value annotation.

7. I'll create a class with @PropertySource annotaion and a bean returning PropertySourcesPlaceholderConfigurer. This step is mandatory to retrieve values from properties file using @Value annotation.

package com.controller.utility;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySource("classpath:message.properties")
public class MessageUtil {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

8. Now values are available using @Value annotation from any class.

    @Value("${index.page}")
    public String INDEX;
  
    @Value("${salutation.page}")
    public String SALUTATION;
  
    @Value("${salutation.text}")
    public String SALUTATION_TEXT;
  
    @Value("${name}")
    public String name;

9. I've used these values in a controller class for request mapping.

    package com.controller.mapping;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HomeController {

    @Value("${index.page}")
    public String INDEX;
  
    @Value("${salutation.page}")
    public String SALUTATION;
  
    @Value("${salutation.text}")
    public String SALUTATION_TEXT;
  
    @Value("${name}")
    public String name;
  

  
    @RequestMapping(value={"/welcome", "/index"}, method={RequestMethod.GET, RequestMethod.POST})  
    public String salutation(Model model) {
        model.addAttribute("text", SALUTATION_TEXT);
        model.addAttribute("name", name);
      
        return SALUTATION;
    }
}

Thursday, May 11, 2017

Spring MVC Config - Put 3 files in WEB-INF folder

1. root-context.xml


<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
   
    <!-- Root Context: defines shared resources visible to all other web components -->
       
</beans> 



2. servlet-context.xml


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

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
  
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
  
    <context:component-scan base-package="com.quynguyenblog.springmvc.controller" />
  
</beans:beans>



3. web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>
  
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
      
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>