Populating JSF Combo Box with Database values. (or drop down list)…

I am presently working on my AISD project, and i am using jsf(primefaces) spring and jpa to build the system. i would like to commend the efforts of the brains behind jsf 2.0 and primefaces (1.* and 2.*) :) in particular for making the life of java web devs much easier. I remember back in the days the first versions of jsf were simply nightmares, which lead my cohorts and i  to move to frameworks like wicket :) .

This blog post seeks to show how to populate a jsf Combo box with values from a database table and also you would notice that the implementation for this case includes both jsf 1.* and jsf 2.*. I assume some familiarity with spring jpa and jsf.

Most relational database records have a primary key to uniquely identify it. This key appears on other tables as foreign keys. In my application i needed to display one or more of the attributes of a record from a table on a form and persist its unique identifier .

Below i provide some sample code that gives some hint on how this can be achieved using plain old java objects..

First lets paint the screen.. For JSF 1.*:


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.myModelValues}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

For JSF 2.* this is even easier (thanks to Çağatay Çivici the primefaces lead for pointing this out to me :) ):


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.mlist}" var="model" itemLabel="#{model.modelvalue}" itemValue="#{model.modelId}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

Next lets define the backing page bean… For JSF 1.* this is ok :

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private Map<String, String> myModelValues = new HashMap<String, String>();
private List<Model> mList;
public PageBean(){
}

 @Autowired
public PageBean(ModelService modelService){
this. modelService = modelService;
        mList = modelService.findAll();
        for (Model m : mList) {
            myModelValues.put(m.getmyModelValue(), m.getmyModelId());
     }
}
public Map<String, String> getMyModelValues() {
return myModelValues;
    }
public void setMyModelValues(Map<String, String> myModelValues) {
this.myModelValues= myModelValues;
 }
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

For JSF 2.* it is even better => You don’t need  use a Map or Hash Map as the case may be above (thanks to Çağatay Çivici the primefaces lead for pointing this out ):

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private List<Model> list;
public PageBean(){
}

@Autowired
public PageBean(ModelService modelService){
        this. modelService = modelService;
        list = modelService.findAll();
}

public List<Model> getList() {
	return list;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

Below is a service interface to define the the findAll method:

public interface ModelService {

public List< Model> findAll();
}

Next the implementation for the Model Service Interface:


@Service("modelService")
public ModelServiceImpl implements ModelService  {
private ModelDAO modeldao;
@Autowired
public ModelServiceImpl(ModelDAO modeldao) {
        this. modeldao = modeldao;
    }
    @Transactional(readOnly = true)
    public List<Model> findAll() {
        return modeldao.findAll();
    }
}

The Data Access object interface:

public interface ModelDAO {

public List< Model> findAll();
}

The Data Access object implementation proper:

@Repository
public class ModelDAOImpl implements ModelDAO {

    @PersistenceContext
    protected EntityManager entityMgr;

    public EntityManager getEntityMgr() {
        return entityMgr;
    }

    public void setEntityMgr(EntityManager entityMgr) {
        this.entityMgr = entityMgr;
    }

    public List<Model> findAll() {
        Query query = entityMgr.createNamedQuery("Model.findAll");
        return query.getResultList();
    }
}

Finally lets define the jpa model object:

@Entity
@Table(name = "MODEL")
@NamedQuery(name = "Model.findAll", query = "SELECT m FROM Model m") // this query returns distinct values from the database.
public class Model implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "MODEL_ID")
    private String modelId;
    @Basic(optional = false)
    @Column(name = "MODEL_VALUE")
private String modelValue;
 public Model() {
    }
 public Model(String modelId, String modelValue) {
this.modelId = modelId;
this.model = modelValue;
}
 public String getModelId() {
        return modelId;
    }

    public void setModelId(String modelId) {
        this.modelId = modelId;
    }

    public String getModelValue() {
        return modelValue;
    }

    public void setModelValue(String modelValue) {
        this. modelValue = modelValue;
    }
    }

The code above steps through it all… Ciao for now..

Configuring Spring Security..

Over the years web application security has continued to be a critical issue. This area of concern is a major source of worry for most enterprise application developers. We as software developers, are faced with the task of securing valuable data that exist within our applications. This data could vary from  email account secured with a username / password pair or a brokerage account secured with a trading PIN, protecting an application is a important aspect of most applications, if not all.  (Walls C., 2007).

According to Craig Walls (2007, pg 248), Security is a concern that transcends an application’s functionality. For the most part, an application should play no part in securing itself. Although you could write security functionality directly into your application’s code (and that’s not uncommon), it is better to keep security concerns separate from application concerns.

One of the popular options for the enterprise java world is spring’s security framework (formerly Acegi).

Craigs Walls in his spring in action book defined spring security as  “a security framework that provides declarative security for your Spring-based applications.”

In this blog post, I intend to share my personal experience configuring spring security.

Firstly there are a few requirements (jars). you will need to define the following in your maven pom.xml file.

<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core-tiger</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-taglibs</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-acl</artifactId>
 <version>2.0.4</version>
 </dependency>
<dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.5.4</version>
 </dependency>

Next task is configuring the Web.xml file:


 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 classpath:applicationContext.xml
 </param-value>
 </context-param>

 <listener>
 <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class>

 </listener>

 <filter>
 <filter-name>springSecurityFilterChain</filter-name>
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
 <filter-name>springSecurityFilterChain</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

Every Spring application requires an applications context, this is a primary requirement of all spring based applications, this is a trimmed down version focusing on the topic of this blog post.

<?xml version="1.0" encoding="MacRoman"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
<context:component-scan base-package="com.example" />
<security:http auto-config='false'>
<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/login.jsp" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_USER" filters="none" />
<security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" />
<security:concurrent-session-control max-sessions="1"/>
<security:logout logout-url="/logout" logout-success-url="/"/>
</security:http>
<security:authentication-provider>
<security:password-encoder hash="md5" />
<security:user-service>
<security:user name="ikenna" password="3d801aa532c1cec3ee82d87a99fdf63f" authorities="ROLE_USER" />
<security:user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER" />
<security:user name="test" password="098f6bcd4621d373cade4e832627b4f6" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</beans>

Finally the login.jsp page. This page hold the form tags and should be placed in the root of the webapps foilder.

<%@page contentType="text/html" pageEncoding="MacRoman"%>
<%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt' %>
<%@ page import="org.springframework.security.ui.AbstractProcessingFilter" %>
<%@ page import="org.springframework.security.ui.webapp.AuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.AuthenticationException" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <title> Login Page</title>
 <link href="<c:url value="includes/stylesheets/main.css" />" media="screen"  rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/calendar.css" />" media="screen" rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/forms.css" />" media="screen" rel="Stylesheet" type="text/css" />
 </head>
 <body>
 <h1>Login </h1>
<c:if test="${not empty param.login_error}">
 <font color="red">
 Your login attempt was not successful, try again.<br/><br/>
 Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
 </font>
 </c:if><br><br>
 <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST">
 <fieldset>
 <legend>Log In Form</legend> <hr>
 <ol>
 <li><label for="login">Username:</label>
 <input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/>
 </li>
 <li>
 <label for="password">Password:</label>
 <input type='password' name='j_password'/>
 </li>
 <li>
 <label for="remember_me">Remember me:</label>
 <input type="checkbox" name="_spring_security_remember_me">
 </li>
 </ol>
 <div>
 <input name="reset" type="reset" value="Reset"  onclick="return confirm('Are you sure you want to Clear or Reset this form');">
 <input name="submit" type="submit" value="Log In">
 </div>
 </fieldset>
 </form
 </div>
</body>
</html>

One thing though, I struggled with is spring security not by passing the resources (*.js, *.css, and images etc..) declared the head section of my login.jsp file.

I noticed Spring security takes into account all the resources that are declared in the *.jsp pages and will atempt to display the last resource it remembered (declared in the login.jsp page).Also modern browsers request for the favicon.ico file from the web pages, I notice spring security required me to let it know that the resources should not be a priority to it.

I would suggest copying all your *.js, *.css, and images etc.. in to one folder (includes) and then declare the folder as IS_AUTHENTICATED_ANONYMOUSLY also setting the filters off.

<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />

REFERENCE:
Walls C., Breidenbach R. 2007. Spring in Action Second Edition, Manning Publishers.

Using the Wicket Framework to Update style tag.

In this post, Wicket Framework is used to update the embedded style tag.

An already working sample can be found here.

Let’s begin by configuring the web application (i.e. web.xml)


<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<display-name>CSS and Wicket</display-name>
<filter>
<filter-name>css_wicket</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>com.jw.ike.pages.CssApplication</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>css_wicket</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

 

The wicket application class go as follows:


public class CssApplication extends WebApplication {

public CssApplication() {
}

public Class getHomePage() {
return CssDemo.class;
}

}

The getHomePage() method returns this Page:

public class CssDemo extends WebPage implements Serializable {
	private String uStyle;

	public CssDemo() {
		add(new Label("style"));
		add(new CssForm("addform"));

	}

	public CssDemo(String userStyle) {
		this.uStyle = userStyle;
		this.add(new Label("style", new PropertyModel(this, "uStyle")));
add(new CssForm("addform"));

	}

}

And the accompanying HTML web page is:

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="../css/style/style.css">
<title>Wicket Updating Style Sheet</title>
<style type="text/css" wicket:id="style"></style>
</head>
<body>

<div id="bmain">
<form wicket:id="addform">
<h2>Update Style Sheet...</h2>

<span>Select Pre-Defined CSS Rules </span>

<select wicket:id="combo">

</select>

<textarea id="ta" wicket:id="txta" rows="20" cols="60"> rich text </textarea>

<input id="btn" type="submit" value="::Post Style Sheet::"></form>
<a href="http://wicket.apache.org/" >
<img id="logo" alt="Wicket" src="../images/wicket-logo.png" border="0" width='111' height="155"/></a>

</div>

<div id="side">

<h1>Change Me @!#%.</h1>

 </div>
</body>
</html>

And then the Form Class:


public class CssForm extends Form {

private String style1 = "Choose a style";
private String style2 = "h1{ font-size: 4.0em; font-family: Mistral; color: #dc512b; border:10px solid #bb342d; background-color: #098762;text-align: center;}";
private String style3 = "h1{ font-size: 5.0em; font-family: Comic Sans MS; color: #0066CC; border:10px solid #330066; background-color: green;text-align: center;}";
private String style4 = "h1{ font-size: 6.0em; font-family: Curlz MT; color: #CCFFFF; border:10px solid #445698; background-color: #6666CC;text-align: center;}";

private static String css;
private List cssList;
private String selectedCss = style1;
private DropDownChoice dropDownMenu;
private TextArea textArea;

public CssForm(String componentid) {
super(componentid);

cssList = Arrays.asList(new String[]{style1, style2, style3, style4});

dropDownMenu = new DropDownChoice("combo", new PropertyModel(this, "selectedCss"),
     cssList) {

 @Override
 protected void onSelectionChanged(Object newSelection) {

     textArea.setModelObject(newSelection);

 }

 @Override
 protected boolean wantOnSelectionChangedNotifications() {

     return true;
 }

};
add(dropDownMenu);

textArea = new TextArea("txta", new PropertyModel(this, "css"));

add(textArea);

}

@Override
protected void onSubmit() {
String definedCssRule =  textArea.getModelObject().toString();
definedCssRule = "\n\n\n" + definedCssRule + "\n\n\n";
setResponsePage(new CssDemo(definedCssRule));
textArea.setModelObject(null);
}
}

The External Style Sheet :


body {
	background-image: url("../images/cl.jpg");
	background-repeat: no-repeat;
}

h1 {
	font-size: 4.5em;
	color: #4088b8;
	margin: -300px 0 0 0;
	position: relative;
	left: -20px;
	top: 10px;
	position: relative
}

h2 {
	color: #4088b8;
}

span {
	font-size: 1.0em;
	color: #4088b8;
	padding:0 33px 0 2px;
}

#logo {
	position: relative;
	left: 0px;
	top: 50px;
	z-index: 1;
}
select {

	position: relative;
	left: 0px;
	bottom: 2px;
	width: 230px;
}

#jw {
	position: relative;
	left: 900px;
	top: -50px;
	z-index: 1;
}

#bmain {
	width: 510px;
	margin: 10px 0 0 0;
	position: inherit;
}

#side {
	float: right;
	width: 600px;
	margin: -150px 0 0 0;
	padding: 1px 0 0 0;
}

#ta {
	padding: 0 20px 0 0;
}

#btn {
	background-color: #4088b8;
	border-color: 4088b8;
	color: white;
	position: relative;
	left: 180px;
	top: 50px;
}

 

2002 – Can’t connect to local MySQL server through socket ‘/var/mysql/mysql.sock’

Today, i stopped being a fan of MAMP for integrating PHP Apache and MYSQL, and i decided to setup Apache, MYSQL and PHP stack on my MAC OS X 10.5.7 (leopard) the good old way…


But, i encountered this error: 2002 – Can’t connect to local MySQL server through socket ‘/var/mysql/mysql.sock’ (2).

Wow… i then discovered funny enough, that MYSQL instance was running perfectly and i was able to connect MYSQL
via the MYSQL Admin GUI tool.

I made a lucky guess asserting, that the PHP config file may be missing some info, Hmmm…

Well the solution goes as follows:

I searched for “mysql.lock” and i discovered that the MYSQL Socket file was located in “/tmp/mysql.lock.

Also, in the my PHP.ini file the value formysql.default_socket” was entirely empty “”.

ehhhh… Run this command in Terminal to view hidden files “defaults write com.apple.finder AppleShowAllFiles TRUE” and then followed by “killall Finder”.

Then Go to “private/etc/PHP.ini”. (note: private is a hidden folder).

If prior to this, in “private/etc/ “folder, the PHP.ini file does not exist copy and paste it there first.

Now open the PHP.ini file with say BBedit or TextWrangler.

Use command + F to find “mysql.default_socket” and paste “/tmp/mysql.sock” as it’s new value.

Finally restart your Apache web server with Terminal using “sudo apachectl graceful”.

After restart, PHP will be able to make connection calls to MYSQL with no further a do or hassle.

Web Development Principles

Recently, i came across my lecture note which covered rules that make a web site design excellent, this was a lecture given by Mr. Denver Reynolds.

It states clearly that >>>>>

  • Content is king: Users would visit a site for information. Without information the raison d’etre of the site is non-existent.
  • User orientated design: If the site design is not focused around the user and facilitating their ease of use the site can appear cumbersome and awkward to use.
  • Low click depth: Every part of the site should be accessible in just a few clicks of the mouse (ideally 3 or less). This makes the site easy to navigate and find information for the users.
  • 6 second rule: The web page should have loaded into the browser within 6 seconds. This is generally the maximum amount of time a visitor would invest in the site without receiving any return in the form of information.
  • Page consistency: The page design should appear consistent and coherent, thus signifying the site as a unified whole etc.