Add the following piece of XML to your pom.xml:

	<repositories>
		<repository>
			<id>jdk14</id>
			<name>Repository for JDK 1.4 builds</name>
			<url>http://www.myhost.com/maven/jdk14</url>
			<layout>default</layout>
			<snapshotPolicy>always</snapshotPolicy>
		</repository>

		<repository>
			<id>Atlassian</id>
			<name>Atlassian repository</name>
			<url>https://maven.atlassian.com/repository/public</url>
		</repository>

		<repository>
			<id>Apache m2 iBiblio archived</id>
			<name>Apache m2 iBiblio archived repository</name>
			<url>http://people.apache.org/repo/m2-ibiblio-archived/</url>
		</repository>

		<repository>
			<id>JBoss</id>
			<name>JBoss repository</name>
			<url>https://repository.jboss.org/nexus/content/groups/public-jboss</url>
		</repository>

		<repository>
			<id>JBOSS</id>
			<name>JBoss Repository</name>
			<url>http://repository.jboss.org/maven2/</url>
		</repository>

		<repository>
			<id>jboss-snapshot</id>
			<url>http://snapshots.jboss.org/maven2</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>nexus</id>
			<url>https://repository.jboss.org/nexus/content/repositories/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>maven-central</id>
			<url>http://repo2.maven.org/maven2/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>EBR</id>
			<url>http://www.springsource.com/repository</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>jboss-plugins</id>
			<url>http://repository.jboss.com/maven2</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
		<pluginRepository>
			<id>jboss-snapshot-plugins</id>
			<url>http://snapshots.jboss.org/maven2</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>
 

[Tip] Problem with valueChangeListener

On March 16, 2011, in JSF, JSF 2.0, by lucasterdev

When using the valueChangeListener attribute, you have to keep in mind that the method registered as valueChangeListener is invoked before the new value is set.

 

JSF: How to find a component in the view root

On March 15, 2011, in JSF, by lucasterdev

Use the following functions. (All the credit goes to mert)

public static UIComponent findComponentInRoot(String id) {
    UIComponent component = null;

    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (facesContext != null) {
      UIComponent root = facesContext.getViewRoot();
      component = findComponent(root, id);
    }

    return component;
}

public static UIComponent findComponent(UIComponent base, String id) {
    if (id.equals(base.getId()))
      return base;

    UIComponent kid = null;
    UIComponent result = null;
    Iterator kids = base.getFacetsAndChildren();
    while (kids.hasNext() && (result == null)) {
      kid = (UIComponent) kids.next();
      if (id.equals(kid.getId())) {
        result = kid;
        break;
      }
      result = findComponent(kid, id);
      if (result != null) {
        break;
      }
    }
    return result;
}
 

In a previous post I showed you how to add Spring Security to your application.
In this continuation I’m going to show how to integrate JSF and Spring Security 3.
At the end, we’ll have a custom JSF login page.
The login page will continue to be shown until a successful authentication will occur.
Spring Security’s authentication error exception will be displayed as a JSF h:messages in the login page itself.

Our login page:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="c_rt" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>

<html>
    <head>
        <title>Spring Security Login</title>
    </head>
	<body>
		<f:view >
		    <h:form >
		        <h:panelGrid columns="2">
		            <h:outputLabel value="User Name" for="j_username"/>
		            <h:inputText id="j_username"
		                           value="#{loginBean.username}"
		                           required="true"/>
		            <h:outputLabel value="Password" for="j_password"/>
		            <h:inputSecret id="j_password"
		                             value="#{loginBean.password}"
		                             required="true"/>
		        </h:panelGrid>
		        <h:commandButton action="#{loginBean.doLogin}" value="Login"/>
		        <h:messages style="color: red;"/>
		    </h:form>
		</f:view>
    </body>
</html>

How our login page will look like:

Changes to be made to web.xml:

	<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>
		 <dispatcher>FORWARD</dispatcher>
		 <dispatcher>REQUEST</dispatcher>
	</filter-mapping>

The backing bean LoginBean.java:

package com.tutorial.backingbeans;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.tutorial.util.FacesUtils;

public class LoginBean {

	private String username;
	private String password;

	public LoginBean() {
	}

	public String doLogin() throws IOException, ServletException {
		ExternalContext context = FacesContext.getCurrentInstance()
				.getExternalContext();

		RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
				.getRequestDispatcher("/j_spring_security_check?j_username=" + username
								+ "&j_password=" + password);

		dispatcher.forward((ServletRequest) context.getRequest(),
				(ServletResponse) context.getResponse());

		FacesContext.getCurrentInstance().responseComplete();
		// It's OK to return null here because Faces is just going to exit.
		return null;
	}

	public String getPassword() {
		return password;
	}

	public String getUsername() {
		return username;
	}

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

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

Changes to be made to applicationContext-secutiry.xml:

		<form-login
			login-page="/login.jsf"
			default-target-url="/loginSuccess.jsp"
			/>

LoginErrorPhaseListener.java:
This listener will capture Spring Security’s exceptions and show them in the login page as JSF messages.

package com.tutorial.listener;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AbstractProcessingFilter;

import com.tutorial.util.FacesUtils;

public class LoginErrorPhaseListener implements PhaseListener
{
    private static final long serialVersionUID = -1216620620302322995L;

    @Override
    public void afterPhase(final PhaseEvent arg0)
    {}

    @Override
    public void beforePhase(final PhaseEvent arg0)
    {
        Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(
                AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

        if (e instanceof BadCredentialsException)
        {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
                    AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, null);
            FacesUtils.addErrorMessage("Username or password not valid.");
        }
    }

    @Override
    public PhaseId getPhaseId()
    {
        return PhaseId.RENDER_RESPONSE;
    }

}

We have to add this listener to faces-config.xml:

 <lifecycle>
  <phase-listener>com.tutorial.listener.LoginErrorPhaseListener</phase-listener>
 </lifecycle>

FacesUtils.java

package com.tutorial.util;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class FacesUtils {

	public static void addErrorMessage(String msg) {
		addMessage(FacesMessage.SEVERITY_ERROR, msg);
	}

	private static void addMessage(FacesMessage.Severity severity, String msg) {
		final FacesMessage facesMsg = new FacesMessage(severity, msg, msg);
		FacesContext.getCurrentInstance().addMessage(null, facesMsg);
	}

	public static void addSuccessMessage(String msg) {
		addMessage(FacesMessage.SEVERITY_INFO, msg);
	}

	public static String getBundleKey(String bundleName, String key) {
		return FacesContext
				.getCurrentInstance()
				.getApplication()
				.getResourceBundle(FacesContext.getCurrentInstance(),
						bundleName).getString(key);
	}

}
 

If you get the following error ater installing Drupal:

Unable to send e-mail. Please contact the site administrator if the problem persists.

Install sendmail:

sudo apt-get install sendmail

Edit php.ini:

I configured it to ouse Gmail’s smtp server.

sudo gedit /etc/php5/apache2/php.ini

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
; http://php.net/smtp-port
smtp_port = 465

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = /usr/sbin/sendmail -t
sendmail_from = me@myserver.com

 

How to install Apache+MySQL+PHP in Ubuntu 10

On March 4, 2011, in Apache, MySQL, PHP, Ubuntu, by lucasterdev

1. Install MySQL

sudo apt-get install mysql-client mysql-server

2. Install Apache2

sudo apt-get install apache2

Now go to http://localhost and you should see the following:

3. Install support for PHP

sudo apt-get install php5 libapache2-mod-php5

4. Restart Apache

sudo /etc/init.d/apache2 restart

5. Install php5-mysql and other useful stuff

sudo apt-get install php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-mhash php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-json

6. Restart Apache

sudo /etc/init.d/apache2 restart

7. Install phpmyqdmin

sudo apt-get install phpmyadmin

WARNING! You must select apache2 when requested, by pressing the space-bar and make sure there is a '*' next to apache2!!!! Otherwise phpmyadmin will install in another folder.

8. Restart Apache

sudo /etc/init.d/apache2 restart

Apache will start automatically when you boot your computer.

The commands to controll Apache are te following:

sudo /etc/init.d/apache2 start
sudo /etc/init.d/apache2 restart
sudo /etc/init.d/apache2 stop

To change Apache’s default port:

sudo gedit /etc/apache2/ports.conf

and change Listen 80 to Listen 79, for instance. Then, restart Apache:

sudo /etc/init.d/apache2 restart
 

JMS in JBoss AS 6

On March 1, 2011, in JBoss, JBoss 6, JMS, by lucasterdev

JBoss AS 6 is bundled with HornetQ, a Java Messaging service provider.

It already has some ready-to-use queues and connection factories. You can view their list in $JBOSS_HOME/server/default/deploy/hornetq/hornetq-jms.xml.

Here is a basic example of message sender and message receiver. It’s a corrected version of the example you can find in the JMS Tutorial 1.3.

I had the whole JBoss Runtime Library in my classpath.

To run the example, right-click on the .java files and select “Run As” –> “Java Application”.

If you go to http://localhost:8080/admin-console and browse the tree on the left, you’ll find jms.queue.ExpiryQueue. This will open the page relative to the queue used in this example. From there, you can observe the number of messages currently held in this queue awaiting delivery.

Also, keep an eye on Eclipse’s Console. Use the second button from the right (Display Selected Console) To cycle through the outputs of the two programs.

package com.jms.myexample;

import java.util.Properties;

import javax.jms.*;
import javax.naming.*;

public class SimpleQueueReceiver {
	/**
	 * Main method.
	 *
	 * @param args
	 *            the queue used by the example
	 */
	public static void main(String[] args) {

		String queueName = "/queue/ExpiryQueue";
		String connectionFactoryName = "/ConnectionFactory";
		Context jndiContext = null;
		QueueConnectionFactory queueConnectionFactory = null;
		QueueConnection queueConnection = null;
		QueueSession queueSession = null;
		Queue queue = null;
		QueueReceiver queueReceiver = null;
		TextMessage message = null;

		Properties props = new Properties();
		props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming.client");
		props.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
		props.setProperty("j2ee.clientName", "SimpleQueueReceiver"); 

		/**
		 * Display the queue name.
		 */
		System.out.println("Queue name is " + queueName);

		/**
		 * Create a JNDI API InitialContext object if none exists yet.
		 */
		try {
			jndiContext = new InitialContext(props);
		} catch (NamingException e) {
			System.out.println("Could not create JNDI API " + "context: " + e.toString());
			System.exit(1);
		}

		/**
		 * Look up connection factory and queue. If either does not exist, exit.
		 */
		try {
			queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup(connectionFactoryName);
			queue = (Queue) jndiContext.lookup(queueName);
		} catch (NamingException e) {
			System.out.println("JNDI API lookup failed: " + e.toString());
			System.exit(1);
		}

		/**
		 * Create connection.
		 * Create session from connection; false means session is not transacted.
		 * Create receiver, then start message delivery.
		 * Receive all text messages from queue until a non-text message is received indicating end of message stream.
		 * Close connection.
		 */
		try {
			queueConnection = queueConnectionFactory.createQueueConnection();
			queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			queueReceiver = queueSession.createReceiver(queue);
			queueConnection.start();
			while (true) {
				Message m = queueReceiver.receive(1);
				if (m != null) {
					if (m instanceof TextMessage) {
						message = (TextMessage) m;
						System.out.println("Reading message: " + message.getText());
					} else {
						System.out.println("Received end-of-messages message.");
						break;
					}
				}
			}
		} catch (JMSException e) {
			System.out.println("Exception occurred: " + e.toString());
		} finally {
			if (queueConnection != null) {
				try {
					queueConnection.close();
				} catch (JMSException e) {
				}
			}

		}
		System.out.println("Receiver: exiting.");
	}
}
package com.jms.myexample;

/**
 * The SimpleQueueSender class consists only of a main method,
 * which sends several messages to a queue.
 *
 * Run this program in conjunction with SimpleQueueReceiver.
 * Specify a queue name on the command line when you run the
 * program. By default, the program sends one message. Specify
 * a number after the queue name to send that number of messages.
 */
import java.util.Properties;

import javax.jms.*;
import javax.naming.*;

public class SimpleQueueSender {
	/**
	 * Main method.
	 *
	 * @param args
	 *            the queue used by the example and, optionally, the number of
	 *            messages to send
	 */
	public static void main(String[] args) {

		String queueName = "/queue/ExpiryQueue";
		String connectionFactoryName = "/ConnectionFactory";
		final int NUM_MSGS = 5;
		Context jndiContext = null;
		QueueConnectionFactory queueConnectionFactory = null;
		QueueConnection queueConnection = null;
		QueueSession queueSession = null;
		Queue queue = null;
		QueueSender queueSender = null;
		TextMessage message = null;

		Properties props = new Properties();
		props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming.client");
		props.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
		props.setProperty("j2ee.clientName", "SimpleQueueSender"); 

		/**
		 * Display the queue name.
		 */
		System.out.println("Queue name is " + queueName);

		/**
		 * Create a JNDI API InitialContext object if none exists yet.
		 */
		try {
			jndiContext = new InitialContext(props);
		} catch (NamingException e) {
			System.out.println("Could not create JNDI API " + "context: " + e.toString());
			System.exit(1);
		}

		/**
		 * Look up connection factory and queue. If either does not exist, exit.
		 */
		try {
			queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup(connectionFactoryName);
			queue = (Queue) jndiContext.lookup(queueName);
		} catch (NamingException e) {
			System.out.println("JNDI API lookup failed: " + e.toString());
			System.exit(1);
		}

		/**
		 * Create connection.
		 * Create session from connection; false means session is not transacted.
		 * Create sender and text message. Send messages, varying text slightly.
		 * Send end-of-messages message.
		 * Finally, close connection.
		 */
		try {
			queueConnection = queueConnectionFactory.createQueueConnection();
			queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			queueSender = queueSession.createSender(queue);
			message = queueSession.createTextMessage();
			for (int i = 0; i < NUM_MSGS; i++) {
				message.setText("This is message " + (i + 1));
				System.out.println("Sending message: " + message.getText());
				queueSender.send(message);
			}
			/**
			 * Send a non-text control message indicating end of messages.
			 */
			System.out.println("Sending end-of-messages message");
			queueSender.send(queueSession.createMessage());
		} catch (JMSException e) {
			System.out.println("Exception occurred: " + e.toString());
		} finally {
			if (queueConnection != null) {
				try {
					queueConnection.close();
				} catch (JMSException e) {
				}
			}
		}
		System.out.println("Sender: exiting.");
	}
}