Sunday, February 19, 2012

JSF Tutorial (Event Listener) Part 3

We are now going to explore the Event Listener.


For this example, we are still referring to previous source code (Please refer to part 1 of the JSF tutorial to download the basic code structure and help you to get started): 


Below is the folder structure and the recent files that has been added for a more visualize presentation 


































New Files:


messages_fr.properties
==========================
hello.world.name=Name fr
hello.world.header=This is a simple Hello World example fr
hello.world.enter.name=Please enter your name fr
hello.world.select.language=Please select language fr
hello.world.location.param=Location fr: {0}
hello.world.title.login.page=Login Page fr
hello.world.btn.press.me=Press me fr


I just put additional string to be able to know if our simple example, has been successfully invoke, which in this case, I added the "fr" string at the end of every label


Modified files:
HelloWorld.java
package com.lai;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Locale;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;


@ManagedBean
@SessionScoped
public class HelloWorld implements Serializable{
        
    private ArrayList<SelectItem> localeLst; //variable for the list of locales
    private String selectedLanguage;
    
    /**
     * default empty constructor
     */
    public HelloWorld(){
    System.out.println("############# INITIALIZING ################");
    initialize();
    }
    
    private void initialize(){
    populateLocaleList();
    }


    //Helper Methods
    
    //Populate Locales
    private void populateLocaleList(){
    if(localeLst == null){
    localeLst =  new ArrayList<SelectItem>();
        localeLst.add(new SelectItem( "en", "English") );
        localeLst.add(new SelectItem( "de", "Germany") );
        localeLst.add(new SelectItem( "fr", "French") );
    }    
    }
       //Method to be called, once a new locale has been selected
public void changeLanguageEventListener(ValueChangeEvent e){
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(e.getNewValue().toString()));
}


    
    // -------------------
// -- getter & setter
// -------------------


public ArrayList<SelectItem> getLocaleLst() {
if(localeLst == null){
populateLocaleList();
}
return localeLst;
}


public void setLocaleLst(ArrayList<SelectItem> localeLst) {
this.localeLst = localeLst;
}


public String getSelectedLanguage() {
return selectedLanguage;
}


public void setSelectedLanguage(String selectedLanguage) {
this.selectedLanguage = selectedLanguage;
}    
}




helloWorld.xhtml
. . .
            <h:outputLabel for="name" value="#{msgs['hello.world.name']}" />
            <h:selectOneMenu value="helloWorld.selectedLanguage"
            onchange="submit()"
            valueChangeListener="#{helloWorld.changeLanguageEventListener}"
            >
            <f:selectItems value="#{helloWorld.localeLst}"
            var="c" itemLabel="#{c.key}" itemValue="#{c.value}"
            />
            </h:selectOneMenu>
. . .


faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    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-facesconfig_2_0.xsd"
    version="2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>messages</base-name>
<var>msgs</var>
</resource-bundle>
</application>

</faces-config>


Compile the source code by: mvn clean install
copy the new war file to the glassfish server
restart the server
URL: http://localhost:8080/prjJsf/helloWorld.faces


Output:








Using tag as the EventListener


helloWorld.xhtml
...


%lt;h:selectOneMenu value="#{helloWorld.selectedLanguage}"
            onchange="submit()"%gt;
%lt;f:valueChangeListener type="com.lai.HelloWorld"/%gt;
            %lt;f:selectItems value="#{helloWorld.localeLst}"
            var="c" itemLabel="#{c.key}" itemValue="#{c.value}"
        /%gt;
%lt;/h:selectOneMenu%gt;


...
Note that we emphasize the valueChangeListener as tag (f:valueChangeListener)


HelloWorld.java
. . .
import javax.faces.event.ValueChangeListener;

public class HelloWorld implements ValueChangeListener, Serializable{
    public void processValueChange(ValueChangeEvent e){
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(e.getNewValue().toString()));
}
. . .


We implements the ValueChangeListener interface.


After build and run, it will behave exactly the same, but just using different approach for the EventListener.

Wednesday, February 1, 2012

Regex matching tutorial

A simple program that will match the text enclosed on quote:


package embed;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTestStrings {
public static void main(String args[]) {
Pattern pat = Pattern.compile("\"[^\"]+\"");
String line = "Block 1, Block 2, \"Street 3, Block 3, Unit 3\", Block 4, \"Block 5, Unit 5\"";
Matcher mat = pat.matcher(line);

while (mat.find()){
System.out.println("Match: " + mat.group());
}
}
}


OUTPUT:
Match: "Street 3, Block 3, Unit 3"
Match: "Block 5, Unit 5"

Saturday, January 28, 2012

JSF Tutorial (I18N) Part 2

JSF Internationalization 


Based on our previous sample, we will now use the resourceBundle.












































We add new files(*.properties and faces-config.xml) for our resource bundle




faces-config.xml
     - Please pay special attention to the namespace, which uses the javaee, and the facesconfig, which is version 2.0
     - On this configuration, we define the resourceBundle that can be use within the whole application.
     - We define the default locale, and the variable to access the resourceBundle, which is the "msgs"



<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    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-facesconfig_2_0.xsd"
    version="2.0">
   
    <application>
    <locale-config>
             <default-locale>en</default-locale>
      </locale-config>
    <resource-bundle>
    <base-name>messages</base-name>
    <var>msgs</var>
    </resource-bundle>
    </application>
</faces-config>


messages.properties

hello.world.name=Name
hello.world.header=This is a simple Hello World example
hello.world.enter.name=Please enter your name
hello.world.select.language=Please select language

hello.world.location.param=Location: {0}
hello.world.title.login.page=Login Page
hello.world.btn.press.me=Press me



helloWorld.xhtml
. . .
<h:outputLabel for="name" value="#{msgs['hello.world.enter.name']}" />
. . .

<!-- Passing Parameter to messageBundle -->
 <h:outputFormat value="#{msgs['hello.world.location.param']}" >
     <f:param value="Singapore"/>
 </h:outputFormat>





Build the project, and restart the server

JSF Tutorial (Getting Started) Part 1

Getting Started on JSF Tutorial Part 1


Technologies:
- Glassfish3 server
- Maven 2
- Java 1.6.0_24
- IDE: eclipse


Folder Structure:










































Notice that we have .jsp and .xhtml file


Below are the codes:
web.xml
     - Please pay special attention to the declaration of namespace. The version of web-app is 2.5 and the xmlns namespace is javaee


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


    <description>JSF Tutorial Project</description>
    <!--optional: context-param>
        <description>Comma separated list of URIs of (additional) faces config files.
            (e.g. /WEB-INF/my-config.xml)
            See JSF 1.0 PRD2, 10.3.2
            Attention: You do not need to put /WEB-INF/faces-config.xml in here.
        </description>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/examples-config.xml</param-value>
    </context-param-->   


    <!-- Faces Servlet -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Faces Servlet Mapping -->
       <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>    
    <!-- Welcome files -->
    <welcome-file-list>
        <welcome-file>helloWorld.xhtml</welcome-file>
    </welcome-file-list>
</web-app>


HelloWorld.java
     - A Managed Bean that holds the value for the property "name".
     - Since we are using the JSF 2.0, we can use the annotation to specify the Managed Bean. This can be done by declaring @ManagedBean at the top of the class name


package com.lai;


import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


@ManagedBean
@SessionScoped
public class HelloWorld implements Serializable{    
    //properties
    private String name;    
    /**
     * default empty constructor
     */
    public HelloWorld(){
    }    
    //-------------------getter & setter
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }    
    /**
     * Method that is backed to a submit button of a form.
     */
    public String send(){
        //the welcomePage is the name of our .xhtml file. If we didnt specify the faces-config.xml, we can use 
    //the approach of specifying the .xhtml or .jsp page name
        return "welcomePage";
    }

    public String sendJsp(){
        //for jsp page
        return "welcomePage2";
    }
}


helloWorld.xhtml
     - You can use the implicit navigation on the commandButton, by specifying the name of the jsp page, or you can call the HelloWorld class to do this:


HelloWorld.java
public void send(){
   return "welcomePage";
}
OR
helloWorld.xhtml
<h:commandButton value="Press me" action="welcomePage"/>


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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">
    <h:head>
        <title>Hello World</title>
    </h:head>
    <h:body>
        <f:view>
            <h:form id="mainForm">
              <h:panelGrid columns="2">
                <h:outputLabel for="name" value="Please enter your name" />
                <h:inputText id="name" value="#{helloWorld.name}" required="true"/>
                <h:commandButton value="Press me" action="#{helloWorld.send}"/>
                <h:messages showDetail="true" showSummary="false"/>
              </h:panelGrid>
            </h:form>
        </f:view>
    </h:body>
</html>


welcomePage.xhtlm
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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">
    <h:head>
        <title>Hello World</title>
    </h:head>
    <h:body>
        <f:view>
            <h:form id="mainForm">
                <h2><h:outputText value="Hello #{helloWorld.name}. We hope you enjoy Apache MyFaces"/></h2>
                <h:commandLink action="back">
                    <h:outputText value="Home"/>
                </h:commandLink>
            </h:form>
        </f:view>
    </h:body>
</html>


pom.xml
     - This will download the required dependencies on our startup JSF project


<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lai</groupId>
<artifactId>prjJsf</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>A custom project using myfaces 1.2</name>
<url>http://maven.apache.org</url>


<repositories>
<repository>
<id>java.net.m2</id>
<name>java.net m2 repo</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>


<build>
<finalName>prjJsf</finalName>


<!-- Specify to the compiler that we are using Java version 1.6 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>


<!-- Project dependencies -->
<dependencies>


<!-- http://download.java.net/maven/2 -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.0-b03</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.0-b03</version>
</dependency>


<!-- http://repo1.maven.org/maven -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>


<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>


<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>


<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>



helloWorld2.jsp
     - For this jsp page, we just change the title and the action
<html>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <head>
        <title>Hello World Using JSP</title>
    </head>
    <body>
        <f:view>
            <h:form id="mainForm">
              <h:panelGrid columns="2">
                <h:outputLabel for="name" value="Please enter your name" />
                <h:inputText id="name" value="#{helloWorld.name}" required="true"/>
                <h:commandButton value="Press me" action="#{helloWorld.sendJsp}"/>
                <h:messages showDetail="true" showSummary="false"/>
              </h:panelGrid>
            </h:form>
        </f:view>
    </body>
</html>


welcomePage2.jsp
     - same as this jsp page, the difference is just the title
<html>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <head>
        <title>Hello World Using JSP</title>
    </head>
    <body>
        <f:view>
            <h:form id="mainForm">
                <h2><h:outputText value="Hello #{helloWorld.name}. We hope you enjoy Apache MyFaces"/></h2>
                <h:commandLink action="helloWorld">
                    <h:outputText value="Home"/>
                </h:commandLink>
            </h:form>
        </f:view>
    </body>
</html>


to browse:
1. copy the prjJsf.jar to <glassfishDir>/domains/domain1/autodeploy directory
2. start the glassfish server <glassfishDir>/bin/startserv.bat
3. browse the url: 
http://localhost:8080/prjJsf/helloWorld.faces to browse the .xhtml file
OR

http://localhost:8080/prjJsf/helloWorld2.faces to browse the jsp page



Download Link: https://docs.google.com/open?id=0B4SJ4_bXuR4ONzAyZWY4NDMtMDljZC00YWNiLWJkMGItMGQwMzUyZjhjYjQw

Monday, January 16, 2012

My Wedding Song List

Its just fun to list your favorite songs and hopefully to be able to play that on your big day. I just want to list so I will always remember

1. A thousand Years - Christina Perri
2. Flightless Bird - American Mouth
3. Marry You - Glee / Bruno Mars version mashup

Timeline Starts Now

This day, January 16, 2012, I will monitor what I want to achieve
For this year, I want to achieve these things:

1. Complete my TODO study list
2. Lose weight, by diet and exercise daily
3. 3 certifications for this year
4. Be able to become part by part knowledgeable on stocks first (other investment on next year)
5. lovelife :p 

I will start to log my daily progress for each day!

If I did accomplish something good for 6 months, I will reward myself :)
Hopefully, I will be ready for my 1st target certification by 3rd Week of April or 3rd Week of May

Currently, I'm prioritizing my todo list and losing weight :D

Wednesday, December 7, 2011

Random thought

Its weird seeing your future with someone who doesn't show interest on you.
This is the first time it happens to me. I have crushes and BFs before, but I didn't see my future with them, that's why Its really weird.
Oh well, I hope he also thinks of me :D